Using a For or While Loop to take user input in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
4 min

banner

# Table of Contents

  1. Using a for loop to take user input in Python
  2. While loop with user Input in Python

# Using a for loop to take user input in Python

To use a for loop to take user input:

  1. Declare a new variable and initialize it to an empty list.
  2. Use the range() class to loop N times in a for loop.
  3. On each iteration, append the input value to the list.
main.py
my_list = [] for _ in range(3): my_list.append(input('Enter a country: ')) print(my_list)

for loop user input

The code for this article is available on GitHub

The first example takes multiple string inputs from a user and appends them to a list.

I used an underscore for the variable name because we don't need to access it.

We used the range() class to iterate 3 times in a for loop and prompt the user for input on each iteration.

The range() class is commonly used for looping a specific number of times in for loops and takes the following arguments:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

main.py
for n in range(3): print(n) result = list(range(3)) # 👇️ [0, 1, 2] print(result)
The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1.

# Using a for loop to take integer user input

If you need to take integer values from user input in a for loop, use the int() class to convert each value.

main.py
my_list = [] for _ in range(3): try: my_list.append(int(input('Enter a number: '))) except ValueError: print('The provided value is not an integer') print(my_list)

for loop integer input

The code for this article is available on GitHub

The input() function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from the input, converts it to a string and returns the result.

The input() function is guaranteed to return a string, even if the user enters an integer.

We used a try/except statement to handle the ValueError that is raised if the int() class is called with a value that is not a valid integer.

# Using a list comprehension instead of a for loop

Alternatively, you can use a list comprehension.

main.py
my_list = [input('Enter a color: ') for _ in range(3)] print(my_list) # ---------------------------------------------- my_list = [int(input('Enter a number: ')) for _ in range(3)] print(my_list)
The code for this article is available on GitHub

The examples use a list comprehension to take multiple inputs from a user.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, the user gets prompted for input.

Note that we can't use a try/except statement for validation in a list comprehension.

# 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

The code for this article is available on GitHub

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.

# Using a while loop to take numeric input

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

The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.