0% found this document useful (0 votes)
23 views62 pages

L02 - Python (Part 1) - 1

Uploaded by

malcolm.holmen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views62 pages

L02 - Python (Part 1) - 1

Uploaded by

malcolm.holmen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

UNIVERSITY OF BORÅS

Python (part 1)
Data Visualization (C1VI1B) Autumn 2025

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 1 (62) Python (part 1) UNIVERSITY OF BORÅS
Agenda
• Introduction to Python
• Programming as a Way of Thinking
• Variables and Statements
• Functions
• Functions and Interfaces
• Conditionals and Recursion
• Return Values

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 2 (62) Python (part 1) UNIVERSITY OF BORÅS
Introduction to Python

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 3 (62) Python (part 1) UNIVERSITY OF BORÅS
Why Learn Python? https://www.tiobe.com/tiobe-index

• The most popular programming


language:
https://www.python.org
• It’s a dynamically type-checked,
interpreted language with a
garbage collector, and is based on
multiple programming paradigms.
• Widely used in web development,
data science, AI/ML, automation,
scripting, and education.

• Managed by the Python Software


Foundation (PSF):
https://www.python.org/psf-landing

https://en.wikipedia.org/wiki/Python_(programming_language)

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 4 (62) Python (part 1) UNIVERSITY OF BORÅS
The Origins of Python
• 1980s: Guido van Rossum worked on the ABC language
(a teaching language) at the Centrum Wiskunde & Informatica (CWI) in the
Netherlands.
• December 1989: Van Rossum started developing Python based on ABC.

• February 1991: Python 0.9.0 (first version) released, and included classes,
inheritance, exception handling, functions, lists, dicts, and strings.

• 1994: Python 1.0 was released, and gained traction for its readability,
simplicity, and growing community.

• 2000: Python 2.0 introduced list comprehensions and garbage collection. It


also introduced incompatibilities and legacy issues. Over time, more
features were added, making the language powerful but also increasingly
inconsistent.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 5 (62) Python (part 1) UNIVERSITY OF BORÅS
Python Standardization
• 2008: Python 3.0 was released and was not backward compatible. It cleaned
up legacy features, unified str and unicode, improved integer division
behavior (/ vs //), and restructured many standard library functions. Early
adoption was slow due to lack of compatibility with existing Python 2 code.
• January 1 2020: Python 2 End-of-Life (official support for Python 2 ended).
Python 3 became the standard, and most libraries finally migrated.

• 2020s+: Python 3.8–3.13 and beyond introduced type hinting, asyncio,


pattern matching (Python 3.10), and performance improvements such as the
"no-GIL" initiative and CPython optimizations
(https://realpython.com/python313-free-threading-jit).

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 6 (62) Python (part 1) UNIVERSITY OF BORÅS
The Python Standard Library
• Python is a high-level, general purpose programming language, in which
programs are written using multiple programming paradigms, including
structured (particularly procedural), object-oriented, and
functional programming.
• Although a programmer could implement all functionality in a Python
program from scratch, most Python programmers take advantage of the rich
collection of existing functionality in the Python Standard Library.
• There are also plenty of Open Source Python Packages available.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 7 (62) Python (part 1) UNIVERSITY OF BORÅS
The Python Language Reference
• The Python Language Reference is: # main.py main.py

• A formal specification of the Python language. from math import sqrt

def main():
• It describes the syntax, semantics, and core behavior ans = sqrt(4)
print(f"sqrt(4) is {ans}")
of Python. if __name__ == "__main__":
main()
• Maintained by the Python Software Foundation (PSF)
https://docs.python.org/3/reference
• The blueprint for how Python should behave, and
useful for people writing interpreters, compilers, or
tools that understand Python code, and for advanced
users who want to know exactly what Python is doing.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 8 (62) Python (part 1) UNIVERSITY OF BORÅS
Python Interpreters
• A Python Interpreter is: # main.py main.py

from math import sqrt


• A program that reads and executes Python
def main():
code according to the language specification. ans = sqrt(4)
print(f"sqrt(4) is {ans}")

• It can run .py files or execute Python code if __name__ == "__main__":

interactively. main()

> python main.py terminal


sqrt(4) is 2.0
• When you type python or python3 in your
> python terminal
terminal, you’re starting a Python Interpreter. Python 3.13
>>> from math import sqrt
>>> def main():
... ans = sqrt(4)
... print(f"sqrt(4) is {ans}")
...
>>> if __name__ == "__main__":
... main()
...
sqrt(4) is 2.0
>>> quit()
>

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 9 (62) Python (part 1) UNIVERSITY OF BORÅS
Python Interpreters
Interpreter Written in Description
Cython C The default (reference) and most widely used implementation.
This is what’s downloaded from https://www.python.org
PyPy RPython Uses a Just-In-Time (JIT) compiler to speed up execution.
Jython Java Runs on the Java Virtual Machine (JVM) and lets you use Java libraries.
IronPython C# Runs on the Common Language Runtime (CLR) and lets you use .NET
libraries.
MicroPython C A lightweight interpreter for microcontrollers and embedded systems.
Brython JavaScript Aims to run Python code in the browser by transpiling it to JavaScript.
RustPython Rust A maturing Python interpreter written in Rust.
Stackless Python C A variant of CPython focused on concurrency and microthreads.
Python Interpreter

> python main.py terminal > python terminal


sqrt(4) is 2.0 Python 3.13
>>>

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 10 (62) Python (part 1) UNIVERSITY OF BORÅS
Typical Python Development Environment
• A Python development environment
usually consists of:
• an Editor (e.g. VSCode, Vim)
or IDE (e.g. PyCharm, Spyder)
• an Interpreter (e.g. CPython)
• a Package Manager
(e.g. pip, conda, mamba)
• the Python Language with the
the Python Standard Library

It’s also common to use


Jupyter Notebook or JupyterLab.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 11 (62) Python (part 1) UNIVERSITY OF BORÅS
From Source Code to Running Program
1. A Python program or script is written in a
python source code file with file extension .py
(e.g. main.py)
2. The program or script is interpreted by a
Python Interpreter (e.g. python main.py):

First the source code (.py) is compiled into
byte code (.pyc).

Then the Python Virtual Machine (PVM)
parses the program’s (and any used library
modules’) byte code.

If the Python Interpreter supports Just-In-Time
(JIT) Compilation, (some) byte code is
compiled into native machine code.
3. Byte/machine code instructions are executed.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 12 (62) Python (part 1) UNIVERSITY OF BORÅS
A Simple Python Program
Anythig after a imports code (e.g. sqrt function) The keyword def defines a function, in
# is a comment from a Python package (math is part this case a function called main, with
of the Python Standard Library) no parameters, that returns nothing.

A code block # First python program


main.py

is created by
indentation import math
(e.g. 4 spaces)
def main(): Calls the sqrt function that
returns the square root of 4.
ans = math.sqrt(4)
Calls the print function that
print(f"sqrt(4) is {ans}") prints a text to the terminal.

if __name__ == "__main__":
main()
terminal
A Python Program (main.py) is
> python main.py started by calling it via an Interpreter,
Calls the main function
sqrt(4) is 2.0 which defines __name__ as
"__main__" in main.py
Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 13 (62) Python (part 1) UNIVERSITY OF BORÅS
Same Program Written as a Python Script
Notice the abscense of
if __name__ == "__main__":

main.py main.py
# Script with function # Script without function
import math import math

def main():
ans = math.sqrt(4) ans = math.sqrt(4)
print(f"sqrt(4) is {ans}") print(f"sqrt(4) is {ans}")

main()

terminal
> python main.py
sqrt(4) is 2.0

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 14 (62) Python (part 1) UNIVERSITY OF BORÅS
Python Module
Python source code files (.py) that are meant to be imported into other python
source code files (.py) are called a modules (python scripts are not modules)

main.py mymath.py
# main.py # mymath.py
import mymath def add(x,y):
return x + y
def main():
ans = mymath.add(1,2)
print(f"1 + 2 = {ans}")

main()

terminal
> python main.py
1 + 2 = 3
Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 15 (62) Python (part 1) UNIVERSITY OF BORÅS
The Python Interpreter
• We can run a Python program/script using the Python Interpreter.

python main.py

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 16 (62) Python (part 1) UNIVERSITY OF BORÅS
The Interactive Python Interpreter
• We can run a Python program/script using the Interactive Python Interpreter.

python

Python
code

quit()

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 17 (62) Python (part 1) UNIVERSITY OF BORÅS
Programming as a Way of Thinking

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 18 (62) Python (part 1) UNIVERSITY OF BORÅS
Arithmetic Operators
• An arithmetic operator is a symbol that Statement run in There are two types of numbers in Python:
represents an arithmetic computation. the interactive
python interpreter 
Integers, which represent numbers with
• The plus sign, +, is the >>> 30+12 no fractional (decimal) part
addition operator. 42
>>> type(42)
Output (result) <class 'int'>
• The minus sign, -, is the >>> 43-1
subtraction operator. 42 
Floating-point numbers, which represent
numbers with a decimal point
• The asterisk, *, is the >>> 6*7 >>> type(42.0)
multiplication operator. 42 <class 'float'>

• The forward slash, /, is the >>> 84/2


42.0
division operator.
Notice the result of dividing two integers with the
• Two forward slashes, //, is the >>> 84//2
division operator / is a floating-point number
42
integer division operator.
• The asterisks, **, is the >>> 7**2 Notice the result of dividing two integers using
49 the integer division operator // is an integer
exponentiation operator.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 19 (62) Python (part 1) UNIVERSITY OF BORÅS
Expressions and Operator Precedence
• An expression is any combination of operator function call
values, variables, operators and value value of expression

function calls that can be evaluated to >>> 2*3+a*b+len("hello!")


42
produce another value.

• Operator precedence (see link below)


follows the evaluation order you might >>> 12+5*6
42
multiplication * is
evaluated before addition +
have learned in a math class.

• You can control the evaluation order of >>> (12+5)*6 The sub-expression in
parentheses (12+5)
sub-expressions using parentheses. 102
is evaluated before
the multiplication *

https://docs.python.org/3/reference/expressions.html#operator-precedenc
e
Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 20 (62) Python (part 1) UNIVERSITY OF BORÅS
Functions
• Functions in Python are called with a
calling the function add
comma-separated list of arguments within >>> add(1,2)
3
with the arguments 1 and
parentheses, and can return a value. 2 that returns the value 3

• Some functions are built in to the language, >>> round(42.4) >>> round(42.6)
e.g. the functions round (rounds a number) 42 43

and abs (returns a number’s absolute value). >>> abs(42) >>> abs(-42)
42 42

• Any function that returns a value can be used >>> abs(42)+1


as an expression. 43

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 21 (62) Python (part 1) UNIVERSITY OF BORÅS
Strings
• To write a string, put a sequence of >>> 'Hello' >>> "world"
characters inside single ' or double " 'Hello' "world"
quotation marks.

>>> "Hello" + " " + "world"


• To concatenate two strings, use the string "Hello world"
concatenation operator +.

• Multiplying * a string with a number, makes >>> 'Spam, ' * 4


'Spam, Spam, Spam, Spam, '
copies of the string and concatenates them.

• The len function returns the length of a >>> len('Spam')


string (number or characters). 4

• The type of a string is str >>> type('Spam')


<class 'str'>

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 22 (62) Python (part 1) UNIVERSITY OF BORÅS
Values and Types
• Every value has a type:
>>> type(2)
• 2 is an integer with data type int int

• 42.0 is a floating-point number with data type float >>> type(42.0)


float
• 'Hello' is a string with data type str
>>> type('Hello')
• The built-in function type returns the type of a value. str

• The functions int(), float(), and str() convert a value >>> int(42.9) >>> int('42')
from one type to an int, float, and str respectively. 42 42

>>> float(42) >>> float('42.0')


42.0 42.0

>>> str(42) >>> str(42.0)


'42' '42.0'

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 23 (62) Python (part 1) UNIVERSITY OF BORÅS
Booleans
• In Python, the boolean values are True and False >>> True
True
>>> False
False

• The type of a boolean is bool


>>> type(True)
class <'bool'>

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 24 (62) Python (part 1) UNIVERSITY OF BORÅS
Variables and Statements

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 25 (62) Python (part 1) UNIVERSITY OF BORÅS
Variables The equals sign = is the assignment operator

• A variable is a name that refers to a >>> n = 17 Create an int variable n with value 17
value.
>>> pi = 3.14 Create a float variable pi with value 3.14
• To create a variable, we can write a
assignment statement. >>> msg = 'string' Create a str variable msg with value string

>>> b = True Create a bool variable b with value True

• Variables are dynamically typed, >>> b = 17 >>> type(b)


17 class <'int'>
so a variable can change types
during the execution of a program.

• A variable can be used in an >>> n + 25 >>> round(pi) >>> len(msg)


42 3 6
expression or as an argument when
calling a function.
Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 26 (62) Python (part 1) UNIVERSITY OF BORÅS
Variable Names and Keywords
• Variable names can contain letters, >>> id_2 = 5
numbers, and the underscore character _,
but they can’t begin with a number.

• By convention, only lower case is for >>> your_name = 'john doe'


variable names, and, in names with
multiple words, each name is separated
with an underscore _ (a.k.a. snake case).
keywords

• Keywords can’t be used as variable names.

Python is case sensitive,


so a1 and A1 are
different variables.
Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 27 (62) Python (part 1) UNIVERSITY OF BORÅS
The import statement
• In order to use additional features from a module, e.g. the >>> import math
math module, you have to import them.
• A module is a collection of variables, functions and
classes.
• To use a variable, function or a class in an imported >>> math.pi
module, you have to use the dot operator . between the 3.141592653589793
name of the module and the name of the variable,
function or class.
>>> math.sqrt(25)
5.0
• The math module includes a variable pi with the value
of the mathematical constant π, a sqrt function that
computes square roots, and a pow function that raises >>> math.pow(5,2)
one number to the power of another number. 25.0

• A module’s variables, functions and classes can also be


imported individually from the module, which means >>> from math import pi >>> from math import sqrt
the module’s name and the dot operator can be omitted. >>> pi >>> sqrt(25)
3.141592653589793 5.0

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 28 (62) Python (part 1) UNIVERSITY OF BORÅS
Expressions vs Statements
• Expressions are evaluated to a value. >>> 19 + n + round(math.pi) * 2
42

• Statements are executed and have an effect >>> n = 17


but no value.
>>> import math

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 29 (62) Python (part 1) UNIVERSITY OF BORÅS
The print Function
• The print function outputs text to >>> print(19) >>> print(n) >>> print(round(pi))
standard output, i.e. the terminal. 19 17 3

>>> print(19 + n + round(pi) * 2)


42

>>> print('The value of pi is approximately')


The value of pi is approximately

• print can also output sequences of >>> print('The value of pi is approximately', pi)
expressions separated by commas. The value of pi is approximately 3.141592653589793

• String interpolation is accomplished by >>> print(f'The value of pi is approximately {pi}')


preceding a string with the letter f and The value of pi is approximately 3.141592653589793
inserting expressions in curly braces {}
within the string.
• Raw strings (parsed verbatim) are created >>> print(r'One\nTwo') >>> print('One\nTwo')
by preceding a string with the letter r. Hello\nWorld One
Two

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 30 (62) Python (part 1) UNIVERSITY OF BORÅS
Arguments
• When calling a function, the expression >>> int('101')
within parentheses is an argument. 101

>>> s = input() >>> math.sqrt(25) >>> math.pow(5,2)


• Functions can be defined to take 5.0 25.0
0 to many arguments. >>> print('Any', 'number', 'of', 'arguments')
Any number of arguments

• Some functions can take additional >>> round(math.pi, 2) >>> round(math.pi, 3)


optional arguments. 3.14 3.142

>>> float('123.0', 2)
• Calling a function with too few/many TypeError: float expected at most 1 argument, got 2
arguments or arguments with >>> math.pow(2)
incompatible types is a TypeError. TypeError: pow expected 2 arguments, got 1

>>> math.sqrt('123')
TypeError: must be a real number, not str

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 31 (62) Python (part 1) UNIVERSITY OF BORÅS
Comments comment

• A comment is created with the hash >>> # number of seconds in 42:42


character #, where anything following >>> seconds = 42 * 60 + 42
>>> print(seconds)
# on a line is part of the comment. 2562

• A multi-line comment is created


within a pair of tripple quotes """. >>> v = 8 # velocity in meters per second
print(v)
• A multi-line comment can span 8

multiple lines. multi-line


comment

""" main.py

velocity
in meters
per second
"""
v = 8
print(v)

> python main.py terminal

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 32 (62) Python (part 1) UNIVERSITY OF BORÅS
Functions

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 33 (62) Python (part 1) UNIVERSITY OF BORÅS
Defining New Functions colon

• A function definition has header def name(parameterlist):


body statements
• a function header, consisting of the keyword def, the
function’s name, a comma-separated parameter list within
parentheses (), and a colon : Indented
(4 spaces)
• a function body, consisting of an indented block of
statements, including a return value statement if name parameterlist
the function returns a value (e.g. return 0).
def add(a,b): main.py
• Any legal variable name is also a legal function name. sum = a + b
statements return sum
• An empty parameter list indicates the function takes no
arguments. print(type(add))

return value ans = add(1,2)


• Defining a function creates a function object of type
function. function call
arguments

• We call a function using its name, passing in arguments to print(ans)


the parameters (if any) within parentheses ().
> python main.py terminal

• When calling a function, it executes the statements in the <class 'function'>


3
body, returning the function’s value (if any).

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 34 (62) Python (part 1) UNIVERSITY OF BORÅS
Parameters and Return Values
• A function can have zero to many parameters. def print_lyrics(): main.py

print("I'm a lumberjack, and I'm okay.")


• When the function is called, the values of print("I sleep all night and I work all day.")
arguments passed to the function are assigned
to the function’s parameters. print_lyrics()

> python main.py terminal


• Values, variables, and expressions can be I'm a lumberjack, and I'm okay.
passed as arguments to a function. I sleep all night and I work all day.

• A function that doesn’t return a value, def print_twice(string): main.py > python main.py terminal

implicitly returns the value None, print(string) Dennis Moore,


which is of type NoneType. print(string) Dennis Moore,

main.py
print_twice('Dennis Moore, ')
def f(a,b):
res = a + b
def add(a,b): main.py > python main.py terminal

ans = f(1,2) sum = a + b 3


print(ans) return sum
print(type(ans))
x = 1
> python main.py terminal
y = 2
None ans = add(x,y)
<class 'NoneType'> print(ans)

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 35 (62) Python (part 1) UNIVERSITY OF BORÅS
Calling Functions
def repeat(word, n): main.py
• We call a function using its name, passing in arguments to print(word * n)
the parameters (if any) within parentheses ().
def first_two_lines():
• A function can call another function. repeat(spam, 4)
repeat(spam, 4)

def last_three_lines():
repeat(spam, 2)
print('(Lovely Spam, Wonderful Spam!)')
repeat(spam, 2)

def print_verse():
first_two_lines()
last_three_lines()

spam = 'Spam, '


print_verse()

> python main.py terminal

Spam, Spam, Spam, Spam,


Spam, Spam, Spam, Spam,
Spam, Spam,
(Lovely Spam, Wonderful Spam!)
Spam, Spam,

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 36 (62) Python (part 1) UNIVERSITY OF BORÅS
Repetition with the for loop
• A for statement (loop) iterates (loops) head for variable in iterable:
over a block of statements a number of body statements
times. Indented colon

• A for loop has: for i in range(2): main.py for i in range(0,2): main.py for i in range(0,2,1): main.py
print(i) print(i) print(i)
• a head, consisting of the keyword for,
followed by variable(s), the keyword in, > python main.py terminal > python main.py terminal > python main.py terminal
0 0 0
an iterable object, and a colon : 1 1 1

• a body, consisting of indented def repeat(word, n): main.py


statements. print(word * n)

• The simplest for loop has one loop def first_two_lines():


variable and uses the built-in range repeat(spam, 4)
repeat(spam, 4)
function to return an iterable sequence of > python main.py terminal
numbers between start (inclusive, def last_three_lines(): Verse 0
repeat(spam, 2) Spam, Spam, Spam, Spam,
default 0) and stop (exclusive) using a print('(Lovely Spam, Wonderful Spam!)') Spam, Spam, Spam, Spam,
step size (default 1). repeat(spam, 2) Spam, Spam,
(Lovely Spam, Wonderful Spam!)
def print_verse(): Spam, Spam,
range(stop) first_two_lines()
range(start, stop) last_three_lines() Verse 1
range(start, stop, step) Spam, Spam, Spam, Spam,
for i in range(2): Spam, Spam, Spam, Spam,
print("Verse", i) Spam, Spam,
print_verse() (Lovely Spam, Wonderful Spam!)
print() Spam, Spam,

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 37 (62) Python (part 1) UNIVERSITY OF BORÅS
Variables and Parameters Are Local
• When you create a variable inside a function’s def print_twice(string): main.py
body, it’s a local variable, which means that it print(string)
print(string)
only exists (visible) inside the function.
def cat_twice(part1, part2):
• Parameters are also local, i.e. only exist (visible) cat = part1 + part2
inside the function. print_twice(cat)

line1 = 'Always look on the '


• Parameters and local variables are created line2 = 'bright side of life.'
when a function is called, and destroyed when cat_twice(line1, line2)
print(cat) # cat not defined here
the function returns.
> python main.py terminal
• Global variables are created outside of any Always look on the bright side of life.
function (or class), exist throughout the Always look on the bright side of life.
NameError: name 'cat' is not defined
program’s lifetime, and are accessible (visible)
from anywhere inside the module (.py file). c = 3 # global main.py c = 3 # global main.py

def add(a,b): def add(a,b):


• If you want to modify a global variable inside a return a + b + c global c
function’s body, you need to use the keyword c = 7 # modify global
global, to declare that it’s a global variable print(1,2) return a + b + c

and not a local variable. print(1,2)


> python main.py terminal > python main.py terminal
6 10

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 38 (62) Python (part 1) UNIVERSITY OF BORÅS
Tracebacks
• When a runtime error occurs in a function, Python displays the name of the function that was running,
the name of the function that called it, and so on, up the function call stack.
1 def print_twice(string): main.py
2 print(cat) # cat is not defined here
3 print(string)
4
5 def cat_twice(part1, part2):
6 cat = part1 + part2
7
print_twice(cat)
8
line1 = 'Always look on the '
9
line2 = 'bright side of life.'
10
cat_twice(line1, line2) error here
11

> python main.py terminal

Traceback (most recent call last):


File "/home/patrick/projects/py/main.py", line 11, in <module>
cat_twice(line1, line2)
File "/home/patrick/projects/py/main.py", line 7, in cat_twice
print_twice(cat)
File "/home/patrick/projects/py/main.py", line 2, in print_twice
print(cat)
^^^
NameError: name 'cat' is not defined
Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 39 (62) Python (part 1) UNIVERSITY OF BORÅS
Functions and Interfaces

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 40 (62) Python (part 1) UNIVERSITY OF BORÅS
The jupyturtle module
• The jupyturtle module allows you to create simple from jupyturtle import make_turtle code cell
drawings by giving instructions to an imaginary turtle. from jupyturtle import forward, left, right

• To use the jupyturtle module: make_turtle() code cell make_turtle() code cell

forward(100) forward(50)
• pip install jupyturtle left(90)
forward(50)
• create a Jupyter Notebook (.ipynb)
• make_turtle() creates a Turtle instance on a
Canvas surface.

• forward(n) moves the turtle forward n pixels.

• left(a) and right(a) rotates the turtle a degrees.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 41 (62) Python (part 1) UNIVERSITY OF BORÅS
Making a Square
• Combining four sets of function calls draws a square. make_turtle() code cell

forward(50)
left(90)

forward(50)
left(90)

forward(50)
left(90)

forward(50)
left(90)

• We can also use a for loop. make_turtle() code cell

for i in range(4):
forward(50)
left(90)

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 42 (62) Python (part 1) UNIVERSITY OF BORÅS
Encapsulation and Generalization
• We can also place the square-drawing code in a def square(): code cell
function called square for i in range(4):
forward(50)
• Wrapping a piece of code up in a function is left(90)
called encapsulation, and also means we can make_turtle()
reuse the square-drawing code any time we like square()
by calling the function.

• We can add the length of the sides as a def square(length): code cell
parameter, so that we can draw squares with for i in range(4):
different sizes. forward(length)
left(90)
• Adding a parameter to a function is called
make_turtle()
generalization because it makes the function square(30)
more general. square(60)

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 43 (62) Python (part 1) UNIVERSITY OF BORÅS
Encapsulation and Generalization
• If we add another parameter, for the def polygon(n, length): code cell
number of sizes, we can make it even more angle = 360 / n
general. for i in range(n):
forward(length)
left(angle)
• We can now draw polygons, so the function
is renamed to polygon. make_turtle()
polygon(7, 30)

• When calling a function with multiple make_turtle() code cell

arguments, it is easy to forget what they polygon(n=7, length=30)


are, or what order they should be in, so we
can include the names of the parameters in
the argument list.

• These are called keyword arguments (as


opposed to the normal positional
arguments), where the arguments are
assigned to the parameters using the
assignment operator =.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 44 (62) Python (part 1) UNIVERSITY OF BORÅS
Refactoring, Interface and Implementation
• We can reorganize our code with an def polyline(n, length, angle): code cell
additional function polyline. for i in range(n):
forward(length)
• Changes like this, which improve the left(angle)
code without changing its behavior, def polygon(n, length):
are called refactoring. angle = 360.0 / n
polyline(n, length, angle)
• The design of a function has 2 parts:
make_turtle() code cell

• The interface is how the function is polygon(n=7, length=30)


used, including its name, the
parameters it takes and what the
function is supposed to do (its
header).

• The implementation is how the


function does what it’s supposed
to do (includes the function body).

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 45 (62) Python (part 1) UNIVERSITY OF BORÅS
Docstrings
• A docstring is a string at the beginning of a function that explains the interface (“doc” is short for “documentation”).

• By convention, docstrings are triple-quoted strings, and should:

• Explain concisely what the function does, without getting into the details of how it works.

• Explain what effect each parameter has on the behavior of the function.

• Indicate what type each parameter should be, if it is not obvious.

def polyline(n, length, angle):


"""Draws line segments with the given length and angle between them.

n: integer number of line segments


length: length of the line segments
angle: angle between segments (in degrees)
"""
for i in range(n):
forward(length)
left(angle)

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 46 (62) Python (part 1) UNIVERSITY OF BORÅS
Conditionals and Recursion

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 47 (62) Python (part 1) UNIVERSITY OF BORÅS
Integer Division and Modulus
• Dividing two integers with the division operator / yields a floating-point number
>>> minutes = 105
>>> hours = minutes / 60
>>> hours
1.75

• Dividing two integers with the integer division operator // yields an integer >>> minutes = 105
>>> hours = minutes // 60
>>> hours
1

• Dividing two integers with the modulus operator % yields a the remainder >>> minutes = 105
(integer) >>> remainder = minutes % 60
>>> remainder
45

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 48 (62) Python (part 1) UNIVERSITY OF BORÅS
Boolean Expressions
• A boolean expression is an expression that is either True or False. >>> print(type(True))
<class 'bool'>
• The two values True and False are of type bool.
>>> print(type(False))
<class 'bool'>

• The relational operators (which yield boolean results) are: >>> 5 == 5 >>> 7 == 5
True False

Operator Description Example >>> 7 != 5 >>> 7 != 7


True False
== Equals 5 == 5
>>> 7 > 5 >>> 5 > 7
!= Not equals 7 != 5 True False
> Greater than 7 > 5 >>> 5 < 7 >>> 7 < 5
True False
< Less than 5 < 7
>>> 6 >= 6 >>> 6 >= 7
>= Greater than or equal to 6 >= 6 True False
<= Less than or equal to 6 <= 6 >>> 6 <= 6 >>> 6 <= 5
True False

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 49 (62) Python (part 1) UNIVERSITY OF BORÅS
Logical Operators
• To combine boolean values into expressions, we can use logical operators.

• The logical operators (which yield boolean results) are:

Operator Description Example


and True if both operands are True, else False True and True
or True if both or either operand is True, else False True or False
not Negates operand (False if True, True if False) not False

>>> 5 > 0 and 5 < 10 >>> 5 % 2 == 0 or 5 % 3 == 0 >>> not 5 > 10


True False True

• Any non-zero number is interpreted as True, else False.

>>> 42 and True


True

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 50 (62) Python (part 1) UNIVERSITY OF BORÅS
The if Statement
• An if statement executes a block of statements if a colon
condition is True.
head if condition:
• An if statement has: body statements
• a head, consisting of the keyword if, followed a boolean
condition, and a colon : Indented

• a body, consisting of indented statements to execute if the


x = 42 main.py
condition is True.
• There is no limit to the number of statements that can if x > 0:
print('x is positive')
appear in the block, but there has to be at least one.
> python main.py terminal
x is positive

• Sometimes it’s useful to have a block that does nothing. x = 42 main.py


In that case, use the keyword pass, which does nothing.
if x < 0:
pass # TODO: handle negative values

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 51 (62) Python (part 1) UNIVERSITY OF BORÅS
The if Statement’s elif and else Clauses
• An if statement has: if condition: Execute if condition is True
statements
• a head, consisting of the keyword if, followed a boolean elif condition2:
condition, and a colon : Execute if condition is False
statements
and condition2 is True
elif conditionN:
• a body, consisting of indented statements to execute if the
statements
condition is True. else:
Execute if condition is False
and condition2 is False
• An if statement can have 0 or more elif branches, with: statements
and conditionN is True
• a head, consisting of the keyword elif, followed a
boolean condition2, and a colon : Execute if condition is False
and condition2 is False
• a body, consisting of indented statements to execute if the and conditionN is False
condition2 is True, given any previous conditions are
False. main.py
x = -42
• An if statement can have 0 or one else branch, with:
if x % 2 == 0:
• a head, consisting of the keyword else, followed by a print('x is even')
colon : elif x == 0:
print('x is zero')
• a body, consisting of indented statements to execute if the else:
print('x is odd')
any previous conditions are False.
> python main.py terminal
x is odd

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 52 (62) Python (part 1) UNIVERSITY OF BORÅS
Nested if Statement
• An if statement can contain another (nested) if statement. x = 5 main.py

if 0 < x:
if 0 < x: if x < 10:
if x < 10: print('x is a positive single-digit number.')

> python main.py terminal


x is a positive single-digit number.

• We can combine the two boolean expressions with a logical and. x = 5 main.py

if 0 < x and x < 10:


if 0 < x and x < 10: print('x is a positive single-digit number.')

> python main.py terminal


x is a positive single-digit number.

• For this kind of condition, Python provides a more concise option. x = 5 main.py

if 0 < x < 10:


if 0 < x < 10: print('x is a positive single-digit number.')

> python main.py terminal


x is a positive single-digit number.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 53 (62) Python (part 1) UNIVERSITY OF BORÅS
Recursion
• A recursive function is a function that calls itself (inside its body). def countdown(n): main.py

if n <= 0: # base case


• A recursive function has a: print('Blastoff!')
else: # recursive case
• base case, which stops the recursion, and must eventually be print(n)
called (otherwise you will get an out of stack error). countdown(n-1)

• recursive case, which contains the recursive call. countdown(3)

terminal
> python main.py
countdown(n=3) print(3) return (n=3)
3
2
countdown(n=2) print(2) return (n=2) 1
Blastoff!

countdown(n=1) print(1) return (n=1)

countdown(n=0) print('Blastoff!') return (n=0)

base case

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 54 (62) Python (part 1) UNIVERSITY OF BORÅS
Keyboard Input
• Python provides a built-in function input that stops the program and waits for the user to type something.

• When the user presses Return (or Enter), the program resumes and input returns what the user typed as a string.

• input also accepts a string as an argument, which is used as the prompt in the terminal.

main.py
prompt = 'What is the airspeed velocity of an unladen swallow?\n'
text = input(prompt)

speed = int(text)
print('The speed is', speed)

terminal
> python main.py
What is the airspeed velocity of an unladen swallow?
10
The speed is 10

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 55 (62) Python (part 1) UNIVERSITY OF BORÅS
Return Values

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 56 (62) Python (part 1) UNIVERSITY OF BORÅS
Some Functions have Return Values
• The sqrt function from the math module returns a value. import math main.py

value = sqrt(4) def circle_area(radius):


area = math.pi * radius**2
• A value is returned from a function via the return statement. return area

def circle_area(radius): radius = math.sqrt(42 / math.pi)


area = math.pi * radius**2 print(f'radius is {radius}')
return area
value = circle_area(radius)
• In this case the value of the local variable area is returned. print(f'circle area is {value}')

value = circle_area(radius) print(area)

• The local variable area is not defined outside of the function.


terminal
> python main.py
radius is 3.656366395715726
circle area is 42.00000000000001
NameError: name 'area' is not defined

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 57 (62) Python (part 1) UNIVERSITY OF BORÅS
Some Functions Return None
• A function that doesn’t explicitly return a value returns None def repeat(word, n): main.py

print(word * n)
def repeat(word, n):
print(word * n) repeat('Finland, ', 3)
# implicitly returns None here
result = repeat('Finland, ', 3)
• None is a special value of type NoneType. print(result)

result = repeat('Finland, ', 3) print(type(result))

terminal
> python main.py
Result has the value None of type NoneType Finland, Finland, Finland,
Finland, Finland, Finland,
None
<class 'NoneType'>

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 58 (62) Python (part 1) UNIVERSITY OF BORÅS
Return Values and Conditionals
• When using return in conditional statements, make sure that def absolute_value(x): main.py
every possible path through the function body hits a return if x < 0:
statement. return -x
else:
return x

print( absolute_value(42) )
print( absolute_value(-42) )
print( absolute_value(0) )

> python main.py terminal

42
42
0
• If a path doesn’t return a value (explicitly), None is returned.
def absolute_value_wrong(x):
main.py
if x < 0:
return -x
if x > 0:
return x

print( absolute_value_wrong(0) )

> python main.py terminal

None

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 59 (62) Python (part 1) UNIVERSITY OF BORÅS
Boolean Functions
• Functions that return a boolean value (True or False) can def is_divisible(x, y): main.py
be used as conditions in conditional statements. if x % y == 0:
return True
else:
return False

if is_divisible(6, 2):
print('divisible')

> python main.py terminal

divisible

def is_divisible(x, y): main.py

return x % y == 0

if is_divisible(6, 2):
print('divisible')

> python main.py terminal

divisible

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 60 (62) Python (part 1) UNIVERSITY OF BORÅS
Recursion with Return Values
• The mathematical factorial function is defined for def factorial(n): main.py
positive integers as: if n == 0:
return 1
else:
0! = 1 return n * factorial(n-1)
n! = n(n-1)!
ans = factorial(3)
• A recursive factorial function in python is: print(ans)

> python main.py terminal


def factorial(n):
6
if n == 0: # base case
return 1 def factorial(n): main.py
else: # recursive case if n == 0:
return n * factorial(n-1) return 1
else:
return n * factorial(n-1)
• But calling the function with a floating-point number
or a negative number, results in an infinite recursion ans = factorial(1.5)
print(ans)
(base case never reached), since we haven’t handled ans = factorial(-1)
the constraints (positive integers) in the function. print(ans)
> python main.py terminal
RecursionError: maximum recursion depth exceeded
RecursionError: maximum recursion depth exceeded

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 61 (62) Python (part 1) UNIVERSITY OF BORÅS
Checking Types (Input Validation)
• The built in function isinstance can >>> isinstance(3, int) terminal
be used to check if an expression is of a True
specific type. >>> isinstance(1.5, int)
False
• We can use the isinstance function in
the factorial function to handle the def factorial(n): main.py
integers constraint in positive integers. if not isinstance(n, int):
print('factorial is only defined for integers.')
if not isinstance(n, int): return None
elif n < 0:
print('factorial is not defined for negative numbers.')
• We can use a simple boolean condition to
return None
handle the positive constraint in positive elif n == 0:
integers. return 1
else:
elif n < 0: return n * factorial(n-1)

factorial('crunchy frog')
• This input validation is important in factorial(-2)
functions to ensure all constraints are
satisfied. > python main.py terminal

factorial is only defined for integers.


factorial is not defined for negative numbers.

Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 62 (62) Python (part 1) UNIVERSITY OF BORÅS

You might also like