Python Teasers

Dates

Format codes for the date.strftime and datetime.strftime functions.

"""
semester.py

Print all the dates we meet this semester, one per line.
"""

import sys
import datetime

hours = [
    0, #Monday
    3, #Tuesday
    0, #Wednesday
    3, #Thursday
    0, #Friday
    0, #Saturday
    0  #Sunday
]

holidays = [   #an empty list
]

d = datetime.date(2019, 8, 13)   #starting date (Tuesday)
h = 0 #accumulated hours

while h < 90:
    if d not in holidays:
        day = d.weekday() #0 for Mon, 1 for Tue, etc.
        hw = hours[day]   #how many hours we meet on this day of the week
        if hw > 0:
            h += hw       #means h = h + hw
            print(h, d.strftime("%A, %B %-d, %Y"))
    d += datetime.timedelta(days = 1)

sys.exit(0) #Successful termination.
3 Tuesday, August 13, 2019
6 Thursday, August 15, 2019
9 Tuesday, August 20, 2019
12 Thursday, August 22, 2019
15 Tuesday, August 27, 2019
18 Thursday, August 29, 2019
21 Tuesday, September 3, 2019
24 Thursday, September 5, 2019
27 Tuesday, September 10, 2019
30 Thursday, September 12, 2019
33 Tuesday, September 17, 2019
36 Thursday, September 19, 2019
39 Tuesday, September 24, 2019
42 Thursday, September 26, 2019
45 Tuesday, October 1, 2019
48 Thursday, October 3, 2019
51 Tuesday, October 8, 2019
54 Thursday, October 10, 2019
57 Tuesday, October 15, 2019
60 Thursday, October 17, 2019
63 Tuesday, October 22, 2019
66 Thursday, October 24, 2019
69 Tuesday, October 29, 2019
72 Thursday, October 31, 2019
75 Tuesday, November 5, 2019
78 Thursday, November 7, 2019
81 Tuesday, November 12, 2019
84 Thursday, November 14, 2019
87 Tuesday, November 19, 2019
90 Thursday, November 21, 2019

Count the days we meet.

Intermissions

"""
intermissions.py

Print the time of each intermission, one per line.
Two intermissions would divide the class into three parts.
"""

import sys
import datetime

n = input("How many intermissions do you want? ")

#Make sure n is an integer.
try:
    n = int(n)
except ValueError:
    print(f"Sorry, {n} is not an integer.")
    n = 1
    print(f"I'll assume you wanted to type {n}.")

start = datetime.datetime(2019, 8, 13, 12 + 6, 0) #6:00 p.m.
length = datetime.timedelta(hours = 3)

n += 1      #means n = n + 1.  n is now the number of parts.
length /= n #means length = length / n.  length is now the length of each part.

for i in range(1, n): #Execute the body of the loop n-1 times.
    t = start + i * length
    print(t.strftime("%I:%M %p")) #Add %S for seconds.

sys.exit(0) #Successful termination.
How many intermissions do you want? 1
07:30 PM
How many intermissions do you want? 2
07:00 PM
08:00 PM
How many intermissions do you want? 3
06:45 PM
07:30 PM
08:15 PM
How many intermissions do you want? 4
06:36 PM
07:12 PM
07:48 PM
08:24 PM