skip to Main Content

I wanted to ask that how can I make my program loop with basic code, (pls don’t recommend cryptic ones) such as if a user types 1 it reruns the program and if they type anything else, the program ends soo please help me in this problem.

2

Answers


  1. Use a while True loop and break out of it when a certain condition is met:

    while True:
        if int(input("Enter a number: ")) == 1: # if user's input is '1'
            break # break out of the infinite loop 
            
        # do repetitive stuff here ... 
    
    Login or Signup to reply.
  2. You have two options:

    Iteration

    Use an infinite while True loop and break out if the user enters 1

    while True:
        inp = input("Enter a number: ")
        if inp == '1':
            break
        # some code goes here
    

    Recursion

    Create a recursive function which returns if the user enters 1

    def get_input():
        inp = input("Enter a number: ")
        if inp == '1':
            return
        # some code goes here
        get_input()
    
    get_input()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search