Python Forum
Problem with elif statement - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Problem with elif statement (/thread-18492.html)



Problem with elif statement - Haddal99 - May-20-2019

I'm completely new to Python (and programming in general) and I can't wrap my head around why this piece of code doesn't work:

posx = 0
posy = 0
doForever = True

while doForever == True:
  if input() == "forward":
    posy += 1
    print(posy)
  elif input() == "backward":
    posy -= 1
    print(posy)
It's supposed to check if the player inputs "forward" or "backward" and update the ypos accordingly. But what actually happens is that if you input "backward", it only works exactly half of the time. The "forward" one works correctly, but the "backward" only returns the updated variable every other time it's used. Help would be much appreciated; thanks in advance.


RE: Problem with elif statement - buran - May-20-2019

as it is now, it will ask for user input twice.

posx = 0
posy = 0
 
while True:
    user_choice = input().lower()
    if  user_choice == "forward":
        posy += 1
        print(posy)
    elif user_choice == "backward":
        posy -= 1
        print(posy)
    elif user_choice == 'exit': # provide way to exit the loop
        break



RE: Problem with elif statement - avorane - May-20-2019

Hello,

I think the problem become of call input in tests. When you enter in the "if", you call input(). If it isn't the value expected, you enter in the "elif" where you call a new input().

Try:

posx = 0
posy = 0
doForever = True
 
while doForever == True:
  value = input()
  if value == "forward":
    posy += 1
    print(posy)
  elif value == "backward":
    posy -= 1
    print(posy)
Best Regards,

Nicolas TATARENKO