Use While True to take multiple inputs in Python using a while loop. Don’t forget to break the loop based on input. Here’s a step-by-step guide on how to achieve this:
- Initialize an empty list to store the inputs.
- Set up a while loop with a condition that allows the loop to continue until a termination input or condition is provided by the user.
- Inside the loop, prompt the user to enter the next input.
- Append each input to the list.
- Exit the loop when the termination condition is met or when you have collected all the desired inputs.
Here’s the Python syntax for taking multiple inputs using a while loop:
# Initialize an empty list to store the inputs
inputs = []
# Set up a while loop with a condition to continue until a termination input or condition is provided
while True:
# Inside the loop, prompt the user to enter the next input
user_input = input("Enter an input (type 'exit' to stop): ")
# Check for the termination condition and exit the loop if met
if user_input.lower() == 'exit':
break
# Append each input to the list (you may need to convert it to the desired data type)
inputs.append(user_input)
# Print the collected inputs
print("Collected inputs:", inputs)
Example take multiple inputs in Python using while loop
Simple example codes Multiple Inputs with Python using While Loop. Exit the loop if the user enters “stop”.
while True:
reply = input("Enter Text: ")
if reply == 'stop':
break
print(reply)
Output:
Another example
Take multiple inputs and append them to the list. If you use an infinite loop then break it if the input is 0.
values = []
while True:
val = int(input("Enter an integer, 0 for Exit: "))
if val == 0:
break
values.append(val)
print(values)
Output:
Enter an integer, 0 for Exit: 1
Enter an integer, 0 for Exit: 2
Enter an integer, 0 for Exit: 0
[1, 2]
Comment if you have any doubts or suggestions on this Python multiple 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.