elif statement issue | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

elif statement issue

Hi all, I m new to python. I was just tried the following code for my practice but it seems I m geeting wrong answer. Please let me know where I’m making mistake. >>> a=input(“Enter a number between 1 to 4: “) Enter a number between 1 to 4: 2 >>> if a==1: Print(“Entered number is 1”) elif a==2: Print (“Entered number is 2”) elif a==3: Print (“Entered number is 3”) else: Print(“Entered number is 4”) Output : Entered number is 4 How?? I entered 2

2nd Jun 2019, 6:11 AM
Baskar
3 Answers
+ 6
This is a very common issue that happens frequently. If you use input() function and enter something, this will always be stored as string. So in your case input may be 2 but it‘s stored as ‘2’. So you either have to compare it as strings like : if a == ‘2’ or you convert input instanty to int as Jay Matthews mentioned.
2nd Jun 2019, 6:22 AM
Lothar
Lothar - avatar
+ 1
Thanks Jay, it works. But if I didn’t define it as a integer, then by default will it take as a string??
2nd Jun 2019, 6:18 AM
Baskar
+ 1
Thanks.
2nd Jun 2019, 6:23 AM
Baskar