the if condition don't work the result should be 160 and i don't know the problem
def addition(*numbers ):
for nums in numbers :
if nums == 10 :
continue
elif nums ==5:
nums = nums-5
return nums
return sum(nums)
print(addition((10, 20, 30, 10, 15, 5, 100)) )
CodePudding user response:
def addition(*numbers ):
num = 0
for nums in numbers :
if nums == 10:
continue
elif nums == 5:
num = num - 5
continue
else:
num = num nums
return num
print(addition(10, 20, 30, 10, 15, 5, 100))
This code will do it. You just need to have a number (num
) where the values are actually added. This will produce 160. Also, as @RandomDavis said, you had too many parenthesis in print(addition(10, 20, 30, 10, 15, 5, 100))
CodePudding user response:
Alternate version that uses a list
:
def addition(*numbers):
nums = []
for num in numbers:
if num == 10:
continue
elif num == 5:
nums.append(-5)
else:
nums.append(num)
return sum(nums)
print(addition(10, 20, 30, 10, 15, 5, 100))
What needed changing:
- You were passing a tuple of numbers instead of the numbers themselves to
addition
(there was an extra set of parentheses) - You were using
nums
as a temporary variable to store each list item as you iterated through the list, but you were also treating it as if it was an accumulator that you were adding the numbers to; when you hadnums = nums-5
all that was doing was causing the current temporarynums
variable to be set to zero. And then you had areturn
in there so that was being returned right away, before the loop could finish. - You had
sum(nums)
at the end; butsum()
only works for a collection. Yetnums
was just a number, so if you tried to run that code it would crash. - You were not using a list or an accumulator variable to keep track of the sum. You could have either had a number that you added to or subtracted from, or a list that you appended items to. If you were using a number to store the sum you could just return that number at the end. If you were using a list you could return the sum of the list and the end (as I did in my example).
- You were not tallying up the numbers from the
*numbers
argument; they were not being added to a list of any kind, or added to a variable that was being used to keep track of the sum. You were just looping through numbers and doing nothing with them, essentially.