Reputation: 563
I coded a little math quiz that I need to insert in a loop (while..) to make it iterates a new time a user wants to. Especially, how do I make it generate ''new random numbers'' each time it iterates. I know I can insert a control variable such as keep_going = y to let user decide whether to continue or not.
Please see codes below, and thanks for the help!
import random
first_num = random.randint(1,500)
second_num = random.randint(1,500)
print (first_num)
print (second_num)
answer = int(input('Entrer la somme des deux nombres: '))
if answer == first_num + second_num:
print("It's correct!")
else:
print("It's wrong!")
Upvotes: 2
Views: 5572
Reputation: 36521
What you need is a while loop. This one will loop forever until the user gets the question right, but you could put any condition after while
that might eventually be false.
Then I use raw_input()
to have the user determine whether or not to continue. This is one of many ways to accomplish what you're going for.
import random
while True:
first_num = random.randint(1,500)
second_num = random.randint(1,500)
print (first_num)
print (second_num)
answer = int(input('Entrer la somme des deux nombres: '))
if answer == first_num + second_num:
print("It's correct!")
break
else:
print("It's wrong!")
tryAgain = raw_input('Try again? [(y)/n] ')
if tryAgain.lower() == 'n':
break
Upvotes: 2