DS 208 · Week 2

Types, Control Flow & Functions

Three ideas used in every later lab: the kind of a value, how code makes choices, and how to avoid repeating code.

Programming for Data Science · University of the Philippines Cebu

Outline

Three building blocks of programs

Previous session

From running cells to writing logic

Week 1 covered setting up Python and running existing code. This week covers writing the decisions, and the errors that come with them.

Conceptual model

An error message is information: Python's statement of exactly what it could not do.

Guideline

When a cell fails, read the last line first. It names the problem.

About the tool

Python began in December 1989

1989

Started

Guido van Rossum begins Python at CWI, a research institute in the Netherlands.

1991

First release

Version 0.9.1 is posted publicly in February 1991.

2008

Python 3

A cleaned-up version that is not compatible with Python 2. This course uses it.

2020

Python 2 retired

Support for Python 2 ends on 1 January 2020.

SourceWikipedia: History of Python

About the tool

How widely Python is used

SourcePackages: pypi.org, retrieved 11 Oct 2026; GitHub ranking: GitHub Octoverse 2025

Key terms · Parts A & B

Eight terms for types and control flow

In Week 1, a variable was a name that holds a value (a piece of data): price = 100. This week’s terms concern what kind of value it is, and how code makes choices.

type

The kind of value something is. It determines which operations are allowed.

e.g. type(5) reports int; type("5") reports str

integer (int)

A whole number, with no decimal point. Used for counts and positions.

e.g. 21, 0, -3

float

A number with a decimal point. Used for measurements and averages.

e.g. 21.0, 3.5

string (str)

Text, written inside quotes. Digits in quotes are still text.

e.g. "Cebu", "21"

boolean (bool)

One of exactly two values, True or False: the answer to a yes/no question.

e.g. 5 > 3 gives True

operator

A symbol that does something to values: add, divide, compare…

e.g. +, /, ==, >=

condition

A yes/no question in code. Its answer is a boolean, and it decides whether a block runs.

e.g. score >= 60

loop

Code that repeats a block: once per item (for), or while a condition stays true (while).

e.g. for h in hours: runs once per number in hours

Key terms · Part C

Six terms for functions

Analogy: a function is a recipe, written once, named, and reused as needed. These terms name its parts.

function

A named, reusable piece of work: it takes inputs and gives back a result.

e.g. len([3, 5, 4]) gives back 3

call

Running a function: its name followed by round brackets, with the inputs inside.

e.g. average([3, 5, 4])

parameter

The name, in the function’s definition, that will hold an input.

e.g. numbers in def average(numbers):

argument

The actual value placed in the brackets when the function is called.

e.g. [3, 5, 4] in average([3, 5, 4])

return

Hand a result back to whoever called the function, and stop the function there.

e.g. return total / count

None

Python’s value for “nothing here”. A function with no return gives back None.

e.g. x = print("hi") leaves x as None

Part A

Types

The kind of each value. An incorrect type causes errors in every later step.

Week 1 introduced storing values in variables. This part adds the idea that every value has a type, and the type determines which operations are allowed.

Conceptual model

Python treats 5 and "5" as different things

One is a number that supports arithmetic. The other is text that resembles a number. Many beginner errors are variants of this one.

Every value has a type: the kind of value it is. Python writes types with short names — int for integer, str for string, bool for boolean.

# ask Python what kind of thing each value is values = [5, "5", 5.0, True, [5], None] for v in values: print(type(v).__name__) int str float bool list NoneType
  • values = [5, "5", …]a list: several values in square brackets, in order (more in Week 3)
  • for v in values:a loop: run the indented line once for each value, with v holding the current one
  • print(type(v).__name__)ask for v’s type and print its short name
  • outputint whole number · str text · float decimal · bool True/False · list · NoneType the type of None
Definition

Definition: data type

Data type (Sedgewick & Wayne)

A data type is a set of values and a set of operations defined on those values.

TypeSome of its valuesOne of its operations, here
int…, −1, 0, 1, 2, …10 + 5 adds: 15
str"", "5", "Ana", …"10" + "5" glues: "105"
boolTrue, Falsenot True is False

The same symbol, +, is a different operation for each type: that is why Python treats 5 and "5" as different things.

Source: Sedgewick & Wayne (2017), Introduction to Programming in Python, §1.2.

Common types

Six frequently used types

TypeExamplePurpose
int5Whole numbers — counts, indices
float5.0Numbers with decimals — measurements, averages
str"5"Text — names, labels, anything typed
boolTrueYes/no — the result of a comparison
list[5]An ordered collection of values
NoneTypeNone"Nothing here" — a deliberate blank
Reading an error

The most common type error

age holds the text "21", not the number 21. Python cannot add a number to text, and states this on the last line.

Reading this error

Last line first
TypeError = an operator got a type it cannot work with
The message
“can only concatenate str to str”: + on text means glue together, and it was handed a number
Line number
press Run: the full traceback says line 2 — the print line with age + 1
Check first
the type of each side of the +
# fails on purpose: read the last line age = "21" print("Next year you will be", age + 1) TypeError: can only concatenate str (not "int") to str
Two fixes

Correcting the value or converting at the point of use

Division

Two kinds of division and their result types

Python provides both. / always makes a float; // discards the remainder. The choice depends on the question being asked.

print(7 / 2) # true division: always a float print(7 // 2) # floor division: an int, rounded down print(7 % 2) # the remainder 3.5 3 1
  • 7 / 2 → 3.5ordinary division; the answer is a float (it has a decimal point) — always, even for 4 / 2
  • 7 // 2 → 3floor division: how many whole 2s fit in 7; the leftover is thrown away
  • 7 % 2 → 1remainder (“modulo”): what is left over. x % 2 == 0 is the test for an even number

Common error

"Average score" wants /. "How many full teams of 4?" wants //. The same numbers give different answers.

Numeric strings

"10" and 10 look similar but differ in type

Data read from a file or a form arrives as text, even when it is all digits. Python treats the quotes literally.

print("10" + "5") # glued, not added print(10 + 5) # actually added print(int("10") + 5) # convert first 105 15 15
  • "10" + "5"two strings: + glues them into '105'. The quotes around the answer indicate that it is still text
  • int("10") + 5convert the text to the integer 10 first, then add: 15

Diagnostic sign

If a "sum" comes out as two numbers joined together, one of them is a string.

Booleans as integers

True equals 1 and False equals 0

A boolean is True or False (capital letter, no quotes). Booleans are a kind of integer in Python. This makes counting the true values a one-line operation: sum(passed) adds up the list, counting each True as 1 and each False as 0.

print(True + True) passed = [True, False, True, True] print(sum(passed)) # counts the Trues 2 3

Later use

Summing a list of comparisons counts how many rows pass a test, a technique used throughout the term.

Exercise · 3 min

Types decide what an operation does

Three lines, one operator: *.

Tasks

  1. Predict what each line prints.
  2. Select ▶ Run / Edit and run the code.
  3. Change "5" * 3 to "5" * 0. What prints?

Result on the lecture laptop (select to reveal)

15, then 555 (the text repeated three times), then 15. "5" * 0 prints an empty line: the empty string.

print(5 * 3) print("5" * 3) print(int("5") * 3)
Review question

Question (select to reveal the answer)

What does type(3 / 1) report?

A · int
B · float
C · str
D · It errors

B — float, it is 3.0.

The single / always produces a float, even when the numbers divide evenly. The integer 3 requires //.

Review question

Question (select to reveal the answer)

What does "3" + "4" produce?

A · 7
B · "34"
C · "7"
D · a TypeError

B — "34".

+ on two strings glues them together. It only errors when the types disagree (str + int). The same symbol does a different job depending on type.

Part B

Control flow

Making code choose, and making it repeat.

Part A covered the kinds of values. So far, code has run every line once, top to bottom; this part lets it skip lines (a choice) and repeat lines (a loop).

Conditionals

if runs a block only when something is true

A condition is a yes/no question such as score >= 90 (“is score at least 90?”). elif (short for “else if”) and else cover the other cases. Python checks them top to bottom and stops at the first match.

A line ending in a colon : owns the block of indented lines under it (4 spaces in). Indentation is not decoration in Python: it says which lines belong to which choice.

score = 73 if score >= 90: grade = "excellent" elif score >= 75: grade = "good" elif score >= 60: grade = "passing" else: grade = "needs work" print(grade) passing
  • if score >= 90:73 ≥ 90? False → skip its block
  • elif score >= 75:73 ≥ 75? False → skip
  • elif score >= 60:73 ≥ 60? True → run grade = "passing", then jump past the rest
  • else:runs only when every condition above was False
  • print(grade)not indented, so it always runs: prints passing
Common error

The order of the branches changes the answer

Python takes the first branch that is true, then stops. score = 75 is ≥ 75, so the later, looser conditions are never checked.

score = 75 → "good"

It matches >= 75 first. The >= 60 branch is also true, but it is never reached.

Guideline: loosest test last

If the branches were swapped so that >= 60 came first, every passing score would print "passing", making the tighter grades unreachable.

Comparison operators

Comparisons produce a bool

OperatorAsksExample → result
==equal?3 == 3 → True
!=not equal?3 != 4 → True
> >=greater (or equal)?5 >= 5 → True
< <=less (or equal)?2 < 1 → False
and / orcombine conditionsx > 0 and x < 10
Loops

A loop replaces repeated lines of code

A loop repeats a block of code. A for loop goes through a list, running the same block once for each item. Here it keeps a running total (a variable that starts at 0 and grows each time round) and counts the non-zero days.

hours = [3, 0, 5, 2, 8, 0, 4] total = 0 days_worked = 0 for h in hours: total = total + h if h > 0: days_worked = days_worked + 1 print(total, days_worked) 22 5
  • total = 0start both counters at zero, before the loop
  • for h in hours:repeat the indented block 7 times; h is 3, then 0, then 5…
  • total = total + htake the old total, add this day’s hours, store it back
  • if h > 0:only on days with hours, add 1 to days_worked
  • 22 5output: 22 hours in total, spread over 5 days that had any work
Exercise · 3 min

Counting with a condition

The counter starts at 0 before the loop and grows only when the condition holds.

Tasks

  1. Predict what print(long_days) shows.
  2. Select ▶ Run / Edit and run the code.
  3. Change h > 0 to h >= 4. How many days now?

Result on the lecture laptop (select to reveal)

5: the five days with any hours. With h >= 4: 3 (the days with 5, 8 and 4 hours).

hours = [3, 0, 5, 2, 8, 0, 4] long_days = 0 for h in hours: if h > 0: long_days = long_days + 1 print(long_days)
Choosing a denominator

The denominator of an average

Total hours ÷ days worked and total hours ÷ all days are different claims. Choosing the denominator is a judgement, not a formula.

total / days_worked = 22 / 5 = 4.4

"On days worked, the average was 4.4 hours." This describes work intensity.

total / len(hours) = 22 / 7 ≈ 3.1

"Across the whole week, 3.1 hours a day." This is a different, equally valid claim.

Neither is uniquely correct

They answer different questions, so the choice must be stated. (len(hours) counts the items in the list: 7.)

Edge case

The case with no days worked

If every value is 0, then days_worked is 0, and dividing by it crashes. Real data does contain this case, so it must be handled explicitly.

# fails on purpose: read the last line total, days_worked = 0, 0 print(total / days_worked) ZeroDivisionError: division by zero

Reading this error

Last line
ZeroDivisionError: division by zero — a division by 0, which has no answer
Line number
the traceback says line 2: the division inside print
Line 1
total, days_worked = 0, 0 sets both variables at once

Guideline

Consider the empty version of each input before finalising the normal case.

Chains and separate tests

elif stops; separate ifs do not

An if/elif chain runs at most one branch. Three separate ifs are each checked, and all can run.

score = 95 # chain: first match wins, done if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" print(grade) A

Common error

With three separate ifs, a 95 passes every test and ends as "C", the last one that ran.

Exercise · 3 min

A chain against separate tests

A score of 95, tested by an if/elif chain.

Tasks

  1. Predict the grade.
  2. Select ▶ Run / Edit and run the code.
  3. Change both elif to if, so the three tests are separate. Predict, then run.

Result on the lecture laptop (select to reveal)

"A": the first match wins and the chain stops. With three separate ifs every test passes, and the last one leaves "C".

score = 95 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" print(grade)
Truthiness

Empty things are False

== 0 and len(x) == 0 are unnecessary. Python already treats empty and zero as False in a condition. Values that count as False are called falsy; everything else is truthy.

names = [] if names: print("we have names") else: print("list is empty") # this runs list is empty

Falsy values

0, "" (empty string), [] (empty list), {} (empty dictionary, Week 3), None — all False. Everything else is True. So if names: reads “if names has anything in it”.

Counting loops

range for loops that need the position

Looping over items is common; sometimes the position is also needed. An item’s index is its position number, counted from 0. range(n) gives 0, 1, … n-1 — n numbers, starting at 0. range(start, stop, step) can also start elsewhere and jump by step.

for i in range(3): print(i) # stops BEFORE 3 — off-by-one lives here 0 1 2

Common error

range(3) gives three numbers, but the last is 2. Count the starts, not the end.

Position and item together

enumerate gives the index and the item

enumerate is a built-in function wrapped around a list in a for loop. Each time round it gives two things: a counting number (the index) and the item itself. Two names before in receive both.

A class register read aloud, “number 1, Ana; number 2, Ben”, gives the number and the name together.

scores = [88, 92, 75] for i, score in enumerate(scores): print(i, score) for n, score in enumerate(scores, start=1): print("Student", n, "scored", score) 0 88 1 92 2 75 Student 1 scored 88 Student 2 scored 92 Student 3 scored 75
  • for i, score in enumerate(scores):each time round, i gets the position and score gets the value
  • 0 88, 1 92, 2 75the output: positions start at 0, like every index in Python
  • start=1start counting at 1 instead, for lists meant for people: Student 1 scored 88 … Student 3 scored 75
While loops

while: repetition until a condition changes

for is used when the number of repetitions is known; while when only the stopping condition is known.

balance = 100 while balance > 0: balance = balance - 30 print(balance) -20
  • while balance > 0:check the condition; while it is True, run the block again
  • balance = balance - 30100 → 70 → 40 → 10 → −20; now −20 > 0 is False, so it stops
  • print(balance)prints -20: the loop only checks at the top, so it can overshoot

Common error

If the condition never becomes False, the loop runs forever. The block must change something that the condition tests.

Building a list

Building a new list inside a loop

A common pattern: start empty, go through the input, and append the wanted items. Here, only the passing scores.

passing.append(s) is a method call: a function that belongs to a value, written after a dot. .append(s) adds s to the end of the list passing. After the loop, passing is [82, 91].

scores = [55, 82, 60, 91] passing = [] for s in scores: if s >= 75: passing.append(s) print(passing) [82, 91]

Note

empty list → loop → conditional append. This pattern recurs throughout the course.

Review question

Question (select to reveal the answer)

With the grade ladder from earlier, which score prints "needs work"?

A · 60
B · 59
C · 75
D · 90

B — 59.

60 matches >= 60 → "passing". Only a score below every threshold falls through to the else. Off-by-one bugs occur at boundaries.

Break

  Five minutes

Next: functions, the idea that connects the whole course.

Part C

Functions

A name for a piece of work done more than once.

Part B covered choice and repetition. Functions such as print(), len() and int() have been used throughout. This part shows how to write new ones.

Functions

A function is a name for a piece of work

A function is a named, reusable piece of work: it takes inputs and gives back a result. Define it once with def; call it (run it, by writing its name and brackets) any number of times. A docstring is the sentence in triple quotes right under def; it tells the reader what the function does.

A recipe card. def writes the card; a call cooks the dish with the given ingredients; return hands back the finished dish.

def average(numbers): """Mean of a list, or 0 if empty.""" if len(numbers) == 0: return 0 return sum(numbers) / len(numbers) print(average([3, 5, 4])) print(average([])) 4.0 0
  • def average(numbers):define a function called average with one input, named numbers
  • if len(numbers) == 0:if the list is empty… return 0 hands back 0 and stops right there
  • return sum(numbers) / len(numbers)add the values, divide by how many there are, hand the answer back
  • average([3, 5, 4]) → 4.0a call; 12 / 3 = 4.0, a float because / always gives a decimal
  • average([]) → 0the empty case is caught by the if and gives back 0
Definition

Definition: function

Function, in mathematics (Stewart)

A function f is a rule that assigns to each element x in a set D exactly one element, called f(x), in a set E.

A Python function with return

behaves the same way: the same arguments give back the same value, which can be stored and reused.

CallGives backA function in the maths sense?
average([3, 5, 4]) with return4.0, every timeyes
average([3, 5, 4]) with print insteadNone (it only displays 4.0)no: nothing comes back

Source: Stewart (2015), Calculus, 8th ed., §1.1.

Common error

return hands a value back; print only displays it

Guards

Handle the empty case instead of crashing

Remove the if len(numbers) == 0 check and average([]) divides by zero. A guard is an early check that catches a bad or empty input before it can cause trouble. The guard turns a crash into a sensible answer.

Without the guard

average([]) → ZeroDivisionError. The whole program stops.

With the guard

average([]) → 0. The caller keeps running.

The judgement

0 is sometimes a reasonable answer for "no data"; in other cases an error is preferable (see the next slides).

Terminology

Parameter vs argument

The parameter is the name in the definition. The argument is the real value passed in when it is called.

def greet(name): # name = parameter return "Hi, " + name print(greet("Ana")) # "Ana" = argument Hi, Ana

Why it matters

The same function does different work depending on the argument, which is the purpose of naming it.

The parameter is the blank on a form (“Name: ____”); the argument is what is written in the blank this time (“Ana”).

Optional extension

Explicit errors are preferable to silent wrong answers

Given nonsense input, a function that returns a meaningless number hides the bug. One that raises an error stops execution before the wrong number spreads. To raise an error is to stop deliberately with a custom message; the error itself is called an exception (more in Week 4).

# fails on purpose: read the last line def average(nums): if not isinstance(nums, list): raise TypeError("expected a list") return sum(nums) / len(nums) average("hello") TypeError: expected a list
  • isinstance(nums, list)asks “is nums a list?” → True/False; not flips it
  • raise TypeError("expected a list")stop here with our own error type and message
  • ...a placeholder: “the rest of the function goes here”
  • Run it: tracebacktwo File lines: line 6 is the call, line 3, in average is where it stopped. Last line = our message

Principle

Fail early and clearly. A wrong number that looks plausible is the most costly kind of bug.

Common error

A counter that always returns 1

It is meant to count passing scores. But passing = 0 sits inside the loop, so it resets every pass. Only the last item's count survives.

def count_passing(scores): for s in scores: passing = 0 # resets each time! if s >= 60: passing = passing + 1 return passing print(count_passing([80, 40, 90])) # want 2 1

The fix

Move passing = 0 above the loop, so it accumulates across items.

Positional arguments

Arguments fill parameters left to right

The position decides which value lands in which parameter. If they are swapped, the code still runs but gives the wrong answer.

def divide(top, bottom): return top / bottom print(divide(10, 2)) print(divide(2, 10)) # silently wrong: the order matters 5.0 0.2

Prevention

Name them at the call — divide(top=10, bottom=2) — when the order is not obvious. These are keyword arguments: name=value, so position no longer matters.

Default values

Parameters with default values

When a parameter has a default (a value written with = in the definition), callers may omit it. This reduces required arguments while keeping flexibility.

def greet(name, greeting="Hi"): return greeting + ", " + name print(greet("Ana")) print(greet("Ana", "Hello")) Hi, Ana Hello, Ana

Rule

Defaults come after the required parameters; Python requires this.

Exercise · 3 min

A default value, and overriding it

greeting has a default, so it can be left out of the call.

Tasks

  1. Predict both lines.
  2. Select ▶ Run / Edit and run the code.
  3. Add a third call, greet("Cara", greeting="Hey"), inside a print.

Result on the lecture laptop (select to reveal)

Hi, Ana and Good morning, Ben; the third prints Hey, Cara.

def greet(name, greeting="Hi"): return greeting + ", " + name print(greet("Ana")) print(greet("Ben", "Good morning"))
Function structure

Handling the invalid case first

A guard clause deals with the empty or wrong input up top and returns. The rest of the function can then assume valid input. if not nums: reads “if nums is empty” (an empty list is falsy).

def average(nums): if not nums: return 0 # empty case, handled return sum(nums) / len(nums) print(average([]), average([2, 4])) 0 3.0

Rationale

Handling the exceptional case first keeps the main path free of nesting.

Worked example

The divide-by-zero error inside a function

Review question

Question (select to reveal the answer)

This should count scores ≥ 75. It always returns 1. Explain why.

def count_passing(scores): for s in scores: n = 0 if s >= 75: n = n + 1 return n print(count_passing([80, 90, 75]))

n = 0 is inside the loop.

It resets to 0 on every pass, so only the last score is counted. With n = 0 above the loop, it counts them all.

Defensive functions

Validation before computation

Inputs are checked before use. A clear early error is preferable to a confusing crash five lines later, or to a wrong answer with no error.

def percent(part, whole): if whole == 0: return None # nothing to be a % of return 100 * part / whole print(percent(3, 4), percent(3, 0)) 75.0 None

Synthesis of Week 2

Types, control flow and functions combine here: check the type, branch on the edge case, and wrap it in a reliable function.

Review question

Question (select to reveal the answer)

A function's body is only print(sum(nums)) — no return. After x = f([1,2,3]), what is x?

A · 6
B · None
C · [1, 2, 3]
D · an error

B — None.

It printed 6 to the screen, but a function with no return hands back None. Therefore x holds nothing usable.

This week's lab

Types, choices, and a bug to fix

The lab covers fixing the "21" + 1 error, convert text to a number, reorder the grade ladder, count with a loop, use range and enumerate, give a function a default, and guard a divide-by-zero. ~45 minutes.

How it works: replace each ____, press ▶ Run to see the output, then Check. Each part starts with a short explanation of the terms it uses.

Guideline: read the last line

Every failing cell is practice in the central skill of reading the error.

Optional extension

Make average() raise an error on bad input, and explain why that is better than a wrong number.

Summary

Three ideas and three common bugs

Glossary

Week 2 terms

All new terms from this week, one line each. Week 3 builds on all of them.

Preparation for next week

Practice & reading

Next Week

Data structures & files

Lists, dictionaries and reading real files: the collections that hold the data analysed in the rest of the course.

DS 208 · Programming for Data Science