简体   繁体   English

生成随机整数,但每次都必须不同

[英]Generating random integers, but they need to be different each time

I'm currently making a program for school work, and I need to make a maths quiz program. 我目前正在编写学校作业程序,并且需要编写数学测验程序。 I'm doing a simple multiplication quiz. 我正在做一个简单的乘法测验。

I need to be able to generate 2 random integers for the questions, but they have to be different for each question. 我需要能够为问题生成2个随机整数,但是每个问题它们必须不同。

import random
correct = wrong = num1 = num2 = 0
questionNum = 1
num1 = random.randint(1,49)
num2 = random.randint(50,100)

for i in range(0, 8):
    print("\nQuestion", questionNum)
    print("What is", num1, "mulitplied by", num2, "?")
    answer = int(input("Answer: "))
    if answer == num1*num2:
        print("Correct.")
        correct = correct + 1
        questionNum = questionNum + 1
    else:
        print("Incorrect. The correct answer is", answer)
        wrong = wrong + 1
        questionNum = questionNum + 1

The questions have the same numbers each time. 每次问题的编号相同。 Is there a way to change this? 有办法改变吗?

Just move your random.randint assignments inside the for loop: 只要将您的random.randint分配的for循环:

for i in range(1, 9):
    num1 = random.randint(1, 49)
    num2 = random.randint(50, 100)

If you only call randint before the loop, the values of num1 and num2 will stay they same through each iteration. 如果仅在循环之前调用randint ,则在每次迭代中num1num2的值将保持不变。 Moving it inside means you get new random numbers every time. 将其移入内部意味着您每次都会获得新的随机数。

Also note: 另请注意:

  • you don't need a separate questionNum variable, you can just use i ; 您不需要单独的questionNum变量,只需使用i that way you don't need to increment it manually. 这样,您无需手动对其进行递增。
  • you don't need to initialize num1 or num2 to zero at the beginning. 您无需在开始时将num1num2初始化为零。
  • Increments are a bit cleaner to write like so: correct += 1 增量这样写起来会更干净: correct += 1
  • You probably want to say print('the correct answer is', num1*num2) or else you'll just print their incorrect input. 您可能要说出print('the correct answer is', num1*num2) ,否则您将只打印他们的错误输入。

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

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