开发者

Trying to loop just some parts of a math quiz program

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)
answ开发者_如何学Pythoner = 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>:

Or:

for <var> in <list>:

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

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

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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜