ReVaN ReVaN - 2 months ago 6
Python Question

Simple if/elif statement + raw_input why dosen't work

I have a problem with simple if statement. I want user to press a key '1','2' or '3' to choose any option then program will do something. For a test it just prints text for example "Wybrano 2" after pressing '2'.

Here is my code:

if raw_input() == '1':
print "Wybrano 1"

elif raw_input() == '2':
print "Wybrano 2"

elif raw_input() == '3':
print "Wybrano 3"


So if I press 1 it correctly prints "Wybrano 1" but when I press 2 or 3 the program does nothing.

Answer

When i press 2 or 3 program does not nothing is wrong. It is waiting for you for next input.

Let me tell you how this is working.

  • raw_input is python function for accepting user input.(I know you are aware of this :) )
  • When you execute code, first it will go to "if" statement. 'if' statement has 'raw_input' function after it. So, it waits for your input.
  • When you enter '1', "1" = "1", it gives you expected output and come out of code.
  • However, next time when you again execute code, again 'raw_input' after 'if' is executed waiting for your input. When you input '2' and since '1' == '2' is false, code goes to next 'elif' statement. After 'elif' there is 'raw_input' function which is waiting for input again.
  • Therefore, you got feel, program does nothing.
  • Same happens when you enter '3'.

Example of above explained behavior

if raw_input("Enter number : ") == '1':

    print "Wybrano 1"
elif raw_input("Enter number : ") == '2':

    print "Wybrano 2"
elif raw_input("Enter number : ") == '3':

    print "Wybrano 3"

Output:

C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 1
Wybrano 1

C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 2
Enter number : 2
Wybrano 2

C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 3
Enter number : 3
Enter number : 3
Wybrano 3

How to make your code working ?

Answer is simple. As explained by @MooingRawr in first comment, just save user input in some variable and then check.

x = raw_input("Enter number : ")
if  x == '1':
    print "Wybrano 1"
elif x == '2':
    print "Wybrano 2"
elif x == '3':
    print "Wybrano 3"

Output:

C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 1
Wybrano 1

C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 2
Wybrano 2

C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 3
Wybrano 3

C:\Users\dinesh_pundkar\Desktop>