Using a for loop to take user input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

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) # ---------------------------------------------- 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 user input

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.

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)

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 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.

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.