Home > front end >  Restart while loop in Python
Restart while loop in Python

Time:11-02

So i have a program that prints a different thing depending on the input(choice) Like this

choice = int(input("Choose a function from 1 to 3: "))
while(True):
if choice == 1:
   print("You chose 1")
elif choice == 2:
   print("You chose 2")
elif choice == 3:
   print("Shutting down")
   break

At the moment it keeps on printing the print statement when I choose 1 or 2, can I make it so that it only prints once(I think you can do this by adding more loops but I hope there is a better alternative)

So I would like that the program ask for the choice again

Thanks!

CodePudding user response:

I don't really know what are you trying to accomplish with your code. In the case that you are trying to choose once, and print once, you don't need a loop. In the case that you want to choose, print and then choose again, put the choice inside the while loop.

CodePudding user response:

You only deffine the variable once and then just let the loop run all the time. Try to move "choice" into the loop so that "choice" is always redefined.

(Also you should make while True and not while(True).)

This should work:

while True:
choice = int(input("Choose a function from 1 to 3: "))
if choice == 1:
   print("You chose 1")
elif choice == 2:
   print("You chose 2")
elif choice == 3:
   print("Shutting down")
   break

CodePudding user response:

You have to put your input function at the start of the while loop.

CodePudding user response:

You have to declare the input variable inside loop to take multiple inputs.

while(True):
    choice = int(input("Choose a function from 1 to 3: "))
    if choice == 1:
          print("You chose 1")
    elif choice == 2:
           print("You chose 2")
    elif choice == 3:
        print("Shutting down")
        break

CodePudding user response:

There's indentation error in your code. Fix that and also, the input statement should be moved inside the while loop so that it can keep asking again and again. Your edited code:

while True:
    choice=int(input("Enter your choice= "))
    if choice==1:
        print("You've chosen 1")
    elif choice==2:
        print("You've chosen 2")
    elif choice==3:
        print("Shutting down")
        break
  • Related