How To Input N Numbers In List One By One?
Solution 1:
The simplest approach is something like this:
n = int(input())
l = [int(input()) for _ inrange(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:
defgetNumber(prompt = ''):
whileTrue:
try:
returnint(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.
Post a Comment for "How To Input N Numbers In List One By One?"