Functions in Python

Functions are a fundamental concept in Python. They allow you to organize your code into reusable blocks, making your programs cleaner and easier to manage. A function is a named section of a program that performs a specific task.

What is a Function?

A function in Python is defined using the def keyword followed by the function name, parentheses, and a colon. Inside the function, you write the code that you want the function to execute when called.

Example: Defining a Function

def greet():
    print("Hello, world!")

Explanation

In this example, we defined a function called greet(). When called, it will print "Hello, world!" to the screen. To call a function, simply write its name followed by parentheses, like this:

greet()

This will output:

Hello, world!

Functions with Parameters

Functions can also accept parameters, which are values that you pass into the function to modify its behavior. Here’s an example:

def greet(name):
    print("Hello, " + name + "!")

Now, the function greet() takes a parameter name. When you call the function, you can pass in a value:

greet("Alice")

This will output:

Hello, Alice!

Returning Values from Functions

Functions can also return values using the return keyword. This allows you to store the result of a function call in a variable for later use. Here’s an example:

def add(a, b):
    return a + b
result = add(3, 5)
print(result)

This will output:

8

Explanation

The function add() takes two parameters, a and b, and returns their sum. The return keyword sends the result back to the place where the function was called, and we store that result in the variable result.

Exercise

Create a function called multiply() that takes two numbers as input and returns their product. Then call the function with two numbers and print the result.