Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialsadat sani
4,764 PointsAdding multiple numbers using a function in python
hi guys! so I am trying to add numbers using a function in python. this is the code:
def add(*numbers): for _ in numbers: return sum(_)
digits = int(input('enter numbers to add separated by comma> '))
print(add(digits))
But i get this error: Traceback (most recent call last): File "C:/Users/sani21550/PycharmProjects/MyProjects/random.py", line 60, in <module> digits = int(input('enter numbers to add seperated by comma> ')) ValueError: invalid literal for int() with base 10: '1, 2'
I seem to be suck here.
1 Answer
boi
14,242 PointsApparently, since input
takes a single value at a time (However if the input values are in a limited number, you can unpack the values like a,b = input('>>')
) passing in an unlimited amount of values require some conversions.
Since I am no master, there can be a better method, but anyways, my version does the trick
def add(numbers):
input_data = numbers.split(",")
final_data = []
for _ in input_data:
final_data.append(int(_))
return sum(final_data)
digits = input('enter numbers to add separated by comma> ')
print(add(digits))
To polish this even further you might need exception handling
.in case a str
was passed, but if it is played by the rules of int
there should be no problem
sadat sani
4,764 Pointssadat sani
4,764 PointsThanks!!! Your method works. I will add the exception handling to polish the code.