尝试仅循环数学测验程序的某些部分 [英] Trying to loop just some parts of a math quiz program

查看:59
本文介绍了尝试仅循环数学测验程序的某些部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出循环此简单数学测验程序的最佳方法(此处最好表示最简洁的方法).我得到两个随机数及其和,提示用户输入并评估该输入.理想情况下,当提示再次播放时,它应该获得新的数字,并在提示不是有效答案时问同样的问题...但是我似乎无法解决这个问题.

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)

推荐答案

您在这里缺少两件事.首先,您需要某种循环构造,例如:

You're missing two things here. First, you need some sort of loop construct, such as:

while <condition>:

或者:

for <var> in <list>:

您需要某种方式来短路"循环,以便您可以重新开始 如果您的用户输入非数字值,则在顶部.为此,你想 阅读continue语句.将所有这些放在一起,您可能会得到 像这样的东西:

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 get something like this:

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语句时才会退出.

Note that this is an infinite loop (while True), that only exits when it hits the break statement.

最后,我强烈建议以艰难的方式学习Python" 作为Python编程的很好的介绍.

In closing, I highly recommend Learn Python the Hard Way as a good introduction to programming in Python.

这篇关于尝试仅循环数学测验程序的某些部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆