【问题标题】:Trying to loop just some parts of a math quiz program试图只循环数学测验程序的某些部分
【发布时间】:2011-11-19 19:56:07
【问题描述】:

我正在尝试找出循环这个简单数学测验程序的最佳方法(这里最好的意思是最简洁和最简单的方法)。我得到两个随机数及其总和,提示用户输入并评估该输入。理想情况下,当他们想再次玩游戏时,它应该获得新号码,并在提示不是有效答案时提出相同的问题......但我似乎无法思考如何去做。

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)

【问题讨论】:

  • 这听起来像是家庭作业。我正在添加作业标签;如果不是作业,你可以删除它。

标签: python loops user-input


【解决方案1】:

Python 中有两种基本的循环:for 循环和 while 循环。您将使用 for 循环来循环列表或其他序列,或者执行特定次数的操作;当您不知道需要做多少次某事时,您会使用一段时间。其中哪一个似乎更适合您的问题?

【讨论】:

    【解决方案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 编程的一个很好的介绍。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多