+ 1
I have problems with my code. Why answer is always wrong? What am I doing wrong?
from random import randint def calc(): x = randint(1,100) y = randint(1,100) z = x + y print(x) print("+") print(y) d = input("Input answer:") if d == z: print("Yes!") calc() else: print("Wrong!") calc() calc
6 Answers
+ 4
When you ask for an input, and store it into variable 'd', 'd' is a string. You should convert it to an integer before evaluating whether it's equal to 'z'.
+ 2
Alvaro is right, for your if statement you could use
if int(d) == z:
cast the string to an int
+ 1
Thanks! I thought it will not work with "if"
+ 1
Or... you could write d=int(input("Input answer:"))
Or even better:
try:
d=int(input("Input answer:"))
catch ValueError:
# ask for input again (maybe in a while loop), or assign a default value
# this prevents an error if the user does not input a number
#... rest of the code
+ 1
maybe you could just not worry about type conversion : use str(z) instead of int(d), because it's never going to fail unless something terrible happens
0
Really... But this is a new problem...