Introduction
Welcome to your third lesson in Python programming. In the previous lessons, you've learned to store information in variables and perform actions on that data using operators. So far, your code has been a linear script, executing from top to bottom. To build the complex, intelligent systems you're aiming for—like those a "polymath" engineer would design—you need a way to structure, organize, and reuse your code. This is where functions come in. They are the fundamental building blocks of all modern software.
Brief Recap:
In our last session, you learned to use arithmetic operators (+, *, /) to perform calculations and comparison operators (==, >, <) to create logical expressions that evaluate to True or False.
This Lesson's Goal:
Today, we will focus on functions. By the end of this 60-minute lesson, you will be able to define and call functions with parameters and return values. Specifically, you will learn to:
- Understand the purpose of functions for code organization and reusability.
- Define a function using the
defkeyword. - Call a function to execute its code.
- Pass information into a function using parameters and arguments.
- Send results out of a function using the
returnstatement.

What Are Functions and Why Do We Use Them?
At its heart, a function is a named, reusable block of code that performs a specific task. Think of it as creating your own custom command. Instead of writing the same sequence of instructions multiple times, you can define it once as a function and then "call" it by name whenever you need it.
This principle is called abstraction. It allows you to focus on what a piece of code does, rather than getting lost in the details of how it does it. For someone aspiring to build large-scale systems, mastering abstraction is non-negotiable.
Let's begin with a short, formal introduction to this concept from a university-level resource.
Defining Functions - Computer Science: An Interdisciplinary Approach
This text from Princeton University's Computer Science department introduces the core principle behind functions.
Read the first two paragraphs under the heading '2.1 Defining Functions'. Focus on the key idea: 'Whenever you can clearly separate tasks within a computation, you should do so.'
Defining and Calling Your First Function
Now for the theory of how to create and use a function. A function has two parts:
- Definition: This is where you create the function. You specify its name and the code it contains. The definition doesn't run the code immediately; it just makes the function available for later use.
- Call: This is where you execute the function's code.
The syntax for defining a function in Python involves the def keyword, a function name, parentheses (), and a colon :. The code belonging to the function must be indented.
To see this in action and understand the flow of execution, let's watch a short, visually-driven explanation.
Python Functions - Visually Explained
The video 'Python Functions - Visually Explained' provides an excellent visual breakdown of how Python defines and then executes a function. This will help you build a clear mental model.
Watch from the beginning (00:12) to 04:44. Pay close attention to: The syntax for the function header (def, name, parentheses, colon). The importance of indentation for the function body. The visual trace of how Python calls the function and executes its body.
Passing Information to Functions: Parameters and Arguments
Functions become truly powerful when they can operate on different data. You can pass data into a function when you call it. This requires understanding two key terms:
- Parameter: A variable name listed in the function's definition. It acts as a placeholder for the data that will be passed in.
- Argument: The actual value or data that you send to the function when you call it.
For example, in def greet(name):, name is the parameter. In greet("Alex"), "Alex" is the argument.
This next video provides a very clear explanation of this crucial distinction.
Python Functions | Python Tutorial for Absolute Beginners #1
In this clip from 'Python Functions' by Programming with Mosh, you'll learn the precise difference between parameters and arguments.
Watch from 02:34 to 04:43. Focus on how the arguments passed during the function call are assigned to the parameter variables inside the function.
Types of Arguments
Python is flexible in how you can pass arguments:
- Positional Arguments: These are the standard arguments you've just seen. They are matched to parameters based on their order.
- Keyword Arguments: You can explicitly name the parameter you're assigning the argument to (e.g.,
increment(number=2, by=1)). This makes your code more readable, especially for functions with many inputs. - Default Arguments: You can give a parameter a default value in the function definition (e.g.,
def increment(number, by=1):). If you don't provide an argument forbywhen you call the function, it will automatically use the default value of1.
This next segment of the same video explains these useful features.
Python Functions | Python Tutorial for Absolute Beginners #1
Let's continue with the same video to see how to use keyword and default arguments to make your functions more readable and flexible.
Watch from 10:02 to 12:22. Note how keyword arguments can make a function call read almost like plain English and how default values make some arguments optional.
Getting Results: The return Statement
Some functions just perform an action (like print()), but many are designed to compute a value and send it back to the code that called it. This is done with the return statement.
When Python executes a return statement, it immediately exits the function and sends the specified value back. This returned value can then be stored in a variable or used in another expression.
A very common point of confusion for beginners is the difference between print() and return.
print()displays a value on the screen for a human to see. It does not send any data back to the program itself.returnsends a value back to the program for further processing. This value is invisible to the user unless you explicitly print it.
Let's dive into a detailed reading that clarifies this and other important aspects of returning values.
The Python return Statement: Usage and Best Practices
This article from Real Python, 'The Python return Statement: Usage and Best Practices', is an excellent deep dive into how return works. It directly addresses the common 'returning vs. printing' confusion.
Please read the following sections: 'Understanding the Python return Statement' 'Explicit return Statements' 'Implicit return Statements' (This explains what happens if you don't use return) 'Returning vs Printing' (Pay close attention to this section) Focus on understanding that return is for your program to use, while print is for you to see.
Your Turn: Putting It All Together
It's time to apply these concepts. We'll create a function to perform a simple physics calculation, which directly relates to building the kind of analytical tools you're interested in.
Hands-On Exercise:
Your task is to write a function that calculates the kinetic energy of a moving object. The formula for kinetic energy (KE) is:
where is mass and is velocity.
-
Define the function:
- Create a function named
calculate_kinetic_energy. - It should accept two parameters:
mass_kgandvelocity_mps.
- Create a function named
-
Inside the function:
- Calculate the kinetic energy using the formula above. Use the exponentiation operator
**that you learned in the last lesson. - Use the
returnstatement to send the calculated energy value back.
- Calculate the kinetic energy using the formula above. Use the exponentiation operator
-
Call the function:
- Outside the function, create two variables,
object_massandobject_velocity, and assign them values (e.g., 100 kg and 25 m/s). - Call your
calculate_kinetic_energyfunction, passing your variables as arguments. - Store the returned value in a new variable called
kinetic_energy_joules.
- Outside the function, create two variables,
-
Display the result:
- Use an f-string with the
print()function to display the result in a readable format, like: "The kinetic energy is 31250.0 Joules."
- Use an f-string with the
Example Code Structure:
# 1. Define the function with two parameters
def calculate_kinetic_energy(mass_kg, velocity_mps):
# 2. Calculate the energy and return it
energy = 0.5 * mass_kg * (velocity_mps ** 2)
return energy
# 3. Set up variables and call the function
object_mass = 100 # in kilograms
object_velocity = 25 # in meters per second
kinetic_energy_joules = calculate_kinetic_energy(object_mass, object_velocity)
# 4. Print the final result
print(f"The kinetic energy is {kinetic_energy_joules} Joules.")
Run this code in your environment. This exercise confirms your ability to define a function, pass it arguments, perform a calculation using knowledge from the previous lesson, and correctly capture and use its return value.
Conclusion
Congratulations on mastering one of the most important concepts in programming. Functions allow you to move beyond simple scripts to writing organized, scalable, and maintainable code—the foundation for any complex application, including advanced AI.
Key Takeaways:
- Functions are reusable, named blocks of code defined with the
defkeyword. - They help in abstraction, separating what a task is from how it's done.
- Parameters are the placeholders in a function's definition, while arguments are the actual values you pass during a function call.
- The
returnstatement sends a value back from the function to the calling code, enabling functions to produce results that can be used elsewhere. - A function that doesn't explicitly
returna value will implicitly returnNone.
Preview of the Next Lesson:
You can now create functions, but your code still runs every line in order. The next critical step is to give your programs decision-making power. In the next lesson, we will explore conditional statements (if, elif, else). You'll learn how to control which blocks of code are executed based on specific conditions, making your programs dynamic and intelligent.