0

I am currently trying to make a program that will print if variable a is divisible by variable b. I keep running into errors when trying to print the values a and b.

My code:

a, b = eval(input('Input a list of 2 numbers: '))
a = str(a)
b = str(b)
if (a % b == 0):
    print ( a + 'is divisible by' + b)
else:
    print( a + 'is not divisible by' + b)

Error message:

Traceback (most recent call last): File "C:/Users/Noah/Documents/Python/Assignment 4 Question 7.py", line 4, in if (a % b == 0): TypeError: not all arguments converted during string formatting

1
  • I modified the code according to your answers, and am now getting an error on line 5. TypeError: unsupported operand type(s) for +: 'int' and 'str' Commented Oct 2, 2015 at 3:26

2 Answers 2

3

This is because you are casting a and b to strings. You're most likely putting them in as int, which they should be. If for some reason you aren't, then the casts should be a = int(a), etc.

Also eval is to be avoided, you could change this to:

a = input('insert a number')
b = input('insert another number')

Or if you aboslutely have to enter them at once, you could do

a, b = input('Insert two numbers separated by commas').split(',')

Just make sure to not have spaces between them, or, to be safe, when casting you can do

a = int(a.strip())
Sign up to request clarification or add additional context in comments.

Comments

1

There are a few problems with this.

a, b = eval(input('Input a list of 2 numbers: '))

don't use eval() for a few more years. Even then use with extreme caution.

a = str(a)
b = str(b)

str() turns whatever is in there into a string which makes...

if (a % b == 0):  #this is where your error is

impossible to do because the "%" modulo operator is expecting numbers on either side. Since these are supposed to be numbers try wrapping a and b in int() or float() statements

a = input('Input the first number: ')
b = input('Input the second number: ')
a = int(a)
b = int(b)
if (a % b == 0):
    print( a + 'is divisible by' + b)
else:
    print( a + 'is not divisible by' + b)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.