What Are Functions?
A function packages a piece of logic into a reusable block of code. Instead of copying and pasting the same code multiple times, you define it once and call it whenever needed. The mental model is input → process → output: you give the function some input, it performs processing, and can produce an output.
Defining vs. Calling a Function
- Defining: Python remembers the logic but does not execute it yet.
- Calling: Python executes the logic inside the function right now.
def greet(): # define
print("hello")
greet() # call → outputs "hello"
Think of a function as a reusable box with a name. You give it instructions once, then use it many times.
Syntax Breakdown
| Element | Purpose |
|---------|---------|
| def | Keyword to start defining a function |
| greet | Name of the function |
| () | Parentheses after the name (can hold parameters) |
| : | Colon begins the function body |
| Indented block | The code that belongs to the function |
| greet() | Calling the function |
Parameters: Making Functions Flexible
Instead of writing a separate function for every person, use a parameter, a variable that receives a value when the function is called.
def greet(name):
print("hello", name)
greet("Alex") # hello Alex
greet("Sam") # hello Sam
greet("Jordan") # hello Jordan
Write the logic once, use it many times with different inputs.
The return Statement
return sends a value back from the function so the rest of your program can use it. This is different from print(), which only displays a value.
Without return (just displays):
def square(x):
print(x * x)
square(5) # prints 25, but result is lost
With return (usable value):
def square(x):
return x * x
result = square(5) # result holds 25
double = result * 2 # now we can use it further
| Action | Purpose |
|--------|---------|
| print() | Displays output to screen |
| return | Sends a value back for program to use |
Examples
Average of Two Numbers
def average(a, b):
return (a + b) / 2
result = average(80, 90)
print(result) # 85.0
Function Inside a Loop
def square(n):
return n * n
numbers = [2, 3, 4]
for num in numbers:
print(square(num)) # 4 9 16
Several concepts work together: list stores values, loop processes one at a time, function performs reusable logic, and return sends back the result. For a deeper dive into Python's building blocks, see the Comprehensive Python Tutorial: Variables, Control Flow, Functions, Classes, and File Handling.
Why Functions Matter for AI Engineering
Real AI applications are built from many small pieces. Functions help organize that complexity:
def clean_text(text):
return text.strip()
def calculate_score(value):
return value * 100
def format_response(response):
return response.strip()
Each function has a focused responsibility, one job, done well. A prompt flows through: clean → model → process → score → format output. Mastering functions is a key step in the Python Mastery Course: Complete Beginner to Pro Guide (2024).
Functions Without Return
A function doesn't always need to return a value. It can simply perform an action:
def show_status():
print("Model is ready")
show_status() # prints the message
When another part of the program needs the result, use return. When you just need an effect, use print.
Maintainability and Readability
- Write once, reuse many times: Update the function in one place, and every caller benefits.
- Meaningful names:
clean_text,generate_response,calculate_scoretell you what the program does before you read the implementation. These are examples of the Top 10 Python Functions to Simplify Your Coding Experience.
Core Python Foundations Recap
| Concept | Purpose | |---------|---------| | Variables & Data Types | Store values of different kinds | | Collections (list, tuple, dict, set) | Organize multiple values | | Conditionals | Make decisions | | Loops | Repeat work | | Functions | Package logic into reusable units |
The pattern: Store. Organize. Decide. Repeat. Reuse. This is how you start thinking like a Python programmer and build the foundation for AI engineering. For those interested in applying these skills to AI, check out Introduction to Artificial Intelligence with Python: Search Algorithms and the Comprehensive Artificial Intelligence Course: AI, ML, Deep Learning & NLP.
In the previous lesson we learned about loops. Loops let Python repeat an action.
Collection, one item at a time, repeat. But now we have another problem. Imagine you write a useful piece of
code. You use it once. Later in your program,
you need the same logic again. You could copy and paste the code. But what if you need it 10 times?
Or 100 times? Copying the same code again and again makes programs difficult to maintain.
If the logic changes, you may have to update it in many different places.
Python gives us a better solution. Functions. A function packages a piece of logic
into a reusable block of code. The mental model for this lesson is input, process, output.
You give the function some input. The function performs some processing. And it can produce an output.
Let's start with the simplest possible function. Define greet. Inside it, print hello.
Something important has happened. We have defined a function. But Python has not run the print
statement yet. We have only created the function. To run it, we call the function
greet. Now Python executes the code inside the function, and the output is hello.
This distinction is important. Defining a function means Python, remember this piece of logic.
Calling a function means Python, execute that logic now. So think of a function as a reusable
box. The box contains some instructions, and we give it a name.
Whenever we need those instructions, we call the function. Let's look at the syntax.
The keyword def tells Python that we are defining a function. Greet is the function name and the
parentheses come after it. The colon begins the function body and the indented code belongs to the
function. Then we call it with greet followed by parentheses.
Notice how simple the idea is. Define once, use many times. Now let's make the function more useful.
What if we want to greet different people? We don't want a separate function for
every person. Instead, we can give the function an input. Define greet with the parameter name.
Print hello and name. Here, name is a parameter, a variable that receives a value when the function
is called. Now we can call the same function with different values. Alex, Sam, and Jordan.
The output is hello Alex, hello Sam, hello Jordan. We wrote the logic once, but we used it
three times. That's the real power of function. Let's visualize what happened.
When we call greet with Alex, the value Alex enters the function. The input enters, the function processes
it, the result appears. Input, process, output.
Now let's make the processing more obvious. Suppose we want to calculate the square of a number.
Define square with the parameter number. Return number times number. We call it result equals square of five.
Then print result. What do you think the output will be? The answer is 25.
Let's understand what Python did. The value five enters the function and the parameter number receives it.
Python calculates number times number, which becomes five times five. And it produces 25.
But this time we use something new. Return.
The return statement sends a value back from the function. This is different from simply printing
something. If square prints number times number it only displays the result.
If square returns number times number, the rest of our program can use it. This distinction becomes extremely
important as programs grow. Let's see why. Result equals square of five.
Now result contains the returned value. We can print it or use it in another calculation. Double
equals result times two. The function becomes part of a larger program.
That's one of the biggest reasons functions are so useful. They organize a program into smaller
pieces of logic. Let's look at another example. The average of two numbers.
Define average with the parameters A and B. Return A plus B divided by two.
Result equals average of 80 and 90. Print result. The output is 85.0.
Here we have two parameters, A and B. The value 80 goes into A. The value 90 goes into B.
The function processes those values and returns the result. 80 and 90
process 85.0. Again, input process
output. Now, let's connect functions to something we already know.
Remember loops? We can use a function inside a loop. Numbers equals 2 3 4.
For number in numbers, result equals square of number. Print result.
What happens here? The loop takes one number at a time. The function processes that number and
the result is printed. The output is 4 9 16. So, now several Python concepts work
together. The list stores multiple values. The loop processes one value at a time.
The function performs reusable logic and return sends the result back. This is much closer to how real programs
are structured. Functions become especially important in AI engineering.
In an AI application, you may need to process a prompt, call a model, clean some text, calculate a score, validate a
response, or format data for an API. You could put all of that logic into one enormous block of code,
but that becomes difficult to understand and maintain. Instead, functions let us separate the
work. Clean text takes some text and returns text.strip.
Now, we have reusable logic for cleaning text. Prompt equals clean_text of prompt.
Another function could handle scoring. Calculate score returns value * 100. And another could handle formatting.
Format response returns response.strip. Each function has a focused responsibility.
This is a major programming habit. Instead of one giant block, we break the application into smaller pieces, and
each function does one specific job. A prompt comes in, one function cleans it, another sends it to the model,
another processes the response, another calculates a score, and out comes the final result.
This is how functions become a foundation for larger AI system. Now let's look at another important
idea. A function does not always need to return a value.
Show status simply prints. Model is ready. This function performs an action. It
does not need to return anything. But when another part of the program needs the result, return becomes
important. So remember, print displays something. Return sends a value back.
Functions also make programs easier to maintain. Imagine the same calculation in 10
different places. Without a function, you might copy it 10 times. If it changes, you have to find
and update 10 pieces of code. With a function, the logic lives in one place, and every part of the program
calls it. If the logic changes, you update the function, and the rest of the program
keeps using it. That gives us another important idea. Write once, reuse many times.
Functions also make code easier to understand. Instead of a large block of
instructions, you see meaningful names: clean text, generate response, calculate score, format output.
Even before reading the implementation, the names tell you what the program is doing.
Let's bring the entire course together. Variables store values. Data types tell us what kind of values
we are working with. Lists, tuples, dictionaries, and sets organize data.
Conditionals make decisions. Loops repeat work. And functions package logic into
reusable units. A function receives information, performs a task, and can return a
result. Input, process, output. Write once, reuse many times.
In AI engineering, this becomes even more important. Real AI applications are not just one line of code calling a
model. They are systems made from many smaller pieces.
One function prepares the input, another calls the model, another processes the response, another evaluates the result,
and another formats the final output. So, when you learn functions, you're not just learning another Python keyword.
You're learning how to organize logic and make code reusable. And with that, we've completed the core
Python foundations of this course. You now understand how Python stores values, organizes collections, makes
decisions, repeats work, and packages reusable logic. Together, these are the building blocks
you'll use with AI systems, automation, data, APIs, and LLM application. The syntax is only the beginning.
The real goal is to understand the patterns behind the code. Store.
Organize. Decide. Repeat. Reuse.
That's how you start thinking like a Python programmer. And that's the foundation for becoming a
Python AI engineer.
A function packages a piece of logic into a reusable block of code, following an input → process → output pattern. Instead of copying and pasting code, you define the logic once and call it whenever needed. This improves code reusability, maintainability, and readability—core principles for building AI applications.
When you define a function with def, Python remembers the logic but does not execute it. When you call the function by its name followed by parentheses, Python executes the logic immediately. For example, def greet(): print("hello") defines it, but greet() triggers the output.
Parameters are variables in the function definition that receive values (arguments) when the function is called. Instead of writing separate functions for different inputs (like greet_Alex(), greet_Sam()), you define greet(name) once and call it with different arguments—greet("Alex"), greet("Sam")—reusing the same logic.
print() only displays output to the screen but does not produce a value the program can use later. return sends a value back from the function, allowing the rest of the program to capture it in a variable and use it for further computation. For example, result = square(5) lets you use result elsewhere, while print(square(5)) only shows the number.
Yes, a function does not always need a return statement. It can simply perform an action, like printing a status message (def show_status(): print("Model is ready")). Use return when you need the result for further work; use just side effects (like print) when you only need an effect.
Real AI applications are built from many small, reusable pieces. Functions help organize complexity by giving each piece a focused responsibility—like clean_text(), calculate_score(), or format_response(). This makes code easier to test, debug, and maintain, and fits naturally into AI pipelines where data flows through distinct processing steps.
Start with def, the function name, parentheses (for parameters, if any), a colon, and an indented block of code. To call the function, use its name followed by parentheses. Example: def greet(): print("hello") (definition) and then greet() (call). The key parts are def, name, parentheses, colon, and the indented body.
Keep this summary
Save it to LunaNotes and it becomes a real note in your library — editable, searchable, and ready to turn into flashcards or a diagram. Free to start.
Save to LunaNotesOr summarise for another video.
32K+ people have turned 65K+ videos into notes
“Very useful tool. I'm using it for the last couple weeks and I'm loving it so far. Makes learning on YouTube a great experience.”
This summary and transcript were automatically generated using AI with the Free YouTube transcript summary tool by LunaNotes.
Related summaries
Python Mastery Course: Complete Beginner to Pro Guide (2024)
Learn Python from scratch with this comprehensive guide covering variables, strings, numbers, and essential programming concepts. Master Python for AI, web development, and automation with step-by-step tutorials from an experienced software engineer.
Top 10 Python Functions to Simplify Your Coding Experience
Discover 10 essential Python functions that can save time and reduce headaches while coding.
CS50 Harvard: From Binary Basics to Building Interactive AI Chatbots and Games
Discover Harvard's CS50 introductory course, exploring foundational computer science concepts from binary data representation to AI programming and game development with Scratch and Python. Learn how fundamental algorithms, data structures, and coding techniques empower you to solve complex problems and create dynamic applications, including chatbots and interactive games.
Comprehensive Python Tutorial: Variables, Control Flow, Functions, Classes, and File Handling
This detailed video tutorial covers foundational to advanced Python programming concepts, including variables, operators, user input, control structures, loops, functions, classes with inheritance, exception handling, and file operations. Designed for learners aiming to build practical coding skills, it offers example-driven explanations and program walkthroughs for real-world application.
NumPy Array Creation: Zeros, Ones, Identity & Random Functions
Learn why NumPy arrays are crucial for data organization in AI/ML, then master 7 essential array creation functions: zeros, ones, full, arange, identity, linspace, and random. Includes practical Jupyter Notebook examples for each function with 1D, 2D, and 3D arrays.
Most viewed summaries
A Comprehensive Guide to Using Stable Diffusion Forge UI
Explore the Stable Diffusion Forge UI, customizable settings, models, and more to enhance your image generation experience.
Kolonyalismo at Imperyalismo: Ang Kasaysayan ng Pagsakop sa Pilipinas
Tuklasin ang kasaysayan ng kolonyalismo at imperyalismo sa Pilipinas sa pamamagitan ni Ferdinand Magellan.
Mastering Inpainting with Stable Diffusion: Fix Mistakes and Enhance Your Images
Learn to fix mistakes and enhance images with Stable Diffusion's inpainting features effectively.
Pamamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakaran ng mga Espanyol sa Pilipinas, at ang epekto nito sa mga Pilipino.
How to Install and Configure Forge: A New Stable Diffusion Web UI
Learn to install and configure the new Forge web UI for Stable Diffusion, with tips on models and settings.
Found this summary useful?
Take it with you. One click puts it in your own LunaNotes library.
Save to LunaNotes