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
The kind of each value, and why 5 ≠ "5".
Making code choose and repeat: if, elif, else, loops.
Naming a piece of work once for reuse. return vs print.
Every later lab (pandas, plotting, files) applies these three ideas in more complex settings.
Most beginner bugs are one of three mistakes. This week covers how to recognise all three.
Week 1 covered setting up Python and running existing code. This week covers writing the decisions, and the errors that come with them.
An error message is information: Python's statement of exactly what it could not do.
When a cell fails, read the last line first. It names the problem.
Guido van Rossum begins Python at CWI, a research institute in the Netherlands.
Version 0.9.1 is posted publicly in February 1991.
A cleaned-up version that is not compatible with Python 2. This course uses it.
Support for Python 2 ends on 1 January 2020.
The name comes from the BBC comedy Monty Python’s Flying Circus, not from the snake.
Because Python 3 changed some rules, code written for Python 2 can fail today. A tutorial that writes print "hi" without brackets is Python 2.
free packages on PyPI, the catalogue that pip installs from.
The second most used language on GitHub in 2025, after TypeScript.
The leading language for AI projects on GitHub in 2025.
NumPy, pandas and matplotlib, covered in weeks 5–8, are three of those packages.
import itSourcePackages: pypi.org, retrieved 11 Oct 2026; GitHub ranking: GitHub Octoverse 2025
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.
The kind of value something is. It determines which operations are allowed.
e.g. type(5) reports int; type("5") reports str
A whole number, with no decimal point. Used for counts and positions.
e.g. 21, 0, -3
A number with a decimal point. Used for measurements and averages.
e.g. 21.0, 3.5
Text, written inside quotes. Digits in quotes are still text.
e.g. "Cebu", "21"
One of exactly two values, True or False: the answer to a yes/no question.
e.g. 5 > 3 gives True
A symbol that does something to values: add, divide, compare…
e.g. +, /, ==, >=
A yes/no question in code. Its answer is a boolean, and it decides whether a block runs.
e.g. score >= 60
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
Analogy: a function is a recipe, written once, named, and reused as needed. These terms name its parts.
A named, reusable piece of work: it takes inputs and gives back a result.
e.g. len([3, 5, 4]) gives back 3
Running a function: its name followed by round brackets, with the inputs inside.
e.g. average([3, 5, 4])
The name, in the function’s definition, that will hold an input.
e.g. numbers in def average(numbers):
The actual value placed in the brackets when the function is called.
e.g. [3, 5, 4] in average([3, 5, 4])
Hand a result back to whoever called the function, and stop the function there.
e.g. return total / count
Python’s value for “nothing here”. A function with no return gives back None.
e.g. x = print("hi") leaves x as None
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.
5 and "5" as different thingsOne 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.
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 oneprint(type(v).__name__)ask for v’s type and print its short nameint whole number · str text · float decimal · bool True/False · list · NoneType the type of NoneA data type is a set of values and a set of operations defined on those values.
| Type | Some of its values | One of its operations, here |
|---|---|---|
int | …, −1, 0, 1, 2, … | 10 + 5 adds: 15 |
str | "", "5", "Ana", … | "10" + "5" glues: "105" |
bool | True, False | not 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.
| Type | Example | Purpose |
|---|---|---|
int | 5 | Whole numbers — counts, indices |
float | 5.0 | Numbers with decimals — measurements, averages |
str | "5" | Text — names, labels, anything typed |
bool | True | Yes/no — the result of a comparison |
list | [5] | An ordered collection of values |
NoneType | None | "Nothing here" — a deliberate blank |
Two numbers can be added, and a word can be put in capitals, but “capitalise 5” or “add 1 to Cebu” make no sense. Python checks the type before it allows an operation. When code misbehaves, the first check is the type of each value.
type(x) reports the type. It is more reliable than guessing.
age holds the text "21", not the number
21. Python cannot add a number to text, and states this on the last line.
TypeError = an operator got a type it cannot work with+ on text means glue together, and it was handed a numberline 2 — the print line with age + 1+Which is right depends on where the text came from. Data read from a file
often arrives as str and is converted at the point of use.
int(), float(), str() change a value from one
type to another. int("21") reads the text and gives back the number
21; the # 22 comment shows what the line prints.
Python provides both. / always makes a float; //
discards the remainder. The choice depends on the question being asked.
7 / 2 → 3.5ordinary division; the answer is a float (it has a decimal point) — always, even for 4 / 27 // 2 → 3floor division: how many whole 2s fit in 7; the leftover is thrown away7 % 2 → 1remainder (“modulo”): what is left over. x % 2 == 0 is the test for an even number"Average score" wants /. "How many full teams of 4?" wants //.
The same numbers give different answers.
Data read from a file or a form arrives as text, even when it is all digits. Python treats the quotes literally.
"10" + "5"two strings: + glues them into '105'. The quotes around the answer indicate that it is still textint("10") + 5convert the text to the integer 10 first, then add: 15If a "sum" comes out as two numbers joined together, one of them is a string.
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.
Summing a list of comparisons counts how many rows pass a test, a technique used throughout the term.
Three lines, one operator: *.
"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.
What does type(3 / 1) report?
intfloatstrB — float, it is 3.0.
The single / always
produces a float, even when the numbers divide evenly. The integer
3 requires //.
The operator, not the input values, determines the type of the result.
When a value's type is uncertain, print its type(x). This
is the fastest check.
What does "3" + "4" produce?
7"34""7"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.
The operator's meaning depends on the types it sits between.
Predicting what an expression does starts with identifying the types involved.
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).
if runs a block only when something is trueA 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.
if score >= 90:73 ≥ 90? False → skip its blockelif score >= 75:73 ≥ 75? False → skipelif score >= 60:73 ≥ 60? True → run grade = "passing", then jump past the restelse:runs only when every condition above was Falseprint(grade)not indented, so it always runs: prints passingPython 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.
If the branches were swapped so that >= 60 came first, every
passing score would print "passing", making the tighter grades unreachable.
bool| Operator | Asks | Example → result |
|---|---|---|
== | equal? | 3 == 3 → True |
!= | not equal? | 3 != 4 → True |
> >= | greater (or equal)? | 5 >= 5 → True |
< <= | less (or equal)? | 2 < 1 → False |
and / or | combine conditions | x > 0 and x < 10 |
A single = assigns; a double ==
compares. Confusing them is the second most common beginner bug.
ifasks a yes/no question, and the answer is a bool.
and is True only if both sides are; or if at least one is.
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.
total = 0start both counters at zero, before the loopfor 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 backif h > 0:only on days with hours, add 1 to days_worked22 5output: 22 hours in total, spread over 5 days that had any workThe counter starts at 0 before the loop and grows only when the condition holds.
print(long_days) shows.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).
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.
They answer different questions, so the choice must be stated. (len(hours) counts
the items in the list: 7.)
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.
ZeroDivisionError: division by zero — a division by 0, which has no answerline 2: the division inside printtotal, days_worked = 0, 0 sets both variables at onceConsider the empty version of each input before finalising the normal case.
elif stops; separate ifs do notAn if/elif chain runs at most one branch. Three
separate ifs are each checked, and all can run.
With three separate ifs, a 95 passes every test and ends as
"C", the last one that ran.
A score of 95, tested by an if/elif chain.
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".
== 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.
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”.
range for loops that need the positionLooping 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.
range(3) gives three numbers, but the last is 2. Count the
starts, not the end.
enumerate gives the index and the itemenumerate 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.
for i, score in enumerate(scores):each time round, i gets the position and score gets the value0 88, 1 92, 2 75the output: positions start at 0, like every index in Pythonstart=1start counting at 1 instead, for lists meant for people: Student 1 scored 88 … Student 3 scored 75while: repetition until a condition changesfor is used when the number of repetitions is known; while
when only the stopping condition is known.
while balance > 0:check the condition; while it is True, run the block againbalance = balance - 30100 → 70 → 40 → 10 → −20; now −20 > 0 is False, so it stopsprint(balance)prints -20: the loop only checks at the top, so it can overshootIf the condition never becomes False, the loop runs forever. The block must change something that the condition tests.
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].
empty list → loop → conditional append. This pattern recurs throughout the course.
With the grade ladder from earlier, which
score prints "needs work"?
60597590B — 59.
60 matches >= 60
→ "passing". Only a score below every threshold falls through to the
else. Off-by-one bugs occur at boundaries.
Tests should use the exact boundary value, not only a number near it.
>= includes the boundary; > excludes it.
Next: functions, the idea that connects the whole course.
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.
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):define a function called average with one input, named numbersif len(numbers) == 0:if the list is empty… return 0 hands back 0 and stops right therereturn sum(numbers) / len(numbers)add the values, divide by how many there are, hand the answer backaverage([3, 5, 4]) → 4.0a call; 12 / 3 = 4.0, a float because / always gives a decimalaverage([]) → 0the empty case is caught by the if and gives back 0A 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.
returnbehaves the same way: the same arguments give back the same value, which can be stored and reused.
| Call | Gives back | A function in the maths sense? |
|---|---|---|
average([3, 5, 4]) with return | 4.0, every time | yes |
average([3, 5, 4]) with print instead | None (it only displays 4.0) | no: nothing comes back |
Source: Stewart (2015), Calculus, 8th ed., §1.1.
return hands a value back; print only displays itA function that only prints gives back None: the
answer is visible but cannot be used. None is Python’s
value for “nothing here”.
To return is to hand
the result back to the code that called the function. Analogy: returning is a cashier
handing over change; print is reading the amount aloud, with nothing handed
over.
Compute with return. Use print only to look at things.
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.
average([]) → ZeroDivisionError. The whole program stops.
average([]) → 0. The caller keeps running.
0 is sometimes a reasonable answer for "no data"; in other cases an error is
preferable (see the next slides).
The parameter is the name in the definition. The argument is the real value passed in when it is called.
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”).
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).
isinstance(nums, list)asks “is nums a list?” → True/False; not flips itraise TypeError("expected a list")stop here with our own error type and message...a placeholder: “the rest of the function goes here”File lines: line 6 is the call, line 3, in average is where it stopped. Last line = our messageFail early and clearly. A wrong number that looks plausible is the most costly kind of bug.
1It 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.
Move passing = 0 above the loop, so it accumulates across items.
The position decides which value lands in which parameter. If they are swapped, the code still runs but gives the wrong answer.
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.
When a parameter has a default (a value written with
= in the definition), callers may omit it. This reduces required arguments while
keeping flexibility.
Defaults come after the required parameters; Python requires this.
greeting has a default, so it can be left out of the 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.
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).
Handling the exceptional case first keeps the main path free of nesting.
The ZeroDivisionError from the divide-by-zero slide still exists,
but it is now handled in one place for every caller.
The lab guards the same kind of divide-by-zero in percent(part, whole),
which requires deciding what answer suits “nothing to divide by”.
This should count scores ≥ 75. It always
returns 1. Explain why.
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.
Where a counter is initialised is as important as how it is incremented.
Paste it into any ▶ Run window and move the line. The lab’s counting task requires starting a counter in the right place.
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.
Types, control flow and functions combine here: check the type, branch on the edge case, and wrap it in a reliable function.
A function's body is only
print(sum(nums)) — no return. After x = f([1,2,3]),
what is x?
6None[1, 2, 3]B — None.
It printed 6 to the screen, but
a function with no return hands back None. Therefore
x holds nothing usable.
Seeing a value on screen is not the same as capturing it in a variable.
No return → the function returns None.
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.
Every failing cell is practice in the central skill of reading the error.
Make average() raise an error on bad input, and explain why that is better
than a wrong number.
5 ≠ "5". When a result is wrong, check the type first.
Bug: str + int.
First true branch wins; order matters. = assigns, ==
compares. Bug: wrong branch order / divide by zero.
Name work once. return gives back; print only shows.
Bug: no return → None.
Summary: most beginner errors are a type confusion, a
branch that never fires, or a missing return.
Reading the last line of the error and naming which of the three it is.
All new terms from this week, one line each. Week 3 builds on all of them.
213.5"21" is text, not a numberTrue or False; counts as 1 or 0+ / // % == >=+score >= 60:for each item, or while a condition holds0, "", [], Noneaverage([3, 5])numbers[3, 5]bottom=2return givesdef saying what it does.append(x)Finish the Week 2 lab and submit it. If a cell fails, read the last line, fix it and continue; this is the exercise.
Python Tutorial §3–4 (numbers, strings, control flow) and §4.7–4.8 (defining
functions) — docs.python.org/3/tutorial.
Everything here is linked on the course page beside this deck.
Type the examples by hand. Reading code and writing code are different skills.
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