Functions

In Python, a function is a block of code that performs a specific task. Functions help to modularize code, making it more readable and reusable.

To define a function, we use the def keyword followed by the function name and parentheses. Inside the parentheses, we can specify parameters that the function can accept. The code block within every function starts with a colon (:) and is indented.

Let's start with a simple function that prints a greeting message:

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

When we call the greet() function, it prints "Hello, world!" to the console.

Functions can also accept parameters, which allow us to pass values into the function for processing. Here's an example:

def greet(name):
    print(f"Hello, {name}!")
greet("Alice")  # Output: "Hello, Alice!"
greet("Bob")    # Output: "Hello, Bob!"

In this example, the greet function accepts one parameter name. When we call the function and pass in a value like "Alice" or "Bob", the function prints a personalized greeting message.

Functions can return values using the return statement. This allows us to capture the result of a function and use it in our code. Here's an example:

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

The add function takes two parameters a and b, adds them together, and returns the result. We can then store the returned value in a variable and print it.

Functions can have default parameter values, which are used if no argument is provided when the function is called. Here's an example:

def greet(name="world"):
    print(f"Hello, {name}!")
greet()         # Output: Hello, world!
greet("Alice")  # Output: Hello, Alice!

In this example, the greet function has a default parameter value of "world". If no argument is passed when the function is called, it uses the default value.

We can also define functions that accept a variable number of arguments using the *args and **kwargs syntax. Here's an example:

def add(*args):
    return sum(args)
print(add(1, 2, 3))        # Output: 6
print(add(4, 5, 6, 7))    # Output: 22

The add function uses *args to accept a variable number of arguments. Inside the function, args is a tuple containing all the arguments passed. We use the sum function to add all the values together and return the result.

The **kwargs syntax allows us to accept a variable number of keyword arguments. Here's an example:

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")

In this example, the print_info function uses **kwargs to accept a varying number of keyword arguments. Inside the function, kwargs is a dictionary containing all the keyword arguments passed. We loop through the dictionary and print each key-value pair.

Functions are a fundamental part of Python programming, enabling us to create modular, reusable, and maintainable code. As we progress, we'll explore more advanced concepts and techniques related to functions.


Quiz

Question 1

What keyword is used to define a function in Python?





Question 2

What will be the output of the following code?

def greet(name):
    print(f"Hello, {name}!")  
greet("Alice")




Question 3

What does the following function return?

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




Question 4

What will be the output of the following code?

def greet(name="world"):
    print(f"Hello, {name}!")  
greet()




Code Editor