Reputation:
I am having difficulty understanding why my function does not store the I value that I append onto a list?
The code is:
def numberofdays ():
sum = 0
leapyears = []
for i in range (1901, 2000):
if i%4 == 0:
leapyears.append (i)
sum = sum + 366
else:
sum = sum + 365
return sum + 366 #to account for year 2000.
return leapyears
When I call print numberofdays()
, it only returns 36525
, the sum
value.
Upvotes: 0
Views: 820
Reputation:
Using return
immediately exits a function. Meaning, the return leapyears
line will never be reached because of the return sum + 366
line directly above it.
If you want to return two values from numberofdays
, you can put them in a tuple and return that:
return sum + 366, leapyears
Below is a demonstration:
>>> def func():
... return 1, 2
...
>>> func()
(1, 2)
>>> a, b = func() # You can use iterable unpacking to give the values names
>>> a
1
>>> b
2
>>>
Also, as @JonClements said in his comment, it looks like you actually meant to do range (1901, 2001)
instead of range (1901, 2000)
. Remember that the second argument to range
is always exclusive (not included).
Finally, you can replace code such as sum = sum + 366
with just sum += 366
. This is really a minor issue, but the latter approach is more pythoic. ;)
Upvotes: 3
Reputation: 5919
The return
statements ends the function - as soon as it hits the return
, it's all over.
To return multiple values, you can return (sum+366,leapyears)
Upvotes: 0