Here’s how you define a function:
def function_name():
# do something
Let’s define a function named greet That prints a greeting:
def greet():
print("Hello, Python learner! 🚀")
Calling a Function 📞
After defining a function, you can call it by its name followed by parentheses.
Let’s call our greet function:
greet() # Output: Hello, Python learner! 🚀
Functions with Parameters 📦
Sometimes, we want our function to perform an operation on a variable. We can
achieve this by defining a function with the parameters:
def greet(name):
print(f"Hello, {name}! 🚀")
Now, when we call the greet Function, we need to provide a name:
greet("Alice") # Output: Hello, Alice! 🚀
Functions that Return Values 🎁
Sometimes, we want our function to give us back a result that we can use later. For
this, we use the return statement:
def square(number):
return number ** 2
When we call this function with a number, it gives us the square of that number:
result = square(5)
print(result) # Output: 25
Exercise : Now, your task is to create a function called calculate_average that
takes a list of numbers as an argument and returns their average. Test your
function with different lists of numbers to ensure it works correctly.
Here’s a skeleton to get you started:
def calculate_average(numbers):
# Calculate the sum of the numbers
# Divide the sum by the length of the numbers list to get the average
# Return the average
numbers = [1, 2, 3, 4, 5]
print(calculate_average(numbers)) # This should print the average of the numbers
in the list
Solution:
def calculate_average(numbers):
# Calculate the sum of the numbers
sum_of_numbers = 0
for number in numbers:
sum_of_numbers += number
# Divide the sum by the length of the numbers list to get the average
average = sum_of_numbers / len(numbers)
# Return the average
return average
numbers = [1, 2, 3, 4, 5]
print(calculate_average(numbers)) # prints: 3.0
Keep practicing and experimenting with functions. Happy coding, and see you in the
next lecture! 🚀