Home > database >  Python - Using a For Loop to create a sum with an exception code
Python - Using a For Loop to create a sum with an exception code

Time:06-24

I need to create a code that adds all numbers in the string L. However, if the number in exc exists in string L, it does not add the number set as exc. For example, exc = 4 L = [3, 4, 5] Then the sum is 8.

Below is what I have so far.

How would I alter the code so that it works?

def summedExcept(exc, L):
    """Takes sum of values in string L except for value defined as exc
    """
    
    sum = 0
    if exc in L:
        



    else:
        for exc in L:
            sum  = L
        

    return sum

CodePudding user response:

You must not call a variable sum in Python as its a built-in function, also you can perform a one-liner comparison inside the for loop to make your code readable and clear:

def summedExcept(exc,L):
    s=0
    for i in L:
        s  = i if i != exc else 0
    return s
    
print(summedExcept(4,[4, 8, 5, 2, 1]))

Output:

16

CodePudding user response:

You should put the if inside the for sentence:

def summedExcept(exc,L):
    sum=0
    for elem in L:
        if elem!=exc:
            sum  = L
    return sum

CodePudding user response:

Above answer works, but just another more concise way to do it:

L = [3,4,5]
exc = 4
print(sum([i for i in L if i != exc])) #8

CodePudding user response:

def summedExcept(exc, L):
"""Takes sum of values in string L except for value defined as exc
"""

if exc in L:

    sum_ = sum(L)-exc

else:
    sum_ = sum(L)

return sum_

This is another solution without added for loops or list comprehensions. Just subtract exc from the sum.

  • Related