我目前正在尝试制作一个程序,如果变量a可以被变量b整除,它就会打印出来。在试图打印值a和b时,我经常会遇到错误。
我的代码:
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)错误消息:
追踪(最近一次调用):if (a %b == 0):TypeError:不是所有在字符串格式化期间转换的参数中的文件“C:/User/ not /Documents/Python/As血4问题7.py”中的第4行
发布于 2015-10-02 03:11:40
这是因为您正在将a和b转换为strings。你很有可能把他们作为int,他们应该是。如果由于某种原因你不是,那么转换应该是a = int(a),等等。
另外,要避免eval,您可以将其更改为:
a = input('insert a number')
b = input('insert another number')或者如果你必须立即进入它们,你可以这样做。
a, b = input('Insert two numbers separated by commas').split(',')只是要确保它们之间没有空位,或者,为了安全起见,在铸造时你可以这样做。
a = int(a.strip())发布于 2015-10-02 03:12:32
这有几个问题。
a, b = eval(input('Input a list of 2 numbers: '))以后几年不要再使用eval()了。即使这样,使用时也要非常小心。
a = str(a)
b = str(b)str()把里面的任何东西变成一条字符串,使.
if (a % b == 0): #this is where your error is不可能这样做,因为"%“模运算符期望两边都有数字。因为这些应该是数字,所以尝试用int()或float()语句包装a和b。
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)https://stackoverflow.com/questions/32899955
复制相似问题