类型错误:并非在字符串格式化过程中转换的所有参数
问题描述:
def converter():
print ("Welcome to Andy's decimal to binary converter!")
x = raw_input("Enter an integer or enter 'exit' to exit program:")
if x=="exit":
print "Goodbye"
exit()
string = ""
while x!=0:
remainder =x%2
string =string+str(remainder) #giving error here and dont know why!
x =x/2
y =string
binary =y[::-1]
print "The integer in binary is: ",binary
again =raw_input("Would you like to enter another integer? Enter yes or no: ")
if again=="no":
print "Goodbye"
exit()
elif again=="yes":
return converter()
else:
print "Enter either 'yes' or 'no'"
print converter()
答
您的代码的问题在于它试图对字符串进行数学运算。
remainder = x%2
这被视为"123" % (2)
,由于该字符串不包含有效的字符来代替你得到这个错误。
要解决这个问题,我会建议您在检查值是否“退出”后将输入转换为整数。请参阅:
if x=="exit":
print "Goodbye"
exit()
else:
try:
x = int(x)
except:
print "%s is not a number!" % (x)
return converter()
这里我们使用一个尝试,除了语句来处理,如果他们的投入是不是一个数字。
这是你的全部代码?什么是导致错误的线? – elethan
可以想象,如果'x'是非数字的,'x%2'可以做到这一点。如果它是一个字符串(并且,给定'raw_input',它*将*为一个字符串),那么我们会将它视为格式字符串 –
您的错误在这里:'remaining = x%2'。 'x'是一个字符串,你试图把它当作一个整数。在while循环之前,使'x'为整数。 'x = int(x)'。 –