L02 - Python (Part 1) - 1
L02 - Python (Part 1) - 1
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
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.
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.
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
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
interactively. main()
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
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
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.
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'>
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
• 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
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.
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
• 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
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
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
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
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 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
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
>>> 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
""" main.py
velocity
in meters
per second
"""
v = 8
print(v)
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
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
• A function that doesn’t return a value, def print_twice(string): main.py > python main.py terminal
main.py
print_twice('Dennis Moore, ')
def f(a,b):
res = a + b
def add(a,b): main.py > python main.py terminal
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()
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
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)
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
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.
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)
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)
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
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”).
• 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.
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
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.
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
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.')
• We can combine the two boolean expressions with a logical and. x = 5 main.py
• For this kind of condition, Python provides a more concise option. x = 5 main.py
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
terminal
> python main.py
countdown(n=3) print(3) return (n=3)
3
2
countdown(n=2) print(2) return (n=2) 1
Blastoff!
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
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)
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) )
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) )
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')
divisible
return x % y == 0
if is_divisible(6, 2):
print('divisible')
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)
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
Patrick Gabrielsson Data Visualization (C1VI1B) Autumn 2025 62 (62) Python (part 1) UNIVERSITY OF BORÅS