Lecture 14 - Looping

Lecture Date: Friday, February 19

Today, we’ll wrap up loops ahead of Test 1!

We’ll continue on with the various types of loops discussed last class and finish up any examples.

If we have time left: let’s take everything we’ve learned up until now to build something interesting. Let’s build a birthday planner!

Our birthday planner will take in a list of names and birthdays. The program will then calculate how many days it is until everyone’s next birthday, display that information, and then give information about which birthday is coming up next.

birthday_planner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Mark Sherriff (mss2x)

import datetime
import calendar

birthdays = {"Mark":datetime.date(1979,11,9), "Amanda":datetime.date(1981,1,1), "Samantha":datetime.date(2014,4,5)}

today = datetime.date.today()

closest_birthday_key = ""
closest_birthday = 0
closest_distance = datetime.timedelta(366)

for key in birthdays.keys():
    next_birthday = datetime.date(today.year, birthdays[key].month, birthdays[key].day)
    if next_birthday-today < datetime.timedelta(0):
        next_birthday = datetime.date(today.year+1, birthdays[key].month, birthdays[key].day)
    print(key + "'s next birthday is " + str(next_birthday) + " and is " + str(next_birthday - today) + " away.")
    if (next_birthday - today) < closest_distance:
        closest_distance = next_birthday - today
        closest_birthday_key = key
        closest_birthday = next_birthday

print(closest_birthday_key + "'s birthday has the next birthday, " + str(closest_birthday) + "!")

print(calendar.month(closest_birthday.year, closest_birthday.month))