简体   繁体   中英

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.

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:

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. 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 ; that way you don't need to increment it manually.
  • you don't need to initialize num1 or num2 to zero at the beginning.
  • Increments are a bit cleaner to write like so: correct += 1
  • You probably want to say print('the correct answer is', num1*num2) or else you'll just print their incorrect input.

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