Defining A Function
Defining A Function
def function_name():
# do something
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 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
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)
Keep practicing and experimenting with functions. Happy coding, and see you in the
next lecture! 🚀