Why the output is always the else part? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why the output is always the else part?

num = input("Enter the number: ") If num == 4: print ("the number is 4") elif num == 5: print("the number is 5") else: print("the number is invalid") In this program, no matter what input we provide it always ends up with the else part of the statement. Why is this happening with this code ? Any Explanation please???

8th Dec 2018, 3:53 PM
Pema Gyalpo
Pema Gyalpo - avatar
5 Answers
+ 8
Inputs in Python 3.x are treated as strings. You'd have to convert them to an appropriate data type afterwards. Here, you can just write num = int(input("Enter the number:")) in the first line, and the code should work fine. Let me know if the problem persists :)
8th Dec 2018, 4:00 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
I'm not an expert in Python, but I think that you first have to cast the input to integer (through the 'int' function??).
8th Dec 2018, 4:01 PM
bullion
+ 2
Pema Gyalpo Num = input() #Num will be always string unless you cast it Num =2 #Num is now int Num =2.0 #Num is float (Note the decimal point) Num =int(input()) #Num is int (Although if you pass an input which cannot be converted to an integer, an error will be raise)
8th Dec 2018, 4:37 PM
Mayur Garg
Mayur Garg - avatar
+ 1
When an input is provided Regardless of what the input is it always says the number is invalid. Why?
8th Dec 2018, 3:54 PM
Pema Gyalpo
Pema Gyalpo - avatar
0
Thank you all for the ans It really helped me. But i have another doubt What is the default datatype of the value when we take it directly as Num = input Or Num = assigning a number So whats the datatype of Num?
8th Dec 2018, 4:12 PM
Pema Gyalpo
Pema Gyalpo - avatar