Function

On day 6 of our programming course, we learned about functions. A function is a block of code that performs a specific task and can be called whenever needed.

1. Definition and Calling functions

Functions are an essential part of programming in Python. They allow us to break down a program into smaller, reusable pieces of code, which can simplify development and make it easier to maintain and update code.

In Python, a function is defined using the def keyword, followed by the name of the function and a set of parentheses. Any parameters the function takes are listed inside the parentheses. The code block for the function is indented below the definition.

Here's an example of a simple function that takes two arguments and returns their sum:

def add_numbers(num1, num2):
    sum = num1 + num2
    return sum

To use this function, we simply call it by name and pass in the arguments:

result = add_numbers(5, 10)
print(result)  # Output: 15

Functions can also have default values for their parameters. Here's an example of a function that takes one required parameter and one optional parameter with a default value:

def greet(name, greeting='Hello'):
    print(f'{greeting}, {name}!')

greet('Alice')  # Output: Hello, Alice!
greet('Bob', 'Hi')  # Output: Hi, Bob!

One of the most useful aspects of functions is that they can return values, which can then be used in other parts of the program. For example, here's a function that calculates the area of a rectangle and returns the result:

def rectangle_area(width, height):
    area = width * height
    return area

# Calculate the area of a rectangle with width 5 and height 10
area = rectangle_area(5, 10)
print(area)  # Output: 50

2. Default Parameters and Keyword Arguments

  1. Default Parameters: In Python, functions can have default parameter values that are used when the caller doesn't pass a value for that parameter. To specify a default parameter value, simply provide an assignment statement for the parameter in the function definition. Here's an example:
def greet(name, greeting='Hello'):
    print(f"{greeting}, {name}!")

# Call the function with only the required parameter
greet('Alice')  # Output: Hello, Alice!

# Call the function with both parameters
greet('Bob', 'Hi')  # Output: Hi, Bob!

In this example, the greeting parameter has a default value of 'Hello', so if the caller doesn't pass a value for that parameter, the default value will be used instead.