当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Python3, Sum user-given tuple

问题描述:

Code:

def sum_given(values):

s = 0

for i in zip(*values):

s += int(i)

return s

try:

v_list = input("Enter values to be summed.\n> ")

except ValueError:

print('Invalid input. Counting as a zero.')

result_of_sum = sum_given(v_list)

print(result_of_sum)

Output:

$ ./helloworld.py

Enter values to be summed.

> 1,2,3,4,5

Traceback (most recent call last):

File "./helloworld.py", line 13, in <module>

result_of_sum = sum_given(v_list)

File "./helloworld.py", line 6, in sum_given

s += i

TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'

I understand this error, but I'm not sure how to solve it.

What I'm trying to do is allow the user to input a number of values, or a range, and have python output the sum.

I haven't implemented the range yet.

网友答案:

You don't want to use zip and the splat syntax here. Instead, you should use str.split to split the input on commas:

for i in values.split(","):

Below is a demonstration:

>>> def sum_given(values):
...     s = 0
...     for i in values.split(","):
...         s += int(i)
...     return s
...
>>> v_list = input("Enter values to be summed.\n> ")
Enter values to be summed.
> 1,2,3,4,5
>>> result_of_sum = sum_given(v_list)
>>> print(result_of_sum)
15
>>>

Note however that you could use sum and a generator expression to simplify your function:

>>> def sum_given(values):
...     return sum(int(x) for x in values.split(","))
...
>>> v_list = input("Enter values to be summed.\n> ")
Enter values to be summed.
> 1,2,3,4,5
>>> result_of_sum = sum_given(v_list)
>>> print(result_of_sum)
15
>>>
网友答案:

A more pythonic way to do this is to replace the for loop with a sum() over a comprehension, generator, or map.

def sum_given(strValues):
    return sum(int(v) for v in strValues.split(","))

# output 15
print sum_given("1,2,3,4,5")
网友答案:
>>> def sum_given():
...     answer = 0
...     for i in input("Enter numbers: ").split(','):
...         answer += int(i)
...     return answer
... 
>>> sum_given()
Enter numbers: 1,2,3,4,5
15

Alternatively:

>>> def sum_given():
...     return sum(int(i.strip()) for i in input("Enter numbers: ").split(','))
... 
>>> sum_given()
Enter numbers: 1,2,3,4,5
15
分享给朋友:
您可能感兴趣的文章:
随机阅读: