def leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
print(leap(1992))
It always returns the none
value but I want to print the bool
in result
Your code
def leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
print(leap(1992))
Let's break it down for 1992.
year = 1992.
1992 % 4 = 0. True. The code moves to next if statement.
1992 % 100 = 92(False). so your codes halts at this point and exits from the function. Hence the None
output for 1992
since you haven't added any logic to return false here.
A simple approach to avoid the None
output would be.
def leap(year):
if year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
return True
else:
return False
print(leap(1992))
Try this:
def leap(year):
return (year%4==0 and year%100!=0 or year%400==0)
This is equivalent to this with if-else format:
def leap(year):
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
return True
else:
return False
else:
return True
else:
return False
You missed out the else parts, and for those cases, the function won't return any boolean value and return None
. The above function can be simplified with removing the return False conditions inside else parts and add one at the last of the function.
def leap(year):
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
return True
else:
return True
return False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.