Python Forum
while loops and using counters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loops and using counters
#1
x = 1
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
while n == "right" or n == "Right":
    if x==1:
        n = input("You are in the Lost Forest\n****************\n****************\n  :(\n****************\n****************\nGo left or right? ")
        x=x+1
    if x<1:
        n = input("You are in the Lost Forest\n****************\n****************\n  (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
print("\nYou got out of the Lost Forest!\n\o/")
Hey there;
Strated learning python this semester and Im having some trouble understanding why this code wont work
(Code from MIT Introduction to Computer science)
tried to upgrade it and add a counter but the program seems to crash after one round of the loop...
would love to have your help, Thanks.
Reply
#2
First, line 7, how will you ever have x < 1?
Go through the logic - x = 1, then get an input. If they answer anything other than right then they jump over the while loop and are out of the forest. If they enter "right" on the first run, it passes the first if inside the loop so asks for a direction. x will now be 2 and so the second if is not passed and the enclosed code will never be executed. Back to the while, if n is now "right" then you go to the if statements, and this time both will fail! So, endless loop inside the while.

Change the < in line 7 to a >. It then works

OH and change the if in line 7 to elif
Reply


Forum Jump:

User Panel Messages

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