Ryan Singh

Exam 2 review: functions, files, exceptions and lists

Tutorial · ISA 281: Concepts in Business Programming, part 2 of 3

#python#pandas#teaching

The second exam review covers chapters 5 to 7. As before, the slides and the practice notebook go in the same order: open it in Colab, make a copy and code along. The file exercises read students.txt; upload it to Colab’s Files panel first.

One request from the session: turn off code completions (GitHub Copilot or similar) while you practise. You learn far more by getting stuck than by accepting suggestions.

The feedback from the first review was “more coding, please”, so this one is heavier on exercises.

Chapter 5: functions

A function is a named block of code that only runs when you call it. You can pass data into it (parameters), and it can hand data back (a return value). Functions keep programs modular: each piece does one job and can be tested on its own.

def area(width, height):
    return width * height

area(10, 10)   # 100

Default arguments

A parameter can have a default value, used when the caller leaves it out:

def area(width, height=10):
    return width * height

area(10)      # 10 x 10 = 100
area(5)       # 5 x 10 = 50
area(5, 5)    # 5 x 5 = 25

Local variables and scope

A variable assigned inside a function is local to it. Its scope, the part of the program where it can be used, is that function only.

def make_greeting(name):
    message = f"Hello, {name}"   # local to make_greeting
    return message

make_greeting("Ryan")
print(message)   # NameError: message is out of scope here

Chapter 6: files and exceptions

Opening and closing files

open() creates a file object connected to a file on disk:

file = open("example.txt", "r")   # "r" read, "w" write, "a" append
data = file.read()
file.close()

Closing matters: it releases the file and makes sure anything you wrote is actually saved. The with statement closes the file for you, even if something goes wrong, so prefer it:

with open("example.txt", "r") as file:
    data = file.read()

Exceptions

Errors happen: a file is missing, a user types letters where you wanted a number. try lets you handle them instead of crashing.

try:
    amount = float(input("Amount: "))
except ValueError:
    print("Please enter a number.")
else:
    print(f"You entered {amount:.2f}")   # runs only if there was no error
finally:
    print("Done.")                       # runs no matter what

Slicing a pandas DataFrame

With pandas you select rows and columns by position using iloc, as df.iloc[rows, columns], where each part is a start:stop slice:

import pandas as pd

df = pd.read_csv("sales.csv")
df.iloc[0:5, 0:2]   # first 5 rows, first 2 columns
df.iloc[:, -1]      # every row, last column

Chapter 7: lists

Lists store several items in one variable, in order:

fruits = ["apple", "banana", "cherry"]
print(fruits[0])     # apple
fruits.append("mango")

Slicing works like range: list[start:stop:step], stopping before stop.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[2:5]    # [2, 3, 4]
numbers[::2]    # [0, 2, 4, 6, 8]
numbers[::-1]   # the list reversed

Why care? Lists of numbers are the start of vectors and matrices, and matrix multiplication is the engine of modern AI. That’s a big part of why Nvidia, whose chips do it extremely well, became the most valuable company in the world. (For a beautiful explanation of the maths, see 3Blue1Brown.)

Further reading