Skip to content

How to keep asking for user input Python | Example code

  • by

There are two ways to keep asking for user input in Python. First using while true with if statement and break statement.

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

Another way is using a while loop with condition expression.

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

Note: this code supports Python 3.x, you will need to use raw_input for the below versions.

Example keep asking for user input in Python

A simple example code continues asking the user for input until it is considered valid.

Example 1

Input is taken as a string by default.

pw = '123'

while True:

    number = input("Enter the Password: ")

    if number == pw:
        print("GOT IT")
        break
    else:
        print("Wrong try again")

Output:

How to keep asking for user input Python

Example 2

number = ""

while number != '123':
    number = input("Enter the Password: ")

Output:

Enter the Password: 1
Enter the Password: 123

Another common way to do this is by using a while loop. Here’s an example of how to keep asking for user input in Python:

while True:
    user_input = input("Enter something (or 'exit' to quit): ")

    if user_input.lower() == 'exit':
        print("Exiting...")
        break

    # Do something with the user input
    print("You entered:", user_input)

# Code will continue here after the loop
print("End of the program.")

In this example, the while True: creates an infinite loop because the condition is always true. Inside the loop, we use the input() function to get user input, and then we check if the input is equal to “exit” (case-insensitive) using user_input.lower() == 'exit'. If the user enters “exit”, the program prints a message and breaks out of the loop using the break statement. Otherwise, it processes the user input, and the loop continues to ask for more input.

To stop the program and break out of the loop, the user can simply type “exit”. Otherwise, the loop will keep running and asking for input until the user decides to quit.

Do comment if you have any doubts or suggestions on this Python input program.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading