Trying To Loop Just Some Parts Of A Math Quiz Program
Solution 1:
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.continueelif 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.
Solution 2:
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?
Post a Comment for "Trying To Loop Just Some Parts Of A Math Quiz Program"