| Date | Section | Topic |
|---|---|---|
| Mon, Aug 24 | TP1 | Introduction to Python & Thonny |
| Wed, Aug 26 | TP2 | Variables & functions |
| Thu, Aug 27 | TP2 | Statements versus expressions |
| Fri, Aug 28 | Binary & floating-point numbers |
Today we introduced Python and the Thonny IDE (Integrated Development Environment).
We learned how to use the Python Shell and how to write Python scripts. We also covered the following:
+, -,
*, /, **)int, float,
and str)Try out each of the operations +, -,
*, /, ** in the shell.
Why doesn’t the following command calculate ? How could you fix it?
5 ** 1 / 2We talked about how operators follow an order of
operations, and if operators have the same level of precedence,
then they are computed left to right. We also talked about how some
operators don’t work for all types. For example, the +
operator concatenates strings, but the * operator is not
defined for strings.
Write a script to calculate the volume of a sphere.
# A script to calculate the volume of a sphere.
PI = 3.14159
radius = 4
volume = 4 / 3 * PI * radius ** 3
print("The volume of the sphere is:", volume)Which of the following Python commands work? Try them in the shell to find out.
n = 44 = nx = y = 1Write a program which uses two variables miles and
gals and prints out the miles per gallon for a car on a
tank of gas. Your output should look something like
You got 37.5 miles per gallon.
(depending on the values of your variables).
_.It is recommended to only use lower case letters only in most
variable names (except when you want to indicate that the variable is
constant and won’t ever change, in which case ALL_CAPS is
recommended). If a variable name has multiple words, then separate the
words with an underscore character, like: surface_area.
We talked about the following built-in functions.
printint, float, str (type
conversion functions)typeabs, roundhelpWe finished by talking about how to import functions
from modules. We imported the math module
which contains familiar math functions like sin(),
cos(), and sqrt(). You can use the command
dir(math) to list all of functions in the math
module.
Write a program to calculate miles per gallon and print the output rounded to 1 decimal place.
How could you tell if the sine and cosine function expect the input in degrees or radians? Test your idea in the shell and see what the default is.
What happens if you type math.sin without an
input?
What happens if you enter help(math.sin)?
What does the degrees() function do?
How could you calculate (i.e., the square root of pi) using the math library?
Today we talked about some of the isses that came up in the quadratic formula programs from yesterday.
The first error we looked at was this incorrect line of code:
(x1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))To explain this error, we talked about the difference between statements and expressions in Python.
Every expression is a statement, but not vice versa. In Python, every valid line of code is a statement.
# Example statements
import math
a = 5.0
b = 3 + a
print("Hello")
# Example expressions
1+1
5.0
(-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)Notice that statements can include expressions. A special kind of statement is an assignment statement where you assign a value to a variable. Every assignment statement has the form:
variable_name = # some expressionYou can always wrap an expression in parentheses, and it will still
be an expression with the same value. But, the reason the line of code
(x1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)) is
not correct is that an assignment statement is not an expression, and
cannot be wrapped in parentheses.
It is a good idea to break code into small reusable pieces. We compared some different implementations of the quadratic formula from last time to see how we could make the code easier to read, and also easier to fix if something goes wrong.
We finished by introducing if-then-else statements in Python. We ran into the problem that our quadratic formula program sometimes gives and error message if you try to take the square root of a negative number. To fix this, we added an if-then statement to check that the number inside the square root is not negative before trying to calculate the two roots.
import math
a = 1
b = 2
c = 3
if (b**2 - 4*a*c >= 0):
x1 = (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)
x2 = (-b - math.sqrt(b**2 - 4*a*c)) / (2*a)
print("The roots are", x1, "and", x2)
else:
print("There are no roots.")We finished with this challenge problem:
Yesterday, we used a lot of different approaches to find the maximum of three distinct numbers. As we saw, it can get challenging to keep track of the logic. Engineers often use a flow chart to keep track of the steps in an algorithm.
Here is one possible flow chart for an algorithm to find the largest of three numbers:
Computers store numbers & data in binary. We talked about how to write whole numbers in base-2.
Convert to base-10.
Convert to base-10.
Convert to base-10.
Convert to base-10.
After that we talked about how to convert base-10 integers to base-2. That is a little bit harder, so we introduced the algorithm below which can be described using a flow chart:
After we introduced binary numbers, we talked about bits and how many integers can be stored using bits.
The maximum number of rupees (money) you could have in the original Zelda game was 255 because the data was stored using 8 bits.
Unlike a lot of programming languages, Python allows arbitrarily large integers. This avoids integer overflow errors, but it can be slower for large integers.
We also talked about how computers store floating point numbers. Most modern programming languages (including Python) store floating point numbers using the IEEE 754 standard.
Because there are only a limited number of bits to store floating point numbers, there is a limit to how large and how accurate they can get.
Compare the output you get when you type 2**1024
versus 2.0**1024 in the Python shell.
Compare the output for 2.0**(-1024) versus
2**(-1070). Notice that you lose precision with small
floating point numbers, but you don’t get an error the way you do with
large floats.
Why do you get an incorrect answer when you enter
0.1+0.1+0.1?
We finished with this workshop:
| Day | Section | Topic |
|---|---|---|
| Mon, Aug 31 | TP3 | Functions |
| Wed, Sep 2 | TP3 | Local vs. global variables |
| Thu, Sep 3 | TP4 | For loops |
| Fri, Sep 4 | TP4 | Turtle graphics |
To create your own functions in Python, use the def
keyword to define them:
def hello():
print("Hello!")Every function is a function object. So
function is a type just like int,
float, and str. When you refer to a function
object in Python, there is a difference between the
name of the function (which is hello in
the previous example) and the way you call the function
to get it to run by typing hello(). Here is another
function example.
def print_twice(string): # The first line is called the **header**
print(string) # All of the other lines are called the **body of the function**
print(string) # The code in the body must be indented
# Code that is not indented is not part of the function.
print_twice("Hello!")This function has a parameter which is the variable
called string in the parentheses. We you call this
function, you need to include an argument which is a
value for the parameter.
>>> print_twice("Hello")
Hello
Hello
>>> print_twice(5)
5
5In this example, “Hello” and 5 are arguments. The variable called
string in the function is a parameter. Weirdly, when we
pass the argument 5 to the function, then the parameter called
string stores the value 5 which is an integer not a string!
But that is okay, because Python knows how to print integers.
When you create a function, you should always include a docstring that briefly explains what the functions does. A docstring is a comment that is written using triple quotes instead of the hash symbol. Here is an example.
def hypot(a, b):
"""Calculates the hypoteneuse of a right triangle with legs a and b."""
c = math.sqrt(a ** 2 + b ** 2)
print(c)The advantage of a docstring over a regular comment is that it can take up multiple lines. Python style guides recommend using docstrings even for one line descriptions of functions, since you might need to add more explanation later.
Functions can have as many parameters as needed. Try to make your own functions to do the following.
Some functions return values and some functions don’t. For example,
math.sqrt(4) returns the value 2.0, so it can
be used as an expression. But the function print("Hello")
does not return a value.
What are the values of the variables x and
y below?
x = print(4)
y = abs(-5)To create a function that returns a value, use the return keyword.
circle_area function to return the area of a
circle instead of printing the area.multiply_by_2 function that returns twice its
input.Today we talked some more about functions. We introduced local variables and global variables. Compare these two programs.
|
|
Any variable created in a function body is local, which means it can only be used inside the function. You won’t have access to local variables outside the function. Variables defined in a program that aren’t parameters or defined in the body of a function are global and can be accessed anywhere in a program. But if you try to change the value of a global variable inside of a function, it creates a new local variable inside the function instead!
Important: Avoid using global variables, except for constants.
Here is a function that calls another function in its body:
def cylinder_volume(radius, height):
"""Returns the volume of a cylinder."""
return circle_area(radius) * heightsales_tax that returns the sales tax
(5.3% in Virginia) for an item.print_receipt that prints three
things: The base price of the item, the sales tax, and the total
price.We finished by introducing recursive functions which are functions that call themselves. In order to make a recursive function that doesn’t get stuck looping forever, you need to use an if-then statement with an escape condition. For example:
def countdown(n):
"""Print the numbers from n down to 1."""
if n > 0:
print(n)
countdown(n - 1)What happens if you call countdown with a negative
number as the argument? Why does that happen?
What happens if you call countdown with a large
value like 1000?
Write a recursive function to make triangles of different sizes like this:
** *** **** *****
* ** *** ****
* ** ***
* **
*Today we introduced for-loops. We started with two example functions to demonstrate how they work.
def box(n):
"""Prints an n-by-n square made of * symbols."""
for i in range(n):
print("*" * i)
def countup(n):
"""Print the first n positive numbers."""
for i in range(1,n+1):
print(i)These examples use the range function. (Try asking ChatGPT or Claude to explain the Python range function).
Python is zero-indexed which means that by default it starts counting at zero.
Write a function to print the positive odd numbers below n.
Write a function to print the first n perfect squares (i.e., 1, 4, 9, 16, etc.)
Write a function to print a triangle with n rows like this:
*
**
***
****We finished by talking about accumulator variables in loops. I showed this example.
def add_odd_numbers(n):
"""Returns the sum of the odd numbers less than n."""
total = 0 # total is an accumulator variable
for odd in range(1, n, 2):
total = total + odd
return totalWrite a function to print an upside down triangle with n rows:
****
***
**
*Write a function to print a hollow n-by-n square, like this example when n is 4:
****
* *
* *
****Write a function that uses a for-loop with an accumulator variable to multiply the numbers 1, 2, …, n. In other words, write a function to compute the factorial of n.
Write a function called sum_of_squares that adds up
all of first n positive perfect squares.
Today we played with turtle graphics
using the turtle module in Python.
Use the commands forward(100) and
left(90) to draw a rectangle.
Write a function to draw a rectangle of any length and width.
Write a function to draw an equilateral triangle.
Here is an example using a for-loop to make a polygon with any number of sides.
from turtle import *
def polygon(side_length, n):
"""Draw a polygon with n sides."""
for i in range(n):
forward(side_length)
left(360 / n)Use for-loops to implement these examples:
Use the circle(radius) function to draw a picture
like this one.

Write a function to draw a bullseye with n rings, like this:

Hint: To get circles with the same center, you need to move the
turtle from the center the edge of the circle without drawing a line.
Use the penup() function before moving to avoid drawing.
Then use pendown() to resume drawing when you
move.
| Day | Section | Topic |
|---|---|---|
| Mon, Sep 7 | Labor day, no class | |
| Wed, Sep 9 | TP7.3 | While-loops |
| Thu, Sep 10 | TP7.3 | While-loops con’d |
| Fri, Sep 11 | TP5 | Boolean expressions |
Today we introduced while-loops. A while-loop is an alternative to a for-loop that is often useful when you don’t know how many steps you need to repeat. We started with these examples:
Example 1: Counter
count = 0
while count < 100:
count = count + 1
print(count)Example 2: Password checker
password = input("Enter the password. ")
while password != "banana":
print("That's not the correct password.")
password = input("Enter the password. ")
print("Welcome, you entered the correct password!")Write a while-loop to print the odd numbers between 0 and n.
Write a guessing_game program. It should have a
while-loop that runs until the user inputs the correct number. If the
user guesses the wrong number, tell them if they are too high or too low
before their next guess (following the flow-chart below). Hint: Be sure
to convert the user input from a string to an integer using the
int function.

Change the following function so that it uses a while-loop instead of a for-loop:
def countdown(n):
"""Count down from an integer n, printing each number. When you get to zero, print 'Go!'"""
for i in range(n, 0, -1):
print(i)
print("Go!") def countdown(n):
"""Count down from an integer n, printing each number. When you get to zero, print 'Go!'"""
while n > 0:
print(n)
n = n - 1
print("Go!")Write a while-loop to repeat a string until the total length is
more than
.
You’ll need to use the len function which returns the
length of a string.
| Day | Section | Topic |
|---|---|---|
| Mon, Sep 14 | TP5 | Boolean expressions con’d |
| Wed, Sep 16 | TP5 | Integer division and modulus |
| Thu, Sep 17 | TP5 | Integer division and modulus |
| Fri, Sep 18 | TP5 | Recursion |
| Day | Section | Topic |
|---|---|---|
| Mon, Sep 28 | TP8 | Strings |
| Wed, Sep 30 | TP8 | Strings con’d |
| Thu, Oct 1 | Review | |
| Fri, Oct 2 | Midterm 1 |
| Day | Section | Topic |
|---|---|---|
| Mon, Oct 5 | Mutability and immutability | |
| Wed, Oct 7 | TP14.2 | Reading files |
| Thu, Oct 8 | TP14.2 | Reading files |
| Fri, Oct 9 | TP10.7 | Common patterns in loops (map, filter, reduce) |
| Day | Section | Topic |
|---|---|---|
| Mon, Oct 12 | Fall break, no class | |
| Wed, Oct 14 | More map, filter, & reduce examples | |
| Thu, Oct 15 | TP19.2 | List comprehensions |
| Fri, Oct 16 | TP10 | Dictionaries |
| Day | Section | Topic |
|---|---|---|
| Mon, Oct 19 | TP10 | Dictionary Comprehensions |
| Wed, Oct 21 | C16 | Iterable types |
| Thu, Oct 22 | TP11 | Tuples |
| Fri, Oct 23 | TP11 | Tuples |
| Day | Section | Topic |
|---|---|---|
| Mon, Oct 26 | TP18.1 | Sets and set comprehensions |
| Wed, Oct 28 | Search algorithms | |
| Thu, Oct 29 | Sorting | |
| Fri, Oct 30 | Nested loops |
| Day | Section | Topic |
|---|---|---|
| Mon, Nov 2 | C9.2 | Program structure |
| Wed, Nov 4 | C9.3 | Function structure & incremental development |
| Thu, Nov 5 | C13.3 | Writing to a file |
| Fri, Nov 6 | C13.3 | Writing to a file - con’d |
| Day | Section | Topic |
|---|---|---|
| Mon, Nov 9 | TP14 | Introduction to classes |
| Wed, Nov 11 | TP15 | Magic methods |
| Thu, Nov 12 | TP15 | Static versus instance methods |
| Fri, Nov 13 | TP15 | Calling magic methods |
| Day | Section | Topic |
|---|---|---|
| Mon, Nov 16 | TP16 | Type conversion and casting |
| Wed, Nov 18 | Sequence and iterator types | |
| Thu, Nov 19 | Review | |
| Fri, Nov 20 | Midterm 2 |
| Day | Section | Topic |
|---|---|---|
| Mon, Nov 23 | TP17 | Inheritance |
| Wed, Nov 25 | Thanksgiving break, no class | |
| Thu, Nov 26 | Thanksgiving break, no class | |
| Fri, Nov 27 | Thanksgiving break, no class |
| Day | Section | Topic |
|---|---|---|
| Mon, Nov 30 | Inheritance | |
| Wed, Dec 2 | Practical exams | |
| Thu, Dec 3 | Practical exams | |
| Fri, Dec 4 | Practical exams | |
| Mon, Dec 7 | Review |