What the code below does is that it generates 2 random integers and multiplies them together. After the user has placed an input and gets it corrects, it will automatically generate another pair of random integers.
How could I make it so that when the user input is wrong, it does not generate a number but waits till the user to finally calculate the correct answer and then it generates a new set of integers?
I've been playing around with having a loop within the main loop but it hasn't solved my problem
while loop:
new_ints = True
while new_ints:
random_int_1 = random.randint(2,9)
random_int_2 = random.randint(2,9)
answer = random_int_1*random_int_2
equation = (f"{random_int_1}x{random_int_2} = ? ")
print(equation)
user_answer = int(input())
if answer == user_answer:
print("correct")
new_ints = True
loop = True
else:
print("Wrong")
new_ints = True
loop = False
CodePudding user response:
Instead of the if
statements you can simply have another while loop to check the guess like this:
while int(input()) != answer:
print('Incorrect. Guess again')
CodePudding user response:
Simply add an if condition before the generation of ints:
while True:
if new_ints:
random_int_1 = random.randint(2,9)
random_int_2 = random.randint(2,9)
answer = random_int_1*random_int_2
You need to decide which condition will break the loop. Imho, you can eliminate the external loop as well, just keep the while True
and establish a break
condition
CodePudding user response:
You can make use of while-else
to solve the problem. The loop will keep repeating if the user's input is not equal to the actual answer, otherwise it will print "correct" and move on to the next question. Below is the complete code after revising.
import random
while True:
random_int_1 = random.randint(2,9)
random_int_2 = random.randint(2,9)
answer = random_int_1*random_int_2
equation = (f"{random_int_1}x{random_int_2} = ? ")
print(equation)
user_answer = ''
while int(input()) != answer:
print("Wrong")
else:
print("correct")