Home > Back-end >  the result should be 160 and i don't know the problem
the result should be 160 and i don't know the problem

Time:08-27

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:

  1. You were passing a tuple of numbers instead of the numbers themselves to addition (there was an extra set of parentheses)
  2. 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 had nums = nums-5 all that was doing was causing the current temporary nums variable to be set to zero. And then you had a return in there so that was being returned right away, before the loop could finish.
  3. You had sum(nums) at the end; but sum() only works for a collection. Yet nums was just a number, so if you tried to run that code it would crash.
  4. 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).
  5. 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.
  • Related