How to Take Multiple Inputs Using a Loop in Python
Collecting multiple inputs from users is a common requirement in Python programs: from building simple command-line tools to processing batches of data. Using loops to gather inputs makes your code flexible, handling any number of values without repeating code.
This guide covers three practical approaches: for loops with lists, list comprehension, and while loops with a sentinel value.
Method 1: Using a For Loop with a List
The most straightforward approach asks the user how many inputs they want to provide, then loops that many times to collect each value:
num_inputs = int(input("How many values? "))
values = []
for i in range(num_inputs):
value = input(f"Enter value {i + 1}: ")
values.append(value)
print("Collected values:", values)
Output:
How many values? 3
Enter value 1: apple
Enter value 2: banana
Enter value 3: cherry
Collected values: ['apple', 'banana', 'cherry']
This method is clear and easy to understand. The user knows exactly how many inputs are expected.
Collecting Numeric Inputs
Since input() always returns a string, convert the values if you need numbers:
num_inputs = int(input("How many numbers? "))
numbers = []
for i in range(num_inputs):
num = int(input(f"Enter number {i + 1}: "))
numbers.append(num)
print("Numbers:", numbers)
print("Sum:", sum(numbers))
print("Average:", sum(numbers) / len(numbers))
Output:
How many numbers? 3
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Numbers: [10, 20, 30]
Sum: 60
Average: 20.0
Method 2: Using List Comprehension
List comprehension offers a more concise way to achieve the same result in a single line:
num_inputs = int(input("How many values? "))
values = [input(f"Enter value {i + 1}: ") for i in range(num_inputs)]
print("Collected values:", values)
Output:
How many values? 3
Enter value 1: red
Enter value 2: green
Enter value 3: blue
Collected values: ['red', 'green', 'blue']
For numeric inputs with conversion:
num_inputs = int(input("How many numbers? "))
numbers = [int(input(f"Enter number {i + 1}: ")) for i in range(num_inputs)]
print("Numbers:", numbers)
Output:
How many numbers? 2
Enter number 1: 42
Enter number 2: 58
Numbers: [42, 58]
List comprehension is best when the logic is simple (just collecting and optionally converting inputs). For complex scenarios that require validation or error handling inside the loop, a standard for loop is more readable.
Method 3: Using a While Loop with a Sentinel Value
When you don't know in advance how many inputs the user will provide, use a while loop that continues until the user enters a special sentinel value (like "done" or "exit"):
values = []
print("Enter values one at a time. Type 'done' to finish.")
while True:
user_input = input("Enter value: ")
if user_input.lower() == 'done':
break
values.append(user_input)
print(f"Collected {len(values)} values:", values)
Output:
Enter values one at a time. Type 'done' to finish.
Enter value: Python
Enter value: Java
Enter value: Rust
Enter value: done
Collected 3 values: ['Python', 'Java', 'Rust']
This approach is flexible: the user controls when to stop without specifying a count upfront.
Collecting Numbers with a Sentinel
numbers = []
print("Enter numbers one at a time. Type 'stop' to finish.")
while True:
user_input = input("Enter number: ")
if user_input.lower() == 'stop':
break
numbers.append(float(user_input))
if numbers:
print(f"Numbers: {numbers}")
print(f"Sum: {sum(numbers)}")
else:
print("No numbers entered.")
Output:
Enter numbers one at a time. Type 'stop' to finish.
Enter number: 4.5
Enter number: 7.2
Enter number: 3.8
Enter number: stop
Numbers: [4.5, 7.2, 3.8]
Sum: 15.5
Taking All Inputs on a Single Line
If you want the user to enter all values at once separated by spaces (instead of one per prompt), use split():
# All inputs on one line, separated by spaces
values = input("Enter values separated by spaces: ").split()
print("Values:", values)
# Convert to integers
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
print("Numbers:", numbers)
print("Sum:", sum(numbers))
Output:
Enter values separated by spaces: apple banana cherry
Values: ['apple', 'banana', 'cherry']
Enter numbers separated by spaces: 10 20 30
Numbers: [10, 20, 30]
Sum: 60
This eliminates the need for a loop entirely and is useful when all inputs are available at once.
Adding Input Validation
Real-world programs should handle invalid inputs gracefully. Combine a loop with try/except to keep prompting until valid input is received:
num_inputs = int(input("How many numbers? "))
numbers = []
for i in range(num_inputs):
while True:
try:
num = float(input(f"Enter number {i + 1}: "))
numbers.append(num)
break
except ValueError:
print("Invalid input. Please enter a number.")
print("Numbers:", numbers)
Output:
How many numbers? 2
Enter number 1: abc
Invalid input. Please enter a number.
Enter number 1: 42
Enter number 2: 3.14
Numbers: [42.0, 3.14]
The inner while True loop keeps asking for the same input until a valid number is entered.
Common Mistake: Forgetting to Convert Input Types
A frequent error is performing arithmetic on string inputs without converting them first:
values = []
for i in range(3):
values.append(input(f"Enter number {i + 1}: "))
# WRONG: sum of strings concatenates instead of adding
print("Result:", sum(values))
Output:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The correct approach
Convert to the appropriate type during collection:
values = []
for i in range(3):
values.append(int(input(f"Enter number {i + 1}: ")))
# CORRECT: sum of integers works as expected
print("Result:", sum(values))
Output:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Result: 60
input() always returns a string in Python 3. If you need numbers, explicitly convert with int() or float() before storing or performing calculations.
Collecting Inputs into a Dictionary
Sometimes you want labeled inputs rather than a plain list:
fields = ['Name', 'Age', 'City']
user_data = {}
for field in fields:
user_data[field] = input(f"Enter your {field}: ")
print("\nCollected data:")
for key, value in user_data.items():
print(f" {key}: {value}")
Output:
Enter your Name: Alice
Enter your Age: 25
Enter your City: New York
Collected data:
Name: Alice
Age: 25
City: New York
Quick Reference
| Method | Best For | Number of Inputs |
|---|---|---|
for loop with range() | Known count of inputs | Fixed (user specifies count) |
| List comprehension | Concise collection without validation | Fixed |
while loop with sentinel | Unknown count of inputs | Variable (user decides when to stop) |
input().split() | All inputs on a single line | Variable (determined by spaces) |
for loop with try/except | Inputs requiring validation | Fixed, with retry on error |
Choose the approach that matches your use case: a for loop when the count is known, a while loop when it isn't, and split() when all inputs can be provided at once.