Skip to content

Python for loop user input | Example code

  • by

You can loop around for each input with for loop user input in Python. If you want to take user input and then use a for loop to perform some operations based on that input, you can follow these steps:

  1. Get user input to determine the number of iterations or elements.
  2. Create a for loop to iterate over the specified range or sequence.
  3. Perform desired operations within the loop.

Example asking user input with for loop in Python

Simple example code. First, get the number of loops then use create an empty list. Loops around for each input and Appends new input values.

loops = int(input("Amount of loops: "))

lis = []

for x in range(loops):
    lis.append(input("Input: "))

print(lis)

Output:

Python for loop user input

Another example

Here’s an example where the user provides the number of elements and then enters those elements. The program will then print each element:

# Step 1: Get the number of elements from the user
num_elements = int(input("Enter the number of elements: "))

# Step 2: Create a for loop to iterate over the range of elements
for i in range(num_elements):

    # Step 3: Get each element from the user and print it
    element = input(f"Enter element {i+1}: ")
    print(f"Element {i+1}: {element}")

In this example, we first use input() to get the number of elements the user wants to enter. Then, using range(num_elements) in the for loop, we iterate the same number of times as the user specified. Within the loop, we use input() again to get each element from the user and then print it.

Keep in mind that this example assumes the user will enter valid input (i.e., a number for the number of elements and corresponding elements for the specified number of times). To handle potential exceptions or errors, you may want to include appropriate error-checking and validation in your code.

Do comment if you have any doubts or suggestions on this user input code.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *