Workshop 3: Define Functions and Classes
-
Intro
-
Quick Introduction to Functional Programming and Flowcharts
-
Example Functions
-
Object-Oriented Programming (OOP)
-
Example Classes (OOP)
-
Helpful Resources
-
Conclusion / Next Workshop
-
Required Readings Before Workshop 4
Information
Primary software used | Python |
Software version | 1.0 |
Course | Workshop 3: Define Functions and Classes |
Primary subject | Prototyping and Manufacturing |
Secondary subject | Robot Programming |
Level | Beginner |
Last updated | August 29, 2025 |
Keywords |
Responsible
Teachers | |
Faculty |
Workshop 3: Define Functions and Classes 0/7
Workshop 3: Define Functions and Classes
Get familiar with how to define your own functions and organize code into classes
Learning Objectives
- Understand the principles of functional programming
- Define custom functions to solve programming problems
- Understand the principles of classes in Python’s Object-Oriented Programming paradigm
This tutorial is published as part of a series of workshops for an interfaculty course from TU Delft Faculty of Architecture and the Built Environment to support learning in and outside the class with open learning material. The intent of the workshop series is to increase familiarity with programming language Python for research and scientific applications as part of the course Creative Robotics in Spatial Design.
You are free to go through the learning material at your own to get familiar with Python fundamentals.
Workshop 3: Define Functions and Classes 1/7
Quick Introduction to Functional Programming and Flowchartslink copied
Functions in Python are blocks of reusable code designed to perform a specific task. They are an essential part of programming, as they allow you to break down complex problems into smaller, more manageable parts. Functions help make your code more modular, readable, and easier to maintain. They can also reduce repetition by allowing you to reuse code without writing it multiple times.
There are multiple functions that are built in the basic version of python. In total there are 62 built in functions that you can find [here](https://docs.python.org/3/library/functions.html). It is strongly recommended to use this webpage as reference. Those functions are collected in what we call a library. In our case so far, we are using functions from the builtin library. There are plenty of other other libraries that we will be using. If you work a lot with python, you will probably also end up building your own library.
Why Use Functions?
- Modularity: Functions allow you to divide your program into distinct parts, each responsible for a specific task. This makes the code easier to understand and manage.
- Reusability: Once a function is defined, it can be reused multiple times in your program without rewriting the same code.
- Maintainability: Functions help in maintaining the code by isolating tasks. If a change is required, it can be made in the function, and it will reflect wherever the function is called.
- Abstraction: Functions hide the complexity of a task from the main program. The main program only needs to know the function name and what it does, not how it does it.
How to Use Functions in Python?
Defining a Function
To define a function in Python, use the `def` keyword followed by the function name and parentheses. The code block within the function is indented.
def function_name(parameters):
# Function body
return value # Optional return statement
Calling a Function
Once a function is defined, you can call it by using its name followed by parentheses. If the function requires parameters, pass them within the parentheses.
def greet(name):
return f"Hello, {name}!"
# Function call
message = greet("Alice")
print(message) # Output: Hello, Alice!
Calling a Function without a return statement
When a function without a return statement is defined, you can use it in the same way as a function with a return statement. Whenever you call the function, it will execute the code inside. However, because it does not return a value you cannot assign the function to a value, as is done in the ‘message’ above.
def greet(name):
print(f"Hello, {name}!") # this time the printing is already done inside the function
# Function call
greet("Alice") # Output: Hello, Alice!
Parameters and Arguments
Functions can take parameters, which are placeholders for the data you want to pass into the function. When you call the function, you provide arguments, which are the actual data passed to the function.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
Return Values
Functions can return a value using the return statement. If a function does not have a return statement, it returns None by default.
def square(x):
return x * x
result = square(4)
print(result) # Output: 16
Default Parameters
You can define default parameter values in a function. If an argument for that parameter is not provided during the function call, the default value will be used.
def greet(name="Guest"):
return f"Hello, {name}!"
print(greet()) # Output: Hello, Guest!
print(greet("Bob")) # Output: Hello, Bob!
Functions in Python are powerful tools that can greatly improve the efficiency and organization of your code. By using functions, you can write cleaner, more efficient, and more maintainable programs.
Workshop 3: Define Functions and Classes 2/7
Example Functionslink copied
Define a Basic Function
Here’s a very simple Python function, that implements the mathematical function f(x)=2x+1
def f(x):
return 2 * x + 1
You can call this function in the following way: f(10) where f is the function name and 10 is the value of x defined in the function.
Try this:
print(f(10))
Output:
21
You could make the print statement part of the defined function so it directly prints to the console. Try this:
def calculate_f(x):
result = 2 * x + 1
print(result)
calculate_f(10)
Functions with Multiple Arguments
You can specify in the function itself how many argument it should expect. Examine example below:
def calculate_sum(num1, num2, num3):
sum = num1 + num2 + num3
return(sum)
x = calculate_sum(4,3,2)
y = x + 12
print(y)
Output:
21
Local Vs. Global Variables
One important considerations when using custom functions is the idea of local vs global variables.
Variable | Where It’s Defined | Where it Can be Accessed | Duration/Lifespan |
Local Variable | Inside a function | Only inside that function | Created when the function starts, destroyed when it ends |
Global Variable | Outside all function | Anywhere in the program | Exists for the entire program run |
You can define global and local variables in python. Local variables are defined inside a function, and global variables are defined outside of any function. Let’s examine the example below to understand the difference:
x = "global"
y = "also global"
def my_function():
x = "this is the local variable"
y = "this is the local y variable"
print("Inside the function:")
print(f" x is: {x}")
print(f" y is: {y}")
my_function()
print("Outside the function:")
print(f" x is: {x}")
print(f" y is: {y}")
Output:
Inside the function:
x is: this is the local variable
y is: this is the local y variable
Outside the function:
x is: global
y is: also global
Workshop 3: Define Functions and Classes 3/7
Object-Oriented Programming (OOP)link copied
We will cover classes and methods briefly to give you an idea how they work. You are encouraged to practice OOP fundamentals as you will also likely to encounter them in your work.
Fundamental Concepts of OOP
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,” which are instances of “classes.” In this paradigm, classes are blueprints that define the properties (often called attributes or fields) and behaviors (methods or functions) common to all objects of that type. Here’s a brief overview:
Objects:
Objects are instances of classes and can represent real-world entities. Each object can have properties (also called attributes or fields) and behaviors (methods or functions).
Classes:
Classes are blueprints or templates for creating objects. They define the properties and behaviors that their objects will have.
Other key concepts handy to be familair with;
Encapsulation:
This principle is about bundling the data (attributes) and the methods that operate on the data into a single unit or class, and controlling the access to the data by using access modifiers like private, protected, and public.
Inheritance:
Inheritance allows a class to use methods and attributes of another class. The class being inherited from is the “parent” or “superclass,” and the class inheriting is the “child” or “subclass.”
Polymorphism:
Polymorphism allows a single entity, like a method or an object, to take many forms. For example, different objects can respond to the same method name but execute different code based on their class.
Abstraction:
Abstraction is about hiding the complex implementation details and showing only the essential features of an object, which helps in reducing programming complexity and effort.
So, in object-oriented thinking, you model your program using objects, classes, and the interactions between them, while utilizing encapsulation, inheritance, polymorphism, and abstraction to create modular, reusable, and more manageable code.
When to NOT use OOP?
OOP might not be the optimal choice when:
Performance is critical. In some cases, the overhead introduced by OOP can be a drawback, and a procedural or functional approach may be more suitable, like in certain real-time systems or embedded systems.
Memory Usage is a Constraint. The additional memory used by objects can be a limiting factor in environments with strict memory constraints, such as embedded systems or IoT devices.
Workshop 3: Define Functions and Classes 4/7
Example Classes (OOP)link copied
The way this differs from a function is that it has to have an object assigned to a class. <br>
Meaning, a function would simply be written as `function(argument)` whereas an object assigned to a class is called by writing `object_name.method_name(argument)`.
Consider the code below for a simple class definition. See the similarities of syntax as far as indentation and collon usage is similar including defining functions.
# 1. THE CLASS (Blueprint)
class Dog:
# 2. THE METHOD (Action) - Initializes the object
def __init__(self, name, breed):
# 3. THE ATTRIBUTES (Characteristics)
self.name = name
self.breed = breed
def bark(self):
print (f"{self.name} says woof! woof!")
# 4. THE OBJECT (The actual instance created from the blueprint)
my_dog = Dog("Fera", 'Leonberger')
# Accessing an ATTRIBUTE of the object
print(f"My dog's name is {my_dog.name}, she is a {my_dog.breed}")
# Outputs: My dog's name is Fera.
# Calling a METHOD on the object
my_dog.bark()
# Outputs: Fera says Woof!
__init__ Method
To create a class, you will use the __init__ method which is denoted by 2 underscores before “init”.
Examine the class below:
class Fruit:
def __init__(self):
self.name = "Apple"
self.color = "Red"
self.weight = 150
my_fruit = Fruit()
print(my_fruit.name)
These attributes in the fruit class are called “instance variables” or “attributes”. They are hard-coded in the class definition. A better way to approach this is to leverage the __init__ method to initialize the attributes with values passed as arguments when creating an instance of the class.
class Fruit:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
# Now you can create different fruits:
my_fruit= Fruit("Apple", "Red", 150)
your_fruit= Fruit("Banana", "Yellow", 120)
print(my_fruit.name) # Apple
print(your_fruit.name) # Banana
Inheritance
Inheritance in OOP is a way to create a new class that is based on an existing class. The new class inherits attributes and methods from the existing class, allowing for code reuse and extension let’s examine the following example of inheritance in OOP.
# The Parent Class (Blueprint)
class Structure:
# Sets up the attributes all structures share.
def __init__(self, name, city):
self.name = name
self.city = city
# A basic action all structures can perform.
def display_info(self):
print(f"{self.name} is located in {self.city}.")
# The Child Class (Specialized Version)
# Tower inherits from Structure.
class Tower(Structure):
# It takes the parent's parameters, plus one new one.
def __init__(self, name, city, height):
# Call the parent's setup first.
super().__init__(name, city)
# Add a new attribute specific to a Tower.
self.height = height
# Override the parent's method to add more detail.
def display_info(self):
# First, run the parent's original method.
super().display_info()
# Then, add the new, specific information.
print(f"It is {self.height} meters tall.")
# --- See it in Action ---
my_tower = Tower("Eiffel Tower", "Paris", 330)
my_tower.display_info()
We can add a few more child classes. They can inherint the parent class properties and methods. Lets create building typology classes: single family house, apartment building, office building, etc.
# The Parent Class (Blueprint)
class Structure:
# Sets up the attributes all structures share.
def __init__(self, name, city):
self.name = name
self.city = city
# A basic action all structures can perform.
def display_info(self):
print(f"{self.name} is located in {self.city}.")
class SingleFamilyHouse(Structure):
def __init__(self, name, city, num_bedrooms):
super().__init__(name, city)
self.num_bedrooms = num_bedrooms
def display_info(self, typology="Single Family House"):
super().display_info()
print(f"It has {self.num_bedrooms} bedrooms.", "It is a " + typology, "typology.")
# Example of using the SingleFamilyHouse class
my_house = SingleFamilyHouse("My House", "Amsterdam", 3)
my_house.display_info()
Dive Deep into OOP
The topic of OOP is extensive and we’ve just covered a brief overview to get you familiar with how they work. You can explore this topic further by referring to the self-study reference list in the extra resources section for this tutorial.
Workshop 3: Define Functions and Classes 5/7
Helpful Resourceslink copied
Recommended Pythin Learning Resources:
- A Practical Introduction to Python Programming (Heinold 2012) – highly recommended reference book for beginners with hands on exercises
- Think Python – Green Tea Press (free online textbook)
- Python Programming And Numerical Methods: A Guide For Engineers And Scientists (free online textbook)
- Learning Python by Mark Lutz – eBook available, e.g., through TU Delft library
- CS50: Computer Science Courses and Programs from Harvard
Comprehensive Python Tutorials:
Test Your Knowledge:
- W3School Python Exercises and Quizzes (highly recommended)
Helpful Short Educational Videos:
Workshop 3: Define Functions and Classes 6/7
Conclusion / Next Workshoplink copied
Take the opportunity to experiment with different techniques and adopt a problem-solving attitude. By exploring various methods, you’ll deepen your understanding and discover the most effective solutions for different scenarios.
Next Workshop Page
Previous Workshop Pages
Workshop 3: Define Functions and Classes 7/7
Required Readings Before Workshop 4link copied
- Computer Vision Crash Course (video)
- How blurs and filters work (video)
- Working with Image Data in Python
- Matplotlib (1 chapter only)
- Pandas (1 chapter only)
- Expanded: NumPy
Write your feedback.
Write your feedback on "Workshop 3: Define Functions and Classes"".
If you're providing a specific feedback to a part of the chapter, mention which part (text, image, or video) that you have specific feedback for."Thank your for your feedback.
Your feedback has been submitted successfully and is now awaiting review. We appreciate your input and will ensure it aligns with our guidelines before it’s published.