1
Lesson 1
Definition and purpose of Functions
In Python, a function is a reusable block of code designed to perform a specific task. Instead of rewriting the same code over and over, we can define a function once and call it whenever we need to execute that particular task. A function takes inputs (if needed), performs actions, and can return outputs.
Here’s a basic example of a function in Python:
Here’s a basic example of a function in Python:
def greet(name): print(f"Hello, {name}!")
In this example:
- def is the keyword that tells Python we’re defining a function.
- greet is the function’s name, which is used to call it.
- name is a parameter. A placeholder for any value we want to pass in when calling the function.
- Inside the function, we have a print() statement that outputs a greeting.
Calling the Function:
To execute this function, we "call" it by its name and pass any required arguments:
greet("Alice") # Output: Hello, Alice!
Purpose of Functions:
Code reusability: Functions allow us to write a block of code once and use it multiple times. For example, if you need to greet multiple people, you don't have to write the greeting code for each person separately. Instead, you can call
Organizing code: Functions help break down complex tasks into smaller, manageable parts. Each function performs a single task, making the code more organized and readable.
Avoiding redundancy: With functions, there’s no need to repeat the same code multiple times. This minimizes errors and reduces maintenance efforts.
Modularity: Functions help create modular code. A program made up of multiple functions can be more easily understood, debugged, and tested, since each function can be examined individually.
Abstraction: Functions allow us to hide complex details. For example, when using the
Example:
Imagine you’re building a program that calculates the area of different shapes. Instead of writing the code for area calculation each time, you could create separate functions for each shape:
def area_of_circle(radius): return 3.14 * radius ** 2 def area_of_rectangle(length, width): return length * width
Now, to get the area of a circle with radius 5, you simply call:
print(area_of_circle(5)) # Output: 78.5
Using functions in this way keeps your code clean, reusable, and easy to understand.