Reputation:
I'm trying to practice python because I'm starting yr 12 soon. I created a quiz game but when i get the question right it always says that it's wrong
print("Welcome to the math quiz game!")
for i in range(0,10):
operators = ['+','-','*','/']
import random
num1 = random.randint(1,10)
num2 = random.randint(1,10)
randop = random.choice(operators)
question = input("What is %d %s %d: " % (num1,randop,num2))
if randop == "+":
answer = num1 + num2
elif randop == "-":
answer = num1 - num2
elif randop == "*":
answer = num1 * num2
elif randop == "/":
answer = num1 / num2
if question == answer:
print("\nCorrect")
elif question != answer:
print("Incorrect or Invalid")
Upvotes: 2
Views: 323
Reputation: 3515
As mentioned you need to cast the return value from input()
into an float (to cope with decimals from division):
question = float(input("What is %d %s %d: " % (num1,randop,num2)))
I don't recommend doing this as a bad input will crash the game so use input validation with a try/except
block:
question = input("What is %d %s %d: " % (num1,randop,num2))
try:
question = float(question)
except ValueError:
print('Invalid or incorrect.')
continue # skip the rest of the code and head straight into the next iteration in the for loop
Also, I don't recommend including the division option as most values will be recurring decimals which cannot be input correctly unless you check beforehand that the answer will not be recurring or if you round the answer off to, say, 2 decimal places and ask the user for a 2 d.p answer
(You could also make the 'answer' variable a string instead of making 'question' an int)
Upvotes: 2
Reputation: 473
When doing a comparison in a program with ==
we must compare two variables of the same type (which can be devious when starting Python). Answer
is a number, while question
is a string which was written by the user. Thus Python recognizes the two as different and false. To avoid this you must either convert the number to a string or the string to a number so you compare two variables of the same type.
Upvotes: 2