Python: How to keep repeating a program until a specific input is obtained?

151,244

Solution 1

There are two ways to do this. First is like this:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_input with input.

Solution 2

This is a small program that will keep asking an input until required input is given.

we should keep the required number as a string, otherwise it may not work. input is taken as string by default

required_number = '18'

while True:
    number = input("Enter the number\n")
    if number == required_number:
        print ("GOT IT")
        break
    else:
        print ("Wrong number try again")

or you can use eval(input()) method

required_number = 18

while True:
    number = eval(input("Enter the number\n"))
    if number == required_number:
        print ("GOT IT")
        break
    else:
        print ("Wrong number try again")

Solution 3

you probably want to use a separate value that tracks if the input is valid:

good_input = None
while not good_input:
     user_input = raw_input("enter the right letter : ")
     if user_input in list_of_good_values: 
        good_input = user_input
Share:
151,244
user3033494
Author by

user3033494

Updated on July 05, 2022

Comments

  • user3033494
    user3033494 almost 2 years

    I have a function that evaluates input, and I need to keep asking for their input and evaluating it until they enter a blank line. How can I set that up?

    while input != '':
        evaluate input
    

    I thought of using something like that, but it didn't exactly work. Any help?

    • Collin
      Collin over 10 years
      How does it not work? What does it do? What do you expect to see?
    • user3033494
      user3033494 over 10 years
      That above code repeatedly asks for the input if it is not ''. I need it to evaluate input until a blank line is entered.
  • Snigdha Batra
    Snigdha Batra over 7 years
    This will raise an EOF error at the last input if there is no further input
  • jwvh
    jwvh over 5 years
    Actually, it keeps repeating even after the required input is given.
  • Kiryl Plyashkevich
    Kiryl Plyashkevich over 2 years
    @SnigdhaBatra You can avoid it with: except EOFError: break
  • Mathieu Dhondt
    Mathieu Dhondt about 2 years
    Every time I write a while loop where the variable that the condition checks is set inside the loop (so that you have to initialize that variable before the loop, like in your second example), it doesn't feel right. And then I search for python repeat until to remind myself that I should just accept that feeling :)