I want to make a program that take integer input from user and sum those. There is no fixed amount of parameter. So I write this code. But there is an error. Hope I will get a solution.
Code:
def sum(*args):
tmp = 0
for number in args:
tmp = tmp + number
return tmp
temp = [int(i) for i in input().split()]
sum(temp)
print(temp)
Error:
10 20 30
Traceback (most recent call last):
File "D:/PyCharm/test2.py", line 8, in <module>
sum(temp)
File "D:/PyCharm/test2.py", line 4, in sum
tmp = tmp + number
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Process finished with exit code 1
You need to unwrap your list before passing it in:
sum(*temp)
That way, args
will be the list [10, 20, 30]
. Instead if you just call sum(temp)
then args will be a list of the arguments so it will just end up being a single element list of a list [[10, 20, 30]]
which is not what you want
Your sum()
function puts all arguments passed to it in a tuple, because you used *args
. You called the sum()
function with one argument, which is a list. So args
is a tuple with one element, a list:
>>> def demo(*args): return args
...
>>> demo([42, 81])
([42, 81],)
You then loop over the tuple, and tried to sum the list object.
Either remove the *
from the args
parameter (and just accept a single argument), or pass the values of your list to sum()
by using the *
in the call too:
def sum(args):
# ... all the same code
# ...
result = sum(temp)
or
result = sum(*temp)
You are also ignoring the return value of the sum()
function and are printing the inputs. If you wanted to print the result, then pass that result to print()
. In the above examples I added a result
variable, print that variable.
There are two errors:
after calling sum(temp)
, you should assign result to a variable and print it.
sum
should take list, not *list.
Your code should look like this:
def sum(args):
tmp = 0
for number in args:
tmp = tmp + number
return tmp
temp = [int(i) for i in input().split()]
result = sum(temp)
print(result)
Prints:
$ python3 suminputs.py
3 4 5
12
$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.