[英]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
,则在每次迭代中num1
和num2
的值将保持不变。 Moving it inside means you get new random numbers every time. 将其移入内部意味着您每次都会获得新的随机数。
Also note: 另请注意:
questionNum
variable, you can just use i
; questionNum
变量,只需使用i
; that way you don't need to increment it manually. num1
or num2
to zero at the beginning. num1
或num2
初始化为零。 correct += 1
correct += 1
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.