I'm trying to create a simple game that creates math problems and the users task is to decide if they are true or false. (eg. 2 + 2 = 6, True or False?) I am using the keyboard module and I want to have the user press the left arrow key if he thinks that the problem is true, and the right one if he thinks that it's false.
import random
import keyboard
def addition_easy():
x = random.randint(1, 6)
y = random.randint(1, 6)
z = x + y
answer_correct = random.choice([True, False])
if answer_correct == False:
answer = (random.randint(2, 12))
else:
answer = z
if answer == z:
answer_correct = True
print(f"{x} + {y} = {answer}")
print("True or False?")
while True:
if keyboard.is_pressed('left'):
user_answer = True
break
elif keyboard.is_pressed('right'):
user_answer = False
break
if user_answer == answer_correct:
return True
else:
return False
The thing is, after I paste this function into a loop, I can only press left or right once. After that the rest of the code is executed without waiting for my keypress.
from problems import addition_easy
exercise_amount = int(input("How many exercises would you like to solve?"))
for exercise in range(1, exercise_amount + 1):
addition_easy()
This returns (for input of 5):
How many exercises would you like to solve? 5
6 + 1 = 9
True or False? //(Here it waits for me to press "left" or "right")
3 + 3 = 8
True or False? //(From here it doesn't stop to wait for a keypress)
4 + 3 = 7
True or False? //(Same here and so on...)
2 + 3 = 3
True or False?
1 + 2 = 3
True or False?
How can I make it wait for a keypress every time it prints out a math problem?
keyboard.wait()afterif keyboard.is_pressed('left')andelif keyboard.is_pressed('right')? - amanbkeyboard.wait()with no arguments makes the program pause forever. (No, I don't know why that's even an option) - Kevin