Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn’t handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers’s answer in stackoverflow but couldn’t make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
In your function, you can directly convert
numinto a list by callingsplit(','), which will split on a comma – in the case a comma doesn’t exist, you just get a single-element list. For example:You can then use your function as you have it:
However you can take it a step further if you want –
maphere can be replaced by a list comprehension, and you can also get rid of the intermediate variablenumberand return the result of the comprehension (same would work formapas well, if you want to keep that):If you want to handle other types of input without error, you can use a
try/exceptblock (and handle theValueErrorexception), or use one of the fun methods on strings to check if the number is a digit:This shows some of the power of a list comprehension – here we say ‘cast this value as an integer, but only if it is a digit (that is the
if n.isdigit()part).And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python – condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above 🙂 ):