Lesson 7: Functions

Jun 18, 2023 | Uncategorized | 0 comments

Home 9 Uncategorized 9 Lesson 7: Functions

Functions are reusable blocks of code that perform a specific task. They help organize code, improve reusability, and make it easier to debug and maintain programs. In Python, we define functions using the def keyword.

Let’s explore how to create and use functions in Python:

# Defining a function
def greet(name):
    print("Hello, " + name + "!")

# Calling a function
greet("Alice")
greet("Bob")

# Function with a return value
def add_numbers(a, b):
    return a + b

result = add_numbers(3, 5)
print("Sum:", result)

Explanation:

  • We define a function greet() that takes a parameter name and prints a greeting message.
  • We call the greet() function with different names as arguments to display personalized greetings.
  • We define a function add_numbers() that takes two parameters a and b and returns their sum using the return statement.
  • We call the add_numbers() function with arguments 3 and 5, store the returned result in the variable result, and print it.

Now it’s time for a practical task:

Task 7:

Write a Python program that defines a function called calculate_average() that takes a list of numbers as a parameter. The function should calculate and return the average of the numbers in the list. Test the function by calling it with different lists of numbers and printing the results.

Once you’ve completed the task, you can proceed to the next lesson.

Join The FFF Newsletter

Future Flow Forecast

Future Flow Forecast

Joinย the number one AI newsletter and learn how to be at the forefront of the latest discoveries. This is your "dotcom bubble" chance!

You have Successfully Subscribed!