Wrap-Up Exercise
Overview
Teaching: 0 min
Exercises: 20 minQuestions
How can we put together all of today’s material?
Objectives
Apply use of functions, conditionals and loops to solve a problem.
Review From Yesterday
In your notebook, write a function that determines whether a year between 1901 and 2000 is a leap year, where it prints a message like “1904 is a leap year” or “1905 is not a leap year” as output. Use this function to evaluate the years 1928, 1950, 1959, 1972 and 1990.
Essentially, given this list of years:years = [1928, 1950, 1959, 1972, 1990]
Produce something like:
1928 is a leap year 1950 is not a leap year. 1959 is not a leap year. 1972 is a leap year 1990 is not a leap year.
8 mod 4 equals 0 10 mod 4 equals 2
If you’re not sure where to start, see the partial answers below:
Suggested Approach
First, try to determine how to use the mod operator
%
to determine if a year is divisible by 4 (and thus a leap year or not).Then, create a conditional statement to use this information, and put it into a function.
Finally, create a list of the years given in the exercise. Use a for loop and your function to evaluate these years.
Modular Arthimetic
If a year in the range specified is divisible by four, it is a leap year.
If a number is divisible by 4, then the arithmetic expression “number mod four” (ornum % 4
in Python) will equal zero.Conditional Statement
Fill in the blanks:
year = 1904 if year % 4 == _____: print(year, _______________) ______: print(year, "is not a leap year.")
Function
Fill in the blanks:
def leap_year(year): _________
Loop
Fill in the blanks:
year_list = [1928, 1950, 1959, 1972, 1990] for year in ______: ________(year)
Complete Solution
def leap_year(year): if year % 4 == 0: print(year, "is a leap year") else: print(year, "is not a leap year.") year_list = [1928, 1950, 1959, 1972, 1990] for year in year_list: leap_year(year)
If you have time:
Expand your function so that it correctly categorizes any year from 0 onwards
Instead of printing whether a year is a leap year or not, save the results to a python dictionary, where there are two keys (“leap” and “not-leap”) and the values are a list of years.
Key Points
Use skills together.