Can anyone explain why this code always prints "True" yet changing it to int or str only always gives "False"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone explain why this code always prints "True" yet changing it to int or str only always gives "False"?

while True: user_input = input("type number or letter or anything") if user_input == str or int: print("good, right") else: print("No, bad!")

9th Apr 2017, 5:17 PM
Callum Rogers
Callum Rogers - avatar
2 Answers
+ 3
The if statement is wrong here. First of all, user_input will always be a string, unless you convert it to some other type. Regardless of whether you do it or not, you can check for: type(user_input) == str Second of all, the construction of if requires full expressions to be compared and/or joined. So in this case, a proper statement would be: if (type(user_input) == str) or (type(user_input) == int): In this statement, the first part will be True, the second part False and so 'or' will output True.
9th Apr 2017, 6:03 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
Ah excellent, thankyou. Wasn't aware of type, am now :)
9th Apr 2017, 6:09 PM
Callum Rogers
Callum Rogers - avatar