Computer Science Notes

COMS 261 - Fall 2026

Jump to: COMS 261 homepage, Week 1, Week 2, Week 3, Week 4, Week 5, Week 6, Week 7, Week 8, Week 9, Week 10, Week 11, Week 12, Week 13, Week 14, Week 15

Week 1 Notes

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

Mon, Aug 24

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:

  1. Try out each of the operations +, -, *, /, ** in the shell.

  2. Why doesn’t the following command calculate 5\sqrt{5}? How could you fix it?

    5 ** 1 / 2

We 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.

  1. 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)

Additional practice

  1. Which of the following Python commands work? Try them in the shell to find out.

  2. Write 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).

Wed, Aug 26

Variable Name Rules

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.

Functions

We talked about the following built-in functions.

We talked how to call functions with arguments:
function_name(argument1, argument2, …)
  1. How many spaces can you put between a function and its arugment(s)? How many should you have?

We 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.

  1. Write a program to calculate the roots of a quadratic polynomial ax2+bx+ca x^2 + bx + c using the quadratic formula x=b±b24ac2a.x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}.

Additional practice

  1. Write a program to calculate miles per gallon and print the output rounded to 1 decimal place.

  2. 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.

  3. What happens if you type math.sin without an input?

  4. What happens if you enter help(math.sin)?

  5. What does the degrees() function do?

  6. How could you calculate π\sqrt{\pi} (i.e., the square root of pi) using the math library?

Thu, Aug 27

Today we talked about some of the isses that came up in the quadratic formula programs from yesterday.

Statements versus Expressions

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 expression

You 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.

Breaking Up Code

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.

Conditional Statements (If-Then-Else Statements)

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:

  1. Write a program that uses if-then-else statements to print the largest of three numbers, aa, bb, and cc. You can assume that all three numbers are different (no repeat values).

Fri, Aug 28

Algorithms and Flow Charts

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:

Binary Numbers

Computers store numbers & data in binary. We talked about how to write whole numbers in base-2.

  1. Convert (110)2(110)_2 to base-10.

  2. Convert (10101)2(10101)_2 to base-10.

  3. Convert (0.1)2(0.1)_2 to base-10.

  4. Convert (10.11)2(10.11)_2 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:

  1. Use the algorithm above to convert 13 to base-2.

After we introduced binary numbers, we talked about bits and how many integers can be stored using nn bits.

  1. How many 4-bit numbers are there?

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.

Floating Point Numbers

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.

  1. Compare the output you get when you type 2**1024 versus 2.0**1024 in the Python shell.

  2. 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.

  3. Why do you get an incorrect answer when you enter 0.1+0.1+0.1?

We finished with this workshop:


Week 2 Notes

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

Mon, Aug 31

Defining Functions

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
5

In 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.

  1. Calculate the area of a circle based on its radius.

Return Values

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.

  1. 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.

  1. Change the circle_area function to return the area of a circle instead of printing the area.

Additional Practice

  1. Write a multiply_by_2 function that returns twice its input.

Wed, Sep 2

Today we talked some more about functions. We introduced local variables and global variables. Compare these two programs.

def circle_area(radius):
    PI = 3.14
    area = PI * radius ** 2
    return area
radius = 5
PI = 3.14 
area = PI * radius ** 2    

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) * height
  1. Write a Python program with the following functions: Both functions should input the price of an item.

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)
  1. What happens if you call countdown with a negative number as the argument? Why does that happen?

  2. What happens if you call countdown with a large value like 1000?

Additional Practice

  1. Write a recursive function to make triangles of different sizes like this:

    **        ***        ****         *****
    *         **         ***          ****
              *          **           ***
                         *            ** 
                                      *

Thu, Sep 3

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.

  1. Write a function to print the positive odd numbers below n. 

  2. Write a function to print the first n perfect squares (i.e., 1, 4, 9, 16, etc.)

  3. 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 total

Additional Practice

  1. Write a function to print an upside down triangle with n rows:

     ****
     ***
     **
     *
  2. Write a function to print a hollow n-by-n square, like this example when n is 4:

     ****
     *  *
     *  *
     ****
  3. 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. 

  4. Write a function called sum_of_squares that adds up all of first n positive perfect squares.

Fri, Sep 4

Today we played with turtle graphics using the turtle module in Python.

  1. Use the commands forward(100) and left(90) to draw a rectangle.

  2. Write a function to draw a rectangle of any length and width.

  3. 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:

  1. Use the circle(radius) function to draw a picture like this one.

  2. 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.


Week 3 Notes

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

Wed, Sep 9

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)
  1. How could you re-write this program with a for-loop? Which is easier?

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!")

In-Class Exercises.

  1. Write a while-loop to print the odd numbers between 0 and n. 

  2. 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.

Additional Practice

  1. 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!")
  2. Write a while-loop to repeat a string until the total length is more than nn. You’ll need to use the len function which returns the length of a string.


Week 4 Notes

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

Week 6 Notes

Day Section Topic
Mon, Sep 28 TP8 Strings
Wed, Sep 30 TP8 Strings con’d
Thu, Oct 1 Review
Fri, Oct 2 Midterm 1

Week 7 Notes

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)

Week 8 Notes

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

Week 9 Notes

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

Week 10 Notes

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

Week 11 Notes

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

Week 12 Notes

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

Week 13 Notes

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

Week 14 Notes

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

Week 15 Notes

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