Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python - local variable referenced before assignment, I can't figure out why this is popping out

These are the instructions: In the Gregorian calendar, three conditions are used to identify leap years:

The year can be evenly divided by 4, is a leap year, unless: The year can be evenly divided by 100, it is NOT a leap year, unless: The year is also evenly divisible by 400. Then it is a leap year.

So I'm writing this code, which needs to be given a year and if the year is a multiple of 4 and 400 it is a leap year. If it is a multiple of 100 it is not:

def is_leap(year):
    k = 400 % year
    m = 4 % year
    p = 100 % year
    if m == 0:
        if p == 0:
            if k == 0:
                leap = True
            else:
                leap = False
    return leap

year = int(input())
print(is_leap(year))

And this is the error message: UnboundLocalError: local variable 'leap' referenced before assignment

I can't figure out why isn't working, leap isn't being used anywhere except for inside the loop

question from:https://stackoverflow.com/questions/65600654/local-variable-referenced-before-assignment-i-cant-figure-out-why-this-is-popp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to define leap so that it exists when the execution doesn't make it to your innermost block.

def is_leap(year):
    k = 400 % year
    m = 4 % year
    p = 100 % year
    leap = False
    if m == 0:
        if p == 0:
            if k == 0:
                leap = True
    return leap

year = int(input())
print(is_leap(year))

Edit:

As others have correctly pointed out there are are some other problems with the code. In my experience date logic is much trickier than one would expect so instead of trying to roll your own I'd recommend using this:

import calendar
calendar.isleap(year)

Calendar documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...