Understanding Functions
What is a Function?
A function is a block of reusable code designed to perform a specific task. It helps make your code organized, reusable, and easier to understand.
Why Use Functions?
To avoid repeating the same code.
To make programs easier to debug and maintain.
To break down complex problems into smaller, manageable pieces.
How to Define a Function
In Python, you define a function using the def keyword.
Basic Syntax
def function_name():
# Code to run
Examples
Example 1: A Simple Function
def greet():
print("Hello, world!")
How to Use It:
You call a function by typing its name followed by parentheses:
greet()
Output:
Hello, world!
Functions with Parameters
Parameters allow you to pass information to a function.
Syntax
def function_name(parameter1, parameter2):
# Code to run
Example 2: Greeting Someone by Name
def greet(name):
print(f"Hello, {name}!")
Calling the Function:
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!
Functions with Return Values
A function can send back a value using the return statement.
Example 3: Adding Two Numbers
def add_numbers(a, b):
return a + b
Using the Function:
result = add_numbers(5, 3)
print(result)
Output:
8
Practice Exercises
Exercise 1: Hello Function
Write a function called say_hello() that prints "Hello, world!" Call the function three times.
Exercise 2: Favorite Food
Write a function called favorite_food(food) that prints "I love [food]!" Replace [food] with the parameter value.
Exercise 3: Area of a Rectangle
Write a function called rectangle_area(length, width) that returns the area of a rectangle. Test it by printing the area of a rectangle with a length of 5 and width of 10.
Exercise 4: Even or Odd
Write a function called is_even(number) that checks if a number is even or odd and prints the result.
Exercise 5: Multiplication Table
Write a function called multiplication_table(n) that prints the multiplication table for n up to 10.
Challenge Exercise
Write a function called grade_calculator(marks) that takes a percentage mark as input and returns a grade:
90% or more: A
80% to 89%: B
70% to 79%: C
60% to 69%: D
Below 60%: F
Tips for Using Functions
Use meaningful names for functions and parameters.
Write comments inside your functions to explain what they do.
Test your functions with different inputs to make sure they work.
Congratulations!
You’ve learned how to define and use functions in Python. Functions are one of the most powerful tools in programming. Keep practicing to become an expert! 🎉