Home > Back-end >  One While Loop Is Overwriting another While Loop
One While Loop Is Overwriting another While Loop

Time:05-02

I was making a code which will change the user input from alphabet to numbers. I made a dictionary with each alphabet as key and a corresponding number value.

In order to make the code self running (I don't have to hit run every time) I used a while loop.

start_over = input("Please Enter (Y) to start and (N) to stop: ").lower()

While start_over == "y" :            # First While Loop
    (the alphabet changer code here)
    start_over = input("Enter (Y) to continue and (N) to stop: ").lower()

While start_over != "y" and start_over != "n" :        # Second while loop
     start_over = input("Enter (Y) to continue and (N): ")

While start_over == "n":       #Third While Loop
      print("Thanks for using the code")
      break

Now the problem is when I input Y, the first while loop runs and it works properly. If I put N, the third while loop runs and the code breaks as wanted. But When I put anything except Y and N the second while loop runs and ask me to put anything else. When I put N in second while loop, the code breaks as wanted. But when I input Y in second while loop, the code breaks instead of running the first while loop. Why is this happening I have no idea.

CodePudding user response:

The problem is when your code enters 2nd while loop and user inputs start_over = 'y'. It won't move to your 1st while loop, since it is placed above. To avoid this you can put your 2nd while in a function:

def start(start_over):
    while start_over != "y" and start_over != "n" :
        start_over = input("Enter (Y) to continue and (N): ")
    return start_over

start_over = input("Please Enter (Y) to start and (N) to stop: ").lower()

if start_over != "y" and start_over != "n" :
    start_over = start(start_over)

while start_over == "y" :           
    start_over = input("Enter (Y) to continue and (N) to stop: ").lower()
    if start_over != "y" and start_over != "n" :
        start_over = start(start_over)

while start_over == "n":       #Third While Loop
      print("Thanks for using the code")
      break
  • Related