This guide explores how to take user input within loops in Python, using both for and while loops. We'll cover how to:
- Collect a fixed number of inputs.
- Collect input until a condition is met.
- Validate user input (specifically for integers).
- Use list comprehensions.
Taking a Fixed Number of Inputs with a for Loop
Use a for loop with range() when you know exactly how many inputs you need.
Collecting Strings
my_list = []
for _ in range(3): # Loop 3 times
country = input('Enter a country: ')
my_list.append(country)
print(my_list) # Example: ['USA', 'Canada', 'Mexico']range(3): Generates a sequence of numbers from 0 to 2. We use_as the loop variable because we don't actually need the number itself, just the iteration.input('Enter a country: '): Prompts the user for input and returns the entered string.my_list.append(country): Adds the entered string to themy_list.
Collecting Integers with Validation
To collect integers, use int() to convert the input, and always include error handling:
my_list = []
for _ in range(3):
while True: # Keep looping until valid input is received
try:
num_str = input('Enter a number: ')
num = int(num_str) # Try to convert to an integer
my_list.append(num)
break # Exit the inner while loop if successful
except ValueError:
print('Invalid number. Please enter an integer.')
print(my_list) # Example input/output: [2, 3, 4]while True:: This creates an infinite loop that we'll break out of only when valid input is received. This is a very common and useful pattern.try...except ValueError:: This handles the potentialValueErrorthat occurs if the user enters something that can't be converted to an integer (e.g., "abc").break: If the conversion to an integer is successful, thebreakstatement exits the innerwhileloop, and the outerforloop continues.
Using list comprehension
List comprehension can also be used to take multiple inputs.
my_list = [input('Enter a color: ') for _ in range(3)]
print(my_list) # Output (will depend on user input): ['red', 'blue', 'green']- However it is important to know that it is not possible to use a
try/exceptblock to handle exceptions within a list comprehension, which makes it less suitable for scenarios where validation is required.
Taking Input Until a Condition is Met with a while Loop
Use a while loop when you don't know in advance how many inputs you'll need, but you have a condition that determines when to stop.
String Input with Validation
password = ''
while True: # Or: while len(password) < 4:
password = input('Enter your password: ')
if len(password) < 4:
print('Password too short')
continue # Go to the next iteration.
else:
print(f'You entered {password}')
break # The condition has been met.
print(password)- The
while True:loop keeps asking for a password until it has the required minimum length. - The
continuestatement will skip the rest of the loop's code when the input is invalid. - The
breakstatement exits the loop when a valid password is entered.
Numeric Input with Validation
num = 0 # Initialize num
while True:
try:
num = int(input("Enter an integer 1-5: "))
if 1 <= num <= 5: # More concise range check
print(f'You entered: {num}')
break # Exit the loop if input is valid
else:
print('The integer must be in the range 1-5')
except ValueError:
print("Please enter a valid integer 1-5")- A
while Trueloop and atry/exceptstatement will handle invalid input, preventing the program from crashing. - The conditional check verifies that the integer is withing the specified range.