Python Functions
Learn how to create reusable blocks of Python code using functions. Functions are one of the most important building blocks of professional Python programs.
What You'll Learn
- Understand what functions are and why they are useful.
- Create functions using the
defkeyword. - Call functions and understand their execution flow.
- Work with parameters and arguments.
- Understand default parameters and return values.
- Build reusable functions using conditions and loops.
- Write cleaner and more professional Python programs.
What Is a Function?
A function is a reusable block of code that performs a specific task.
Instead of writing the same code again and again, you can place that code inside a function and execute it whenever you need it.
Think of a function as a small machine:
Function Concept
Input → Function → Processing → Output
A function can receive data, process it, and optionally return a result.
def greet():
print("Hello, Python!")
greet()
Hello, Python!
Why Functions Matter
Functions are extremely important because real-world programs can contain thousands or even millions of lines of code.
Without functions, maintaining such programs would become extremely difficult.
Functions help you:
- Reuse code.
- Avoid unnecessary repetition.
- Organize large programs.
- Make code easier to understand.
- Test individual pieces of logic.
- Fix problems more easily.
- Build scalable applications.
If you find yourself writing the same logic repeatedly, consider turning that logic into a function.
Defining a Function with def
Python uses the def keyword to define a function.
def function_name():
# function body
statement
The structure contains several important parts:
deftells Python that you are defining a function.function_nameis the name of the function.()contains parameters if required.:starts the function body.- Indented code belongs to the function.
def welcome():
print("Welcome to PyLearn!")
Notice that defining the function does not execute it. Python only creates the function at this point.
Calling a Function
To execute a function, you must call it.
def welcome():
print("Welcome to PyLearn!")
welcome()
Welcome to PyLearn!
The parentheses () tell Python that you want to
execute the function.
Defining a function and calling a function are two different operations.
Understanding Function Execution Flow
Python executes a function only when the function is called.
def message():
print("Inside the function")
print("Before function")
message()
print("After function")
Before function Inside the function After function
When Python reaches message(), execution moves
into the function. After the function finishes, execution
returns to the next statement.
Parameters and Arguments
Functions can receive information from the code that calls them.
A variable written inside the function definition is called a parameter.
The actual value passed when calling the function is called an argument.
def greet(name):
print(f"Hello, {name}!")
greet("Ali")
Hello, Ali!
Here, name is the parameter and
"Ali" is the argument.
Remember
Parameter: variable in the function definition.
Argument: value supplied when calling the function.
Using Multiple Parameters
A function can accept multiple parameters.
def introduce(name, age):
print(f"My name is {name}.")
print(f"I am {age} years old.")
introduce("Sara", 22)
My name is Sara. I am 22 years old.
Arguments are matched to parameters according to their position when positional arguments are used.
If a function requires two arguments and you provide only
one, Python will raise a TypeError.
Default Parameters
A parameter can have a default value.
def greet(name="Student"):
print(f"Hello, {name}!")
greet()
greet("Adnan")
Hello, Student! Hello, Adnan!
When no argument is supplied, Python uses the default value.
When an argument is supplied, the provided value replaces the default.
Coming Up Later
We will study parameter types, keyword arguments,
*args, and **kwargs in much
greater detail in later lessons.
Return Values
A function can calculate something and send a result back to the code that called it.
Python uses the return statement for this purpose.
def add(a, b):
return a + b
result = add(10, 5)
print(result)
15
The value returned by the function can be stored in a variable, printed, compared, or used in another calculation.
def square(number):
return number * number
answer = square(6)
print(answer + 10)
46
We will explore return values deeply in the dedicated Return Values lesson later in the course.
Functions with if Statements
Functions can contain conditional logic.
def check_age(age):
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
check_age(21)
check_age(15)
You are an adult. You are a minor.
This approach allows us to package decision-making logic into reusable functions.
Functions with Loops
Functions can also contain loops.
def print_numbers(limit):
for number in range(1, limit + 1):
print(number)
print_numbers(5)
1 2 3 4 5
This is especially useful when a repeated operation needs to be performed in multiple places in a program.
Functions Create Reusable Code
One of the biggest advantages of functions is code reuse.
Imagine that an ecommerce application needs to calculate a discount in ten different places.
Instead of writing the calculation ten times, we can create one function.
def calculate_discount(price, discount):
return price - (price * discount / 100)
print(calculate_discount(1000, 10))
print(calculate_discount(2500, 20))
print(calculate_discount(5000, 15))
900.0 2000.0 4250.0
The discount logic exists in one place. If the formula changes later, you only need to update the function.
Built-in vs User-Defined Functions
Python provides many functions that are already available. These are called built-in functions.
Examples of built-in functions
print("Hello")
len("Python")
type(25)
max(10, 20, 30)
min(10, 20, 30)
sum([10, 20, 30])
A user-defined function is a function that you create yourself.
def calculate_area(length, width):
return length * width
print(calculate_area(10, 5))
50
Documenting Functions with Docstrings
A docstring is a string placed immediately inside a function to describe what the function does.
def calculate_area(length, width):
"""Calculate the area of a rectangle."""
return length * width
print(calculate_area(8, 4))
Docstrings are especially useful when working on large projects or collaborating with other developers.
Professional Habit
Give important functions clear documentation so another developer can understand their purpose without reading every line of implementation.
Function Naming and Best Practices
Good function names make Python programs easier to read.
Use descriptive names
def calculate_total():
pass
def validate_email():
pass
def generate_report():
pass
Avoid unclear names
def x():
pass
def do_it():
pass
Useful guidelines
- Use lowercase names.
- Use underscores between words.
- Choose names that describe the task.
- Keep functions focused on one main responsibility.
- Avoid unnecessarily large functions.
- Use docstrings for important functions.
calculate_student_average() is much easier
to understand than calc1().
Practical Real-World Examples
Example 1 — Student Result
def calculate_average(marks):
return sum(marks) / len(marks)
marks = [80, 75, 90, 85, 70]
average = calculate_average(marks)
print(f"Average: {average}")
Average: 80.0
Example 2 — Sales Calculation
def calculate_revenue(quantity, price):
return quantity * price
units = 25
price = 1200
revenue = calculate_revenue(units, price)
print(f"Revenue: Rs. {revenue}")
Revenue: Rs. 30000
Example 3 — Login Validation
def check_login(username, password):
if username == "admin" and password == "1234":
return True
return False
if check_login("admin", "1234"):
print("Login successful")
else:
print("Invalid credentials")
Login successful
Real applications should never store passwords as plain text. Passwords should be securely hashed and managed by an appropriate authentication system.
Common Mistakes
1. Forgetting the colon
def greet()
print("Hello")
The function definition must end with :.
2. Incorrect indentation
def greet():
print("Hello")
The function body must be indented.
3. Defining but not calling the function
def greet():
print("Hello")
The function exists, but it has not been called.
4. Forgetting required arguments
def add(a, b):
return a + b
add(10)
The function requires two arguments but only one was provided.
5. Confusing print with return
Important Difference
print() displays information to the
screen.
return sends a value back to the caller.
Practice Exercises
Exercise 1 — Greeting Function
Create a function called greet() that prints
Hello, Python!.
Exercise 2 — Personalized Greeting
Create a function that accepts a person's name and prints a personalized greeting.
Exercise 3 — Add Two Numbers
Create a function that accepts two numbers and returns their sum.
Exercise 4 — Even or Odd
Create a function that accepts a number and prints whether it is even or odd.
Exercise 5 — Rectangle Area
Create a function that accepts length and width and returns the area of a rectangle.
Exercise 6 — Student Average
Create a function that accepts a list of marks and returns the average.
Exercise 7 — Discount Calculator
Create a function that receives a price and discount percentage and returns the final price.
Mini Challenge — Student Grade Calculator
Build a small program that uses functions to calculate a student's result.
🎯 Your Mission
Create separate functions for:
- Calculating the average.
- Determining the grade.
- Displaying the result.
The program should accept five marks and produce a professional result summary.
def calculate_average(marks):
return sum(marks) / len(marks)
def calculate_grade(average):
if average >= 80:
return "A"
elif average >= 70:
return "B"
elif average >= 60:
return "C"
elif average >= 50:
return "D"
else:
return "F"
def display_result(name, average, grade):
print(f"Student: {name}")
print(f"Average: {average:.2f}")
print(f"Grade: {grade}")
marks = [85, 78, 92, 88, 80]
average = calculate_average(marks)
grade = calculate_grade(average)
display_result("Ali", average, grade)
Student: Ali Average: 84.60 Grade: A
Notice how the program is divided into small, understandable functions. This is how larger programs become easier to maintain.
Quick Knowledge Check
1. Which keyword is used to define a function?
2. What does calling a function do?
3. What is a parameter?
4. What keyword sends a value back from a function?
5. Which is a valid function definition?
6. What is the main benefit of functions?
7. What happens if a required argument is missing?
8. What is a docstring used for?
Lesson Summary
Functions are one of the most important concepts in Python. They allow you to organize code into reusable pieces that perform specific tasks.
Key Takeaways
- Use
defto define a function. - Call a function using its name followed by parentheses.
- Parameters allow functions to receive information.
- Arguments are the actual values supplied to parameters.
- Default parameters provide fallback values.
returnsends a result back to the caller.- Functions can contain conditions and loops.
- Functions reduce repetition and improve organization.
- Docstrings can document important functions.
- Good function names make programs easier to understand.
In the next lesson, we will take parameters much further and explore how Python handles different types of arguments, including positional arguments, keyword arguments, and more.
Ready for Lesson 29?
Mark this lesson complete when you are comfortable creating and calling basic Python functions.