'Why do I get 0 when running my "mult(num)" function?
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?
Solution 1:[1]
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))
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lcomrade |
| Solution 2 |
