首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试循环执行数学测验程序的某些部分

尝试循环执行数学测验程序的某些部分
EN

Stack Overflow用户
提问于 2011-09-19 04:46:10
回答 2查看 4.4K关注 0票数 1

我正在尝试找出最好的方法来循环这个简单的数学测验程序(这里最好的意思是最整洁和最简单的方法)。我得到两个随机数及其总和,提示用户输入,并计算该输入。理想情况下,当他们想要再次玩游戏时,它应该获得新的数字,并且当提示不是有效的answer...but时,它应该问同样的问题。我似乎无法理解如何处理它。

代码语言:javascript
运行
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2011-09-19 04:55:46

这里你遗漏了两样东西。首先,您需要某种类型的循环结构,例如:

代码语言:javascript
运行
复制
while <condition>:

或者:

代码语言:javascript
运行
复制
for <var> in <list>:

你需要一些方法来“短路”循环,这样如果你的用户输入了一个非数字值,你就可以重新开始。为此,您需要阅读continue语句。把这些放在一起,你可能会得到这样的结果:

代码语言:javascript
运行
复制
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语言编程的好入门。

票数 2
EN

Stack Overflow用户

发布于 2011-09-19 05:00:57

在Python中有两种基本类型的循环: for循环和while循环。您可以使用for循环遍历列表或其他序列,或者执行特定次数的操作;当您不知道需要执行某项操作的次数时,可以使用while。下面哪一个看起来更适合你的问题?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7464345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档