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()
答案 0 :(得分:1)
您的代码的问题在于您正在尝试对字符串进行数学运算。
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()
这里我们使用try和except语句来处理它们的输入是否不是数字。