21. Functions in Python

Quiz: 0/5

In Python, a function is a reusable block of code designed to perform a specific task. Functions save us from rewriting the same code repeatedly and make our programs more modular, readable, and maintainable.

Instead of duplicating code, we define a function once and call it whenever we need to execute the task it performs.

Defining a function

A function can:

  • Take inputs (parameters) to work with.
  • Perform a series of actions.
  • Optionally, return outputs.

Here’s a simple example:

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

Breaking it down:

  1. def: The keyword to define a function.
  2. greet: The name of the function. You’ll use this name to call it later.
  3. name: A parameter, which acts as a placeholder for any value you pass to the function.
  4. Inside the function, the print() statement executes an action: it prints a greeting that includes the value of name.

Calling a function

To execute the function, we "call" it by its name and provide any required arguments (values for its parameters). For example:

greet("Alice")  # Output: Hello, Alice!

You can reuse the same function with different arguments:

greet("Bob")    # Output: Hello, Bob!
greet("Eve")    # Output: Hello, Eve!

Why use functions?

Functions offer several important benefits:

1. Code reusability

Write the code once, reuse it anywhere. For instance, instead of repeating the same greeting logic, you can just call greet() multiple times.

2. Code organization

Break complex tasks into smaller, manageable parts. Each function performs a specific job, making your code easier to understand and maintain.

3. Avoiding redundancy

No need to repeat yourself! Functions minimize repetition, reducing errors and simplifying updates.

4. Modularity

Functions make your code modular. You can test, debug, or improve individual pieces of functionality without affecting the rest of the program.

5. Abstraction

Functions hide complex implementation details. For example, you don’t need to know how the built-in print() function works internally—you just call it. Similarly, you can write your own functions to abstract away repetitive or complex logic.

Example: Calculating areas

Imagine you’re building a program to calculate the area of different shapes. Instead of repeating similar logic, you can define reusable functions:

def area_of_circle(radius):
    return 3.14 * radius ** 2

def area_of_rectangle(length, width):
    return length * width

Now, you can calculate areas easily:

print(area_of_circle(5))          # Output: 78.5
print(area_of_rectangle(10, 4))   # Output: 40

Key takeaways

  • Functions make your code cleaner, reusable, and easier to manage.
  • They allow you to focus on solving bigger problems by breaking them into smaller, independent tasks.
  • Good functions are like building blocks—they let you assemble complex programs from simple, reliable components.

By using functions effectively, you’ll write code that’s not only functional but also elegant and maintainable.

Hands-On Practise

Exercise: Creating and using functions

Write a Python program that performs the following tasks:

  1. Define a function called greet_user that:

    • Takes a single parameter, name.
    • Prints a greeting in the format: "Welcome, <name>!".
  2. Define a second function called area_of_square that:

    • Takes one parameter, side_length.
    • Calculates and returns the area of a square using the formula: \text{Area} = \text{side_length}^2
  3. Call the greet_user function to greet the user (you can use your own name).

  4. Ask the user to input the side length of a square and use the area_of_square function to calculate its area.

    • Display the result in the format:
      "The area of the square is: <calculated_area>".
Output:

Quizzes: 0/5

Question 1:

What is the primary purpose of a function in Python?

  • To store multiple values in a single variable.
  • To perform a specific task and allow code reuse.
  • To execute code only when certain conditions are met.
  • To handle errors in the program.

Question 2:

Which keyword is used to define a function in Python?

  • function
  • def
  • lambda
  • define

Question 3:

What is a parameter in a Python function?

  • A variable defined outside the function.
  • A value that a function returns after execution.
  • A placeholder for a value passed to the function.
  • A block of code within the function.

Question 4:

What will the following code output? `python def greet(name): print(f"Hello, {name}!") greet("Alice") `

  • Hello, name!
  • Hello, Alice!
  • Error: name not defined.
  • The code will not run because it is missing a return statement.

Question 5:

What does the 'return' statement do in a function?

  • It ends the program.
  • It specifies the inputs a function takes.
  • It stops the function and outputs a value.
  • It repeats the function's execution.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonPython Modules and LibrariesNext lessonCalling Functions