Python
Programming Exercises, Gently Explained
63
It can also help to draw a flow chart of the general logic on a whiteboard or with paper and pen.
It could look something like this:
Figure 20-1: A flow chart showing the logical steps of determining if a year is a leap year.
Leap year rules have a few exceptions, so this function needs a set of if-elif-else statements.
The order of these statements matters. You could use an if statement to check if the year is divisible
by 4 and, if so, return True.
But before returning, you need another if statement to check if the year
is divisible by 100 and return False. But before that, you need yet another if statement
that returns
True
if the year is divisible by 400. Writing code this way ends up looking like this:
def isLeapYear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
# Year is divisible by 400:
return True
else:
# Year is divisible by 100 but not by 400:
return False
else:
# Year is divisible by 4 but not by 100:
return True
else:
# Year is not divisible by 4:
return False
This code works correctly but is hard to follow. There are several
levels of indentation, and the
nested if-else statements make it tricky to see which else statement is paired with which if
statement.
Instead, try switching around the order of the logic. For example, if the year is divisible by 400,
return True. Or else, if the year is divisible by 100, return False. Or else, if the year is divisible by 4,
return True. Or else, for all other years return False. Writing code this way reduces the amount of
nested if-else statements and produces more readable code.
Python Programming Exercises, Gently Explained
64
Dostları ilə paylaş: