Skip to content

How to take infinite input in Python | Example code

Use a while loop to take infinite input in Python. Save that input to the other data structure such a list and use any condition to break the while loop.

Example take infinite input in Python

A simple example code takes any type of user to enter a value.

inputs = []
while True:
    inp = input("Type Anything/ Press Enter: ")
    if inp == "":
        break
    inputs.append(inp)

print(inputs)

Output:

How to take infinite input in Python

Another example

inputs = []

while True:
    user_input = input("Enter a value (or 'q' to quit): ")
    
    if user_input == 'q':
        break
    
    inputs.append(user_input)

print("Inputs:", inputs)

In this example, the program prompts the user to enter a value. If the user enters ‘q’, the loop breaks, and the program prints the collected inputs. Otherwise, the user input is added to the inputs list.

The loop will continue indefinitely until the user enters ‘q’ to quit. This allows you to take an infinite number of inputs until the user explicitly chooses to exit.

Keep in mind that an actual “infinite” loop may not be desirable in all cases, as it can potentially lead to an application freeze. However, the example provided demonstrates the concept of collecting inputs until a specific condition is met.

Comment if you have any doubts or suggestions on this Python input program.

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.

4 thoughts on “How to take infinite input in Python | Example code”

  1. I am new in python,I want to make program which accepts as many number from user and add them all when I type ‘s’ I tried but it’s not working please help me…..

    def add_1():

    active = True

    num_1 = []

    while active:

    number = input(“Enter the number: “)

    number = int(number)

    num_1.append(number)

    continue

    if number == ‘s’:

    number = chr(number)

    for nums in num_1:

    x = sum(num_1[0:])

    print(x)

    add_1()

    1. check this code, i didn’t check all cases

      def add_1():
          active = True
          num_1 = []
          while active:
              number = input("Enter the number: ")
              if number == 's':
                  for number in num_1:
                      x = sum(num_1[0:])
                  print(x)
      
              else:
                  number = int(number)
                  num_1.append(number)
      
      
      add_1()
      

Leave a Reply

Discover more from Tutorial

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

Continue reading