Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with elif statement
#1
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.
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question If, elif, and else statement not working PickleScripts 3 841 Mar-30-2023, 02:53 PM
Last Post: PickleScripts
  problem with while statement. BobSmoss 3 1,623 Jan-08-2022, 03:22 PM
Last Post: BobSmoss
  Problem in if-else statement shantanu97 2 2,389 Apr-09-2021, 06:37 AM
Last Post: shantanu97
  multiple condition if statement problem FelixReiter 3 2,541 Jan-11-2021, 08:07 AM
Last Post: FelixReiter
  Problem with If statement and dataframe Milfredo 1 1,740 Sep-16-2020, 05:50 AM
Last Post: Milfredo
  Problem with If else statement Milfredo 5 2,536 Aug-30-2020, 06:32 PM
Last Post: Milfredo
  Problem with a 'break' statement. christopher3786 3 2,393 Jun-20-2020, 10:16 AM
Last Post: pyzyx3qwerty
  If elif else statement not functioning SamDiggityDog 4 2,599 Jun-03-2020, 12:27 AM
Last Post: SamDiggityDog
  Proper use of if..elif..else statement nick1941 2 2,376 Mar-06-2020, 11:22 PM
Last Post: nick1941
  Problem with an IF statement Ryan_Todd 13 4,891 Jan-30-2020, 08:22 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020