Skip to content

How to keep asking for user input Python | Example code

  • by

There are two ways to do 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 support Python 3.x, you will need to use raw_input for the below versions.

Example keep asking for user input in Python

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")
        print("Wrong try again")


How to keep asking for user input Python

Example 2

number = ""

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


Enter the Password: 1
Enter the Password: 123

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

Note: IDE: PyCharm 2021.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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.