r/programminghelp • • Sep 08 '21

Python Functions help

Number of days per month

month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 

def is_leap(x): 
    return x % 4 == 0 and (x % 100 != 0 or x % 400 == 0) 

def days_in_month(year, month):  
        if not 1 <= month <= 12: 
            return "invalid month" 
        if month == 2 and is_leap(year): 
            return 29 
        return month_days[month]

print(days_in_month(2017, 2))

In the function: days_in_month(year, month) in the 2nd if statement how can the is_leap take in the arguement year and still be able to complete its function.

To clarify what I mean is how does the program pick up that when I assign something to the year arguement it has to run the is_leap function even though the is_leap function is coded to have the arguement of x.

If year was 12, would is_leap(year) take that 12 in and replace x with it and then run it?

4 Upvotes

3 comments sorted by

2

u/ConstructedNewt MOD Sep 09 '21

In programming the concept of scoping is relevant here: x is just a local variable (local scoped variable), just like year and month is inside the function days_in_month. This way is_leap(anything), is_leap(1234), is_leap(year) are all valid and inside the "scope" of the function is_leap they are referenced as the variable x.

1

u/biggAzzZuck Sep 09 '21

This makes much more sense with scoping. Thanks for the explaination!

1

u/skellious Sep 09 '21

rather than having a 0 in your month_days list, why not just add as the first line of the days_in_month function

month += 1