简体   繁体   中英

python how can I generate new random numbers each time a loop iterates?

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!")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM