| 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.
Use the flow chart below to 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. 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.
Today we talked about while-loops again. We started with Heron’s algorithm for finding square roots.
What happens when you compute square_root(10) with
this function? Why doesn’t it work?
def square_root(a):
"""Uses Heron's algorithm to find the square root of a."""
x = a
while x**2 != a:
x = (x + a/x) / 2
return xWe talked about why it is a bad idea to use != and
== with floating point numbers. We also talked about the
difference between a single equal sign = which is the
Python assignment operator versus a double equal sign
== which is a Python comparison operator.
Python has 6 comparison operators: (==, !=,
>, <, >=, and
<=).
Here is a better way to write the square root function. Notice the accuracy parameter has a default value.
def square_root(a, accuracy = 10 ** (-12)):
"""Uses Heron's algorithm to find the square root of a."""
x = a
while abs(x**2 - a) > accuracy:
x = (x + a/x) / 2
return xNext we looked at an example with an accumulator variable.
"""Keeps track of the running total of numbers entered by the user."""
print("Enter integers to add. Enter the word done when you are finished.")
total = 0
while True:
user_input = input("> ")
if user_input == "done":
break
else:
total = total + int(user_input)
print("The current total is:", total)Re-write this program using a loop without a break statement.
Re-write this program as a function that returns the final total
when the user enters “quit”. Note: the return keyword also
breaks out of loops.
Write a factorial function using a loop. Recall that
the factorial function inputs a positive integer
and returns the product of 1 * 2 * 3 * ... * n.
Write a program to add the fractions for up to 100. Would it be better to use a while-loop or a for-loop?
Write a program to add the fractions until the total is greater than 100. Would it be better to use a while-loop or a for-loop?
Today we talked about Python operators. We
introduced the modulus (%) and
floor division (//) operators with these
examples:
23 // 5
23 % 5
-100 // 12
-100 % 12
What day of the week will it be exactly one month from now on October 11 (without looking at a calendar)?
We also reviewed how the Boolean operators
and, or, and not work.
(True and False) or not TrueThen we did this workshop in class.
days that inputs a number of
minutes, and then prints how long that is in days and hours and leftover
minutes. For example, days(3015) should print 2 days, 2
hours, and 15 minutes.| Day | Section | Topic |
|---|---|---|
| Mon, Sep 14 | TP5 | Integer division and modulus |
| Wed, Sep 16 | TP5 | Integer division and modulus |
| Thu, Sep 17 | TP8 | Strings indices & slicing |
| Fri, Sep 18 | TP8 | String methods |
We started today by talking about how to trace a loop or a program. We did this example in class:
n = 365
total = 0
while n > 0:
digit = n % 10
total = total + digit
n = n // 10
print(total)To trace a program, make a table with a column for every variable in the program. Follow the program line by line, and update the values of the variables in the columns as you go.
After that, we did these programming exercises involving modular arithmetic.
For any integer , the Collatz sequence is obtained by following this rule:
Write a function with a while-loop to print the Collatz sequence for any positive integer . The Collatz conjecture is a famous unsolved math problem which predicts that you will eventually reach 1 no matter which you start with.
Write a function called collatz_length that returns
the length of a Collatz sequence starting at
instead of printing the sequence.
Use the collatz_length function to find longest
Collatz sequence for the numbers from 2 to 999.
Which number between 2 and 999 has the longest Collatz sequence?
We began by reviewing the coins problem from last time. Then we did these exercises in class.
Write a function to print all positive integer divisors of
.
For example, divisors(12) should print the numbers 1, 2, 3,
4, 6, 12.
Write a program to solve Brahmagupta’s Egg Problem (from the 7th century):
An old woman goes to market and a horse steps on her basket and crushes her eggs. The rider offers to pay for the damages and asks her how many eggs were in the basket. She does not remember the exact number, but when she had taken them out two at a time, there was one egg left. The same happened when she picked them out three, four, five, and six at a time, but when she took them seven at a time they came out even. What is the smallest number of eggs she could have had?
Write a function that returns how many divisors
has. For example, count_divisors(12) should return
6.
How could you use the count_divisors function to
print all of the prime numbers below 1000? Recall that a number is prime
if its only divisors are 1 and itself.
A year is a leap year if it is divisible by 4 but not by 100,
unless it is divisible by 400 in which case it is a leap year. For
example, 1900 was not a leap year, but 2000 was. Write a function called
is_leap_year that determines whether a given year is a leap
year or not. It should return a Boolean value (True or
False).
We started by talking about Boolean valued
functions. We did the example of determining whether a year is
a leap year from the additional practice problems yesterday. We ended up
writing two versions of the is_leap_year function, one
using if-then statements (including the else-if keyword
elif):
def is_leap_year(year):
"""Returns True if year is a leap year, otherwise returns False."""
if year % 4 == 0 and year % 100 != 0:
return True
elif year % 400 == 0:
return True
else:
return FalseSince the conditions we are checking are already Boolean expressions, we can skip if-then statements entirely and just return the value of a single Boolean expression:
def is_leap_year(year):
"""Returns True if year is a leap year, otherwise returns False."""
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):You can decide for yourself which version of the
is_leap_year function you prefer. We finished our
discussion of Boolean valued functions with the following exercise.
is_leap_year function in a loop to print the
next 20 years, with an asterisk to mark leap years.After that, we talked about Python strings.
# Some example strings
fruit = "banana"
alphabet = "abcdefghijklmnopqrstuvwxyz"
string = "The quick brown fox"Each character in a string has an index. For
example, the indices of string are shown below.
| string |
T
|
h
|
e
|
q
|
u
|
i
|
c
|
k
|
b
|
r
|
o
|
w
|
n
|
f
|
o
|
x
|
|||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| index |
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
|
11
|
12
|
13
|
14
|
15
|
16
|
17
|
18
|
What is the value of alphabet[3]? What is
alphabet[0]?
How could you get the last character in alphabet?
What error message do you get if you ask for
alphabet[26]?
What happens if you ask for the character at a non-integer index,
like fruit[1.5]?
You can also access characters in a string using negative index values. These count from the end of the string backwards.
| string |
b
|
a
|
n
|
a
|
n
|
a
|
|---|---|---|---|---|---|---|
| negative index |
-6
|
-5
|
-4
|
-3
|
-2
|
-1
|
alphabet[-2]?To get the length of a string, use the Python function
len.
What is len(alphabet)?
What is len("6")?
What is len("")?
You can get a substring by slicing the string using
this pattern: string[start:stop].
"brown" from the string
string = "The quick brown fox"?You can use positive or negative index values when you slice a string. If you want to slice all the way to the end, you can leave the end blank:
alphabet[-3:]?You can loop through the characters of a string using a for-loop:
string = "hello"
for char in string:
print(char)Write a function called count_char. It should input
a string and a character, and return the number of times that character
appears in the string. For example
count_char("banana", "a") # should return 3. Write a loop to print all consecutive substrings of a given length. For example,
print_substrings("banana", 4) # should print "bana", "anan", and "nana" Hint: Unlike the count_char function,
it is not a good idea to loop through the characters in the string.
Instead, loop through the index numbers for the starting positions of
substrings you want to print.
Write a function called count_substrings that inputs
a string and substring, and counts how often that substring appears in
the string. For example
count_substring("banana", "an") # should return 2. Today we talked about string methods. A method is a special kind of function that belongs to the object you are using it on. To call a string method, you use the following syntax.
Python has lots of string methods, but today we talked about some of the most important examples.
The count method. Try the command
"banana".count("a"). What does the count
method do? Does it work if the additional argument is a substring like
"an" instead of a single character?
The find method. Returns the index where the first example of a substring can be found in a larger string. If the larger string does not contain the substring, then it returns .
"banana".find("na")?"banana".find("x")?"banana".find("a")?The upper and lower methods. Try these commands:
"Banana".upper() and
"Banana".lower().
The replace method. What does the replace method
do? Try these examples to see:
"banana".replace("a", "b")
We did these practice problems:
count_vowels that returns how
many vowels (a, e, i, o, u) there are in a string. It helps to use the
.lower() method to avoid having to check for upper case
vowels too.This example let us talk about method chaining when
you call methods like this: x.method1().method2().
Use method chaining to remove punctuation and make every letter
lower case for this string: "hELLo, WOrlD!".
Use method chaining to write an expression that converts a string
to lower case and replaces spaces with dashes. So it should convert
"Week 4 Notes" to "week-4-notes".
| Day | Section | Topic |
|---|---|---|
| Mon, Sep 21 | TP10 | Lists |
| Wed, Sep 23 | TP10 | The in operator |
| Thu, Sep 24 | docs | Sequence types |
| Fri, Sep 25 | TP10 | 2-dimensional lists |
Today we introduced lists in Python. Lists are a type of object the can store more than one value. We introduced how to define a list using square brackets (including an empty list).
# Example lists
fruits = ["apple", "banana", "cherry"]
squares = [1, 4, 9, 16, 25, 36]
mixed = [4, True, "ten", 3.14] # Unlike Java arrays, lists can contain more than one type. len)
There are two different ways to loop through the elements in a list.
|
|
Write a function called multiply that multiplies all
of the numbers in a list together and returns the result. Use a loop
with an accumulator variable to accumulate the product as you
go.
Write a function called print_lengths that inputs a
list of strings, and then prints out the length of each string.
We finished with this example, which requires us to use an empty list
as an accumulator variable, and then add new elements to the list as we
go. To add an element to a list, use the .append
method.
Write a function called return_lengths that inputs a
list of strings, and then returns a new list that contains the length of
each string in the original list. For example:
return_lengths(["apple", "berry", "cherry"]) # Should return [5, 5, 6]We started talking about the in operator in Python. We did this exercise in class:
print_common_elements(list1, list2)
which prints any elements that appear in both list1 and
list2. Hint: You only need to use a single loop combined
with a single if-then statement involving the in
operator.After that we talked about reasons why you would want to loop through the indices of a string or list instead of the elements themselves. We talked about how to solve these two problems:
Write a function to print all continuous length 3 substrings of a string.
Write a function to return the index of the first even element in a list of numbers (or -1 if there are no even elements).
Write a function called repeat_pair that returns
True if a string has two consecutive characters that are the same
(otherwise return False).
What happens if you use your function on a list instead of a string. Does it still work?
We did a workshop in class.
What is "Test this"[-1]?
Can you slice from a range? Try it out: what is
range(10)[2:5]?
Can you add two ranges together? What is
range(4) + range(5)?
Today we introduced 2-dimensional lists. We started with this example. Suppose I have a grid with data like the following:
| Student | Homework | Midterm Exam | Final Exam |
|---|---|---|---|
| Alice Adams | 90 | 85 | 80 |
| Bob Brown | 80 | 90 | 87 |
| Charlie Clark | 60 | 75 | 72 |
| Daisy Davis | 78 | 69 | 75 |
| Edward Evans | 81 | 90 | 97 |
I could store each student’s data in a Python list.
student_data = [
["Alice Adams", 90, 85, 80],
["Bob Brown", 80, 90, 87],
["Charlie Clark", 60, 75, 72],
["Daisy Davis", 78, 69, 75],
["Edward Evans", 81, 90, 97]
]What is the value of student_data[1]?
What is the value of student_data[-1][3]?
How would you select the midterm grade for the 4th student?
Write a for-loop to print every entry in the last column.
Suppose that the final grade for the course above is 20% homework, 30% midterm exam, and 50% final exam. Write a loop that prints each student’s name and their final grade.
Two-dimensional lists are convenient for storing the data in many board games.
board that stores
the data from this tic-tac-toe board.| X | ||
| O | ||
| O | X |
"X" to the top right corner of the
tic-tac-toe board?You can also use double indexing for other data structures, like lists of strings:
Suppose we have a list:
lst = ["How", "are", "you", "today?"]What is lst[3][2]?
Here is an example with triple indexing:
triple = [
["One", "list"],
["Two", "lists"],
["One", "more", "list"]
]What is the value of triple[-1][1][0]?
Write a function called row_sums that inputs a
2-dimensional list of numbers, and returns a list with the sum of the
numbers in each row. For example:
row_sum([[1, 2], [3, 4], [5, 6]]) # should return [3, 7, 11]Write a function called column_sums that inputs a
2-dimensional list of numbers, and returns a list with the sum of the
numbers in each column. You can assume that every row has the same
number of elements. For example:
column_sum([[1, 2], [3, 4], [5, 6]]) # should return [9, 12]| Day | Section | Topic |
|---|---|---|
| Mon, Sep 28 | TP6 | Recursion |
| Wed, Sep 30 | TP6 | Recursion with return values |
| Thu, Oct 1 | Review | |
| Fri, Oct 2 | Midterm 1 |
Today we talked about how to trace a recursive function. We started with this example:
def fib(n):
"""Computes the n-th Fibonacci number"""
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print(fib(5))We made a table showing how the variable n and the
return value change as the function recursively evaluates
fib(5).
| n | return expression | final value |
|---|---|---|
| 5 |
fib(4) + fib(3)
|
5 |
| 4 |
fib(3) + fib(2)
|
3 |
| 3 |
fib(2) + fib(1)
|
2 |
| 2 |
fib(1) + fib(0)
|
1 |
| 1 | 1 | 1 |
| 0 | 0 | 0 |
After that example, we did this:
Write a recursive function is_palindrome to check if
a string is a palindrome (a word that is spelled the same forward and
backward like “racecar”). Hint: Use string[0] and
string[-1] to check if the first and last letters are the
same. Then use string[1:-1] to get the middle part of the
string. A string of length one or zero is automatically a
palindrome.
Write a recursive function to add up all of the numbers in a list.
We started by going over example 2 on the workshop from last time. Then we traced another recursive function example.
def split_string(string):
"""Returns a list of substrings separated by commas."""
if "," in string:
location = string.find(",")
return [string[:location]] + split_string(string[location+1:])
return [string]
print(split_string("1,cat,2,dog"))We made a table to keep track of the variables in the loop, and what gets returned (both the expression and its eventual value).
string
|
location
|
Return expression | Final return value |
|---|---|---|---|
"1,cat,2,dog"
|
1 |
["1"] + split_string("cat,2,dog")
|
["1", "cat", "2", "dog"]
|
"cat,2,dog"
|
3 |
["cat"] + split_string("2,dog")
|
["cat", "2", "dog"]
|
"2,dog"
|
1 |
["2"] + split_string("dog")
|
["2", "dog"]
|
"dog"
|
undefined |
["dog"]
|
["dog"]
|
In Python it is usually recommended to use loops rather than recursion, when possible.
split_string function above without using
recursion. Use a while-loop instead.One way to calculate the remainder of a (positive) number modulo
7 is to subtract 7 repeatedly until you get something smaller than 7.
For example, 30 → 23 → 16 → 9 → 2. Write a recursive function called
mod7 that implements this strategy.
Write a recursive function mod(m, n) that computes
m % n for any integers (assuming that n is not
zero) without using the modulo operator (%) or
division.
| Day | Section | Topic |
|---|---|---|
| Mon, Oct 5 | ||
| 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 |