Home > database >  Why do I get 0 when running my "mult(num)" function?
Why do I get 0 when running my "mult(num)" function?

Time:02-11

I am a noob in Python and I got stuck with the following code. I can't figure out why my function 'mult(num') can't calculate sum 'su' even though inside the function when I run print(su, end=" ") it gives all numbers I expect?

def mult(num):
    su = 0
    for i in range(num):
        if i % 3 == 0 or i % 5 == 0:
            su  = i
            return su
            # print(su, end="   ")  when running this line I see >>>> 0   3   8   14   23   33   45   60


print(mult(18))

output

>>>  0

Why do I get 0?

CodePudding user response:

When you execute return su you exit the function. You quit on the first iteration of the loop, so the answer is 0.

Fixed code:

def mult(num):
    su = 0
    for i in range(num):
        if i % 3 == 0 or i % 5 == 0:
            su  = i
            #return su
    
    return su


print(mult(18))

CodePudding user response:

In your code, there is a problem in the indentation of return su. The code should be corrected as follows.

def mult(num):
    su = 0
    for i in range(num):
        if i % 3 == 0 or i % 5 == 0:
            su  = I

    return su

print(mult(18))

Note that the return su is only executed one time even it is inside a loop. That is why your code gets the output as 0.

  • Related