How to input n numbers in list one by one?

11,427

Solution 1

The simplest approach is something like this:

n = int(input())
l = [int(input()) for _ in range(n)]

However this has a number of problems:

  • It will crash on invalid inputs.
  • It evaluates the inputs which is dangerous - the user could modify your program state. (Python 2.x)
  • The user could enter floating point numbers and the program won't complain, it will just silently truncate. (Python 2.x)

Instead you can use raw_input and parse the result as an integer. You will also need error handling in the appropriate locations. How you handle errors depend on the program.

You might find this function might be useful as a starting point:

def getNumber(prompt = ''):
    while True:
        try:
            return int(raw_input(prompt))
        except:
            print "Invalid input, try again."

Note that the behaviour of input and raw_input has changed between Python 2.x and Python 3.x. Python 3.x's input function behaves like Python 2.x's raw_input function.

Solution 2

The interface you propose is rather badly designed. Why not simply let the user enter the numbers? Let the computer do the counting, if a count is really needed:

line = raw_input("Numbers: ")
numbers = [int(s) for s i line.split()]

The code will be more complex with error checking, but the basic approach is to make things easier for the user.

Share:
11,427
mahidce
Author by

mahidce

Updated on June 05, 2022

Comments

  • mahidce
    mahidce almost 2 years

    I want my program to ask a value of n. After user inputs the value, program takes input for n values and stores them in a list or something like array (in C). Input must be in the format:

    Enter value of n: 4
    2
    5
    7
    1
    

    I want to store this input in a list for my later use.