While loop with user Input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 24, 2022

banner

Photo from Unsplash

While loop with user Input in Python #

To take user input in a while loop:

  1. Use a while loop to iterate until a condition is met.
  2. Use the input() function to take user input.
  3. If the condition is met, break out of the while loop.
main.py
# 👇️ while loop with user input strings password = '' while True: password = input('Enter your password: ') if len(password) < 4: print('Password too short') continue else: print(f'You entered {password}') break print(password) # ---------------------------------------- # 👇️ while loop with user input numbers num = 0 while True: try: num = int(input("Enter an integer 1-5: ")) except ValueError: print("Please enter a valid integer 1-5") continue if num >= 1 and num <= 5: print(f'You entered: {num}') break else: print('The integer must be in the range 1-5')

while loop with user input

The first example uses a while loop to iterate until the provided value has a length of at least 4 characters.

If the value is too short, we use the continue statement to continue to the next iteration.
main.py
password = '' while True: password = input('Enter your password: ') if len(password) < 4: print('Password too short') continue else: print(f'You entered {password}') break print(password)

If the value is at least 4 characters long, we use the break statement as the input is valid.

The continue statement continues with the next iteration of the loop.

The break statement breaks out of the innermost enclosing for or while loop.

When validating user input in a while loop, we use the continue statement when the input is invalid, e.g. in an except block or an if statement.

If the input is valid, we use the break statement to exit out of the while loop.

You can use the same approach when validating numeric input.

main.py
num = 0 while True: try: num = int(input("Enter an integer 1-5: ")) except ValueError: print("Please enter a valid integer 1-5") continue if num >= 1 and num <= 5: print(f'You entered: {num}') break else: print('The integer must be in the range 1-5')

while loop with user input numeric

We used a while loop to iterate until the provided input value is in a specified range.

If the try block completes successfully, then the user entered an integer.

The if statement checks if the integer is in the range 1-5 and if the condition is met, we break out of the while loop.

If the integer is not in the specified range, the else block runs and prints a message.

If the user didn't enter an integer, the except block runs, where we use the continue statement to prompt the user again.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.