How to take an unknown number of inputs in Python | Example code

  • by

Use While True with if statement and break statement to take an unknown number of inputs in Python. Break the while when the user just hit enter without any input value.

Example take an unknown number of inputs in Python

Simple example code takes unknown numbers of inputs and stores them into a list object.

inputs = []
while True:
    inp = input()
    if inp == "":
        break
    inputs.append(inp)

print(inputs)

Output:

How to take an unknown number of inputs in Python

This is how to read an unknown number of integer inputs from user:

inputs = []
while True:
    inp = input()
    if inp == "":
        break
    inputs.append(int(inp))

print(inputs)

Output:

1
2
3

[1, 2, 3]

Do comment if you have any doubts or suggestions on this Python input topic.

Note: IDE: PyCharm 2021.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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.