我正在尝试制作一个简单的乘法游戏。一开始我有这样的代码
m = 1
total = 3
print "Which Multiplication tables do you want to practice?"
toPractice = raw_input()
while m <= total:
print "What is %s times %s" % (toPractice, m)
answer = raw_input('Your Answer: ')
print answer
if answer == toPractice * m:
print "Correct!"
m = m + 1
else:
print "Answer %s is incorrect." % (answer)
print 'Correct Answer: ', toPractice * m # For testing
m = m + 1 # For testing
但是这样做只会使您正在做的乘法表(例如 12)在 12 * 2 上显示为 1212,在 12 * 3 上显示为 121212,等等。所以我将其转换为整数。
toPractice = raw_input()
toPractice = int(toPractice)
但是当我这样做时它会说 12 * 2 的答案是 24 但它说答案不正确。我问过 friend 并尝试四处搜索,但无法弄清楚为什么它不起作用。
请您参考如下方法:
不要忘记:raw_input 总是返回一个 str。乘以一个字符串只是重复它,例如“12”* 3 =“121212”。您需要使用 int 函数将输入转换为整数:
answer = raw_input('Your Answer: ')
answer = int(answer)
或者更短的方式:
answer = int(raw_input('Your Answer: '))
您需要为程序中需要数字的每个输入执行此操作。
