2

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.

Community
  • 1
  • 1

2 Answers2

5

In your function, you can directly convert num into a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:

In [1]: num = '1'

In [2]: num.split(',')
Out[2]: ['1']

In [3]: num = '1,2,3,4'

In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']

You can then use your function as you have it:

def inputnumber():
    num = raw_input('Enter number(s): ').split(',')
    number = map(int,num)
    return number

x = inputnumber()
print x

However you can take it a step further if you want - map here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number and return the result of the comprehension (same would work for map as well, if you want to keep that):

def inputnumber():
    num = raw_input('Enter number(s): ').split(',')
    return [int(n) for n in num]

x = inputnumber()
print x

If you want to handle other types of input without error, you can use a try/except block (and handle the ValueError exception), or use one of the fun methods on strings to check if the number is a digit:

def inputnumber():
    num = raw_input('Enter number(s): ').split(',')
    return [int(n) for n in num if n.isdigit()]

x = inputnumber()
print x

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 :) ):

print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
  • @Geomatics No problem at all, happy it helps :) And sorry, just noticed your edit about handling other words - I'll drop that in as well. – RocketDonkey Jan 05 '13 at 23:49
-1

input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:

def inputnumber():
    num = raw_input()
    for i, j in enumerate(num):
        if j not in ', ':
            try:
                int(num[i])
            except ValueError:
                #error handling goes here
    return num

def main():
    x = inputnumber()
    print x

I guess all it is is a long-winded version of RocketDonkey's answer.

Volatility
  • 31,232
  • 10
  • 80
  • 89
  • But if the input is single number this gives an error: `code` TypeError: 'int' object is not iterable –  Jan 05 '13 at 23:37
  • I edited my answer - it should work now – Volatility Jan 05 '13 at 23:45
  • -1: You (correctly) advise against using `input` because it evaluates the input, and then use `eval` to evaluate the input anyway. This is therefore just as unsafe as using `input` directly. – Blair Jan 05 '13 at 23:57
  • @Blair that's true, I'll change it (although Rocket's answer would probably better anyway) – Volatility Jan 06 '13 at 00:00
  • Your original solution was a clever way of handling it - you can actually get around the pitfalls of `eval` by using the `literal_eval` function in the `ast` module (although on second thought, that won't work in the case of somebody entering a word as opposed to a number, so just ignore me :) ). – RocketDonkey Jan 06 '13 at 00:20