Skip to content

Python while input is not empty | Example code

You have to use a break statement if the user enters some value. Where the while loop will run and prompt the input message until the user gives some value. The syntax for while input is not empty in Python.

while True:

    s = input()

    if not s:
        break
    somelist.append(s)

You can check input is empty or not with the help of the if statement.

x=input()
if x:
    print(x)
else:
    print('empty input')

Run while loop input is not empty in Python

Simple example code.

name = ''

# Start a loop that will run until the user give input
while True:
    name = input("Enter Name to exist: ")

    if name:
        print(name)
        break

Output:

Python while input is not empty

To create a while loop in Python that continues until the user enters an empty input, you can use the following code:

while True:
    user_input = input("Enter something (or leave it empty to exit): ")
    
    if user_input == "":
        break
    
    # Do something with the input
    print("You entered:", user_input)

In this code, the while loop runs indefinitely (while True:) until the break statement is encountered. Inside the loop, the user is prompted to enter something, and their input is stored in the user_input variable. The if statement checks if the input is an empty string (user_input == ""), and if so, the loop is exited using break. If the input is not empty, you can perform any desired actions with the input. In this example, it simply prints the input back to the user.

Comment if you have any doubts or suggestions on this Python input topic.

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.

1 thought on “Python while input is not empty | Example code”

  1. This does not work in Python 3 it seems. This is my code:

    def detalles_cliente(prompt):
    while True:
    return(input(prompt))
    if prompt:
    return(prompt)
    break

    NOMBRE_CLIENTE = str(detalles_cliente(‘Nombre Cliente: ‘))
    print(NOMBRE_CLIENTE)

    Even if you enter nothing it breaks out with no errors.

Leave a Reply

Discover more from Tutorial

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

Continue reading