简体   繁体   English

python 如何在每次循环迭代时生成新的随机数?

[英]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.我编写了一个小数学测验,我需要将其插入一个循环(while..)中以使其迭代用户想要的新时间。 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.我知道我可以插入一个控制变量,例如 keep_going = y 来让用户决定是否继续。

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 .你需要的是一个while 循环 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.这将永远循环,直到用户正确回答问题,但您可以在while之后放置任何条件,这最终可能是错误的。

Then I use raw_input() to have the user determine whether or not to continue.然后我使用raw_input()让用户决定是否继续。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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