Home Course Roadmap
Lesson 28 · Functions

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.

45–55 minutes Beginner Functions
0%

What You'll Learn

  • Understand what functions are and why they are useful.
  • Create functions using the def keyword.
  • 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.
01

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.

Python
def greet():
    print("Hello, Python!")

greet()
Output
Hello, Python!
02

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.
Professional programming principle:

If you find yourself writing the same logic repeatedly, consider turning that logic into a function.

03

Defining a Function with def

Python uses the def keyword to define a function.

Basic Syntax
def function_name():
    # function body
    statement

The structure contains several important parts:

  • def tells Python that you are defining a function.
  • function_name is the name of the function.
  • () contains parameters if required.
  • : starts the function body.
  • Indented code belongs to the function.
Example
def welcome():
    print("Welcome to PyLearn!")

Notice that defining the function does not execute it. Python only creates the function at this point.

04

Calling a Function

To execute a function, you must call it.

Calling a Function
def welcome():
    print("Welcome to PyLearn!")

welcome()
Output
Welcome to PyLearn!

The parentheses () tell Python that you want to execute the function.

Important:

Defining a function and calling a function are two different operations.

05

Understanding Function Execution Flow

Python executes a function only when the function is called.

Execution Flow
def message():
    print("Inside the function")

print("Before function")

message()

print("After function")
Output
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.

06

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.

Parameter and Argument
def greet(name):
    print(f"Hello, {name}!")

greet("Ali")
Output
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.

07

Using Multiple Parameters

A function can accept multiple parameters.

Multiple Parameters
def introduce(name, age):
    print(f"My name is {name}.")
    print(f"I am {age} years old.")

introduce("Sara", 22)
Output
My name is Sara.
I am 22 years old.

Arguments are matched to parameters according to their position when positional arguments are used.

Be careful:

If a function requires two arguments and you provide only one, Python will raise a TypeError.

08

Default Parameters

A parameter can have a default value.

Default Parameter
def greet(name="Student"):
    print(f"Hello, {name}!")

greet()
greet("Adnan")
Output
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.

09

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.

Returning a Result
def add(a, b):
    return a + b

result = add(10, 5)

print(result)
Output
15

The value returned by the function can be stored in a variable, printed, compared, or used in another calculation.

Using a Returned Value
def square(number):
    return number * number

answer = square(6)

print(answer + 10)
Output
46

We will explore return values deeply in the dedicated Return Values lesson later in the course.

10

Functions with if Statements

Functions can contain conditional logic.

Condition Inside a Function
def check_age(age):
    if age >= 18:
        print("You are an adult.")
    else:
        print("You are a minor.")

check_age(21)
check_age(15)
Output
You are an adult.
You are a minor.

This approach allows us to package decision-making logic into reusable functions.

11

Functions with Loops

Functions can also contain loops.

Function with a Loop
def print_numbers(limit):
    for number in range(1, limit + 1):
        print(number)

print_numbers(5)
Output
1
2
3
4
5

This is especially useful when a repeated operation needs to be performed in multiple places in a program.

12

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.

Reusable Discount 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))
Output
900.0
2000.0
4250.0
Why this is better:

The discount logic exists in one place. If the formula changes later, you only need to update the function.

13

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

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.

User-Defined Function
def calculate_area(length, width):
    return length * width

print(calculate_area(10, 5))
Output
50
14

Documenting Functions with Docstrings

A docstring is a string placed immediately inside a function to describe what the function does.

Docstring Example
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.

15

Function Naming and Best Practices

Good function names make Python programs easier to read.

Use descriptive names

Good Naming
def calculate_total():
    pass

def validate_email():
    pass

def generate_report():
    pass

Avoid unclear names

Avoid This
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.
Example:

calculate_student_average() is much easier to understand than calc1().

16

Practical Real-World Examples

Example 1 — Student Result

Student Grade Calculator
def calculate_average(marks):
    return sum(marks) / len(marks)

marks = [80, 75, 90, 85, 70]

average = calculate_average(marks)

print(f"Average: {average}")
Output
Average: 80.0

Example 2 — Sales Calculation

Sales Utility
def calculate_revenue(quantity, price):
    return quantity * price

units = 25
price = 1200

revenue = calculate_revenue(units, price)

print(f"Revenue: Rs. {revenue}")
Output
Revenue: Rs. 30000

Example 3 — Login Validation

Simple Login Check
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")
Output
Login successful
Learning example only:

Real applications should never store passwords as plain text. Passwords should be securely hashed and managed by an appropriate authentication system.

17

Common Mistakes

1. Forgetting the colon

Incorrect
def greet()
    print("Hello")

The function definition must end with :.

2. Incorrect indentation

Incorrect
def greet():
print("Hello")

The function body must be indented.

3. Defining but not calling the function

Nothing is printed
def greet():
    print("Hello")

The function exists, but it has not been called.

4. Forgetting required arguments

Incorrect
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.

18

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.

19

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.

Suggested Structure
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)
Expected Output
Student: Ali
Average: 84.60
Grade: A
Challenge goal:

Notice how the program is divided into small, understandable functions. This is how larger programs become easier to maintain.

20

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?

21

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 def to 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.
  • return sends 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.