Skip to content

How to take multiple inputs in Python using while loop | Example code

  • by

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:

  1. Initialize an empty list to store the inputs.
  2. 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.
  3. Inside the loop, prompt the user to enter the next input.
  4. Append each input to the list.
  5. 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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading