+ 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

3rd Feb 2017, 8:20 AM
Š•Š³Š¾Ń€ ŠšŠ¾Š»Š¾Š²
Š•Š³Š¾Ń€ ŠšŠ¾Š»Š¾Š² - avatar
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'.
3rd Feb 2017, 8:25 AM
Ɓlvaro
+ 2
Alvaro is right, for your if statement you could use if int(d) == z: cast the string to an int
3rd Feb 2017, 8:32 AM
Bill
Bill - avatar
+ 1
Thanks! I thought it will not work with "if"
3rd Feb 2017, 8:35 AM
Š•Š³Š¾Ń€ ŠšŠ¾Š»Š¾Š²
Š•Š³Š¾Ń€ ŠšŠ¾Š»Š¾Š² - avatar
+ 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
3rd Feb 2017, 9:03 AM
Ɓlvaro
+ 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
3rd Feb 2017, 7:29 PM
Amaras A
Amaras A - avatar
0
Really... But this is a new problem...
3rd Feb 2017, 8:27 AM
Š•Š³Š¾Ń€ ŠšŠ¾Š»Š¾Š²
Š•Š³Š¾Ń€ ŠšŠ¾Š»Š¾Š² - avatar