我正在尝试找出最好的方法来循环这个简单的数学测验程序(这里最好的意思是最整洁和最简单的方法)。我得到两个随机数及其总和,提示用户输入,并计算该输入。理想情况下,当他们想要再次玩游戏时,它应该获得新的数字,并且当提示不是有效的answer...but时,它应该问同样的问题。我似乎无法理解如何处理它。
import random
from sys import exit
add1 = random.randint(1, 10)
add2 = random.randint(1, 10)
answer = str(add1 + add2)
question = "What is %d + %d?" % (add1, add2)
print question
print answer
userIn = raw_input("> ")
if userIn.isdigit() == False:
print "Type a number!"
#then I want it to ask the same question and prompt for an answer.
elif userIn == answer:
print "AWESOME"
else:
print "Sorry, that's incorrect!"
print "Play again? y/n"
again = raw_input("> ")
if again == "y":
pass
#play the game again
else:
exit(0)发布于 2011-09-19 04:55:46
这里你遗漏了两样东西。首先,您需要某种类型的循环结构,例如:
while <condition>:或者:
for <var> in <list>:你需要一些方法来“短路”循环,这样如果你的用户输入了一个非数字值,你就可以重新开始。为此,您需要阅读continue语句。把这些放在一起,你可能会得到这样的结果:
While True:
add1 = random.randint(1, 10)
add2 = random.randint(1, 10)
answer = str(add1 + add2)
question = "What is %d + %d?" % (add1, add2)
print question
print answer
userIn = raw_input("> ")
if userIn.isdigit() == False:
print "Type a number!"
# Start again at the top of the loop.
continue
elif userIn == answer:
print "AWESOME"
else:
print "Sorry, that's incorrect!"
print "Play again? y/n"
again = raw_input("> ")
if again != "y":
break请注意,这是一个无限循环(while True),只有在命中break语句时才会退出。
最后,我强烈推荐Learn Python the Hard Way作为Python语言编程的好入门。
发布于 2011-09-19 05:00:57
在Python中有两种基本类型的循环: for循环和while循环。您可以使用for循环遍历列表或其他序列,或者执行特定次数的操作;当您不知道需要执行某项操作的次数时,可以使用while。下面哪一个看起来更适合你的问题?
https://stackoverflow.com/questions/7464345
复制相似问题