尝试只循环数学测验程序的某些部分

1 投票
2 回答
4686 浏览
提问于 2025-04-17 02:33

我正在想办法让这个简单的数学测验程序循环得更好(这里的“更好”是指更整洁和简单的方法)。程序会生成两个随机数字和它们的和,然后提示用户输入答案,并检查这个输入是否正确。理想情况下,当用户想再玩一次时,程序应该生成新的数字;如果用户的输入不正确,程序应该重复问同样的问题……但我就是搞不清楚该怎么做。

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)

2 个回答

1

在Python中,有两种基本的循环方式:for循环和while循环。你可以用for循环来遍历一个列表或者其他的序列,或者用它来做某件事情固定的次数;而while循环则是在你不知道需要做多少次的时候使用。你觉得哪种循环更适合你的问题呢?

2

你这里缺少了两个东西。首先,你需要一种循环结构,比如:

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编程的好入门书籍。

撰写回答