Python while loop user input | Example code

  • by

You can create a while with user input-based value evaluation with conditions. Just need to take input from the user and evaluate those values in the while loop expression condition.

Example while loop user input in Python

Simple example code takes input from the user and adds values into a list until a quit is entered by the user.

names = []

new_name = ''

# Start a loop that will run until the user enters 'quit'.
while new_name != 'quit':
    new_name = input("Enter Name, or 'quit': ")

    if new_name != 'quit':
        names.append(new_name)

print(names)

Output:

Python while loop user input

Other examples

Check if the input name matched.

name = "not_aneta"

while name != "aneta":
    name = input("What is my name? ")

    if name == "aneta":
        print("You guessed my name!")

Output:

What is my name? aneta
You guessed my name!

Get user input to stop a while loop

x = ""

while x != "0":
    x = input("Enter 0 to exit: ")
    if x == "0":
        print("Stop the loop!")

Output:

Enter 0 to exit: 0
Stop the loop!

Do comment if you have any doubts or suggestions on this Python while loop topic.

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. Required fields are marked *

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