+ 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
3 ответов
+ 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.
+ 1
Thanks Jay, it works. But if I didn’t define it as a integer, then by default will it take as a string??
+ 1
Thanks.