尝试仅循环数学测验程序的某些部分
我试图找出循环这个简单数学测验程序的最佳方法(这里最好的意思是最简洁的方法)。我得到两个随机数及其总和,提示用户输入并评估该输入。理想情况下,当他们想再次玩时,它应该获得新的数字,并在提示不是有效答案时提出相同的问题……但我似乎不知道如何去做。
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)
I'm trying to figure out the best way to loop this simple math quiz program (best here meaning the neatest and simplest method). I get two random numbers and their sum, prompt the user to enter, and evaluate that input. Ideally, it should get new numbers when they want to play again and ask the same question when the prompt is not a valid answer...but I just can't seem to wrap my head around how to go about it.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你在这里错过了两件事。首先,您需要某种循环构造,例如:
或者:
并且您需要某种方法来“短路”循环,以便可以重新开始
如果您的用户输入非数字值,则位于顶部。为此,你想要
阅读
continue
语句。把这些放在一起,你可能会得到像这样的东西:
请注意,这是一个无限循环(
while True
),仅在遇到break
语句时退出。最后,我强烈推荐艰苦学习Python作为Python编程的一个很好的介绍。
You're missing two things here. First, you need some sort of loop construct, such as:
Or:
And you need some way to "short-circuit" the loop so that you can start again
at the top if your user types in a non-numeric value. For that you want to
read up on the
continue
statement. Putting this all together, you might getsomething like this:
Note that this is an infinite loop (
while True
), that only exits when it hits thebreak
statement.In closing, I highly recommend Learn Python the Hard Way as a good introduction to programming in Python.
Python 中有两种基本类型的循环:for 循环和 while 循环。您可以使用 for 循环来循环列表或其他序列,或者执行特定次数的操作;当你不知道需要做多少次某件事时,你会使用一段时间。其中哪一个似乎更适合您的问题?
There are two basic kinds of loops in Python: for loops and while loops. You would use a for loop to loop over a list or other sequence, or to do something a specific number of times; you would use a while when you don't know how many times you need to do something. Which of these seems better suited to your problem?