I\'m trying to write a short program which allows the user to input a list of numbers into an input() function, and then using the add_25 function add 25 to each item in a list.
Besides all the input()
aspects covered in the other answers, I'd like to add this completely different aspect:
Your function add_25()
is probably not supposed to change its input. Yours does, or tries to, and fails because tuples do not allow that.
But you actually do not have to change the input (and you should not, because this is not good style due to its ugly side-effects). Instead you could just return a new tuple:
def add_25(mytuple):
return tuple(x + 25 for x in mytuple)
This way, nothing is assigned to a tuple, just a new tuple is created and returned.
In Python 2 input()
will eval the string and in this case it will create a tuple, and as tuples are immutable you'll get that error.
>>> eval('1, 2, 3')
(1, 2, 3)
It is safer to use raw_input
with a list-comprehension
here:
inp = raw_input("Please input a series of numbers, divided by a comma:")
actual_list = [int(x) for x in inp.split(',')]
Or if you're not worried about user's input then simply convert the tuple to list by passing it to list()
.
Also note that as you're trying to update the list in-place inside of the function it makes no sense to return the list unless you want to assign another variable to the same list object. Either return a new list or don't return anything.
The function input
reads a string and evaluates it as a Python expression. Thus, the comma-separated list becomes a tuple of values, these are passed to add_25()
, and this function tries to assign to mylist[i]
something.
And tuples are immutable, they do not support item assignment (on purpose).
You could use actual_list = list(input(...))
to convert the tuple to a list
(which supports item assignment).
But every time someone uses input()
, one has to warn him: input()
is a security risk. It evaluates the input of the user and thus might execute arbitrary things the user typed. This means that your program will perform what the user asks it to, with your permissions. This is normally not what is considered a good design.
If you always will be the only user or if you trust all users of your program completely, then so be it.
def test_tuples_of_one_look_peculiar(self):
self.assertEqual( __,(1).__class__)
self.assertEqual(__, (1,).__class__)