Skip to Content
Course content

4.1 Defining and Calling Functions

Functions are one of the most important building blocks in Python programming. They allow you to organize and reuse code efficiently. In Python, you define a function using the def keyword and call it by simply using its name followed by parentheses.

Defining a Function:

In Python, a function is defined using the following syntax:

def function_name(parameters):
    # Function body
    statement(s)
    return result
  • def: This keyword is used to define a function.
  • function_name: The name you give to your function. It should follow the same rules as variable names.
  • parameters: Optional inputs to the function. You can define one or more parameters, or none at all.
  • Function body: The code that runs when the function is called. It can contain any valid Python statements.
  • return: This is used to return a value from the function. The return statement is optional; if it is not provided, the function will return None by default.

Example 1: Simple Function Definition and Call

Let's define a simple function called greet that prints a greeting message when called.

# Function definition
def greet():
    print("Hello, welcome to Python programming!")

# Function call
greet()

Output:

Hello, welcome to Python programming!

In this example:

  • The function greet() does not take any parameters.
  • It simply prints a message when called.

Example 2: Function with Parameters

You can also define functions that take one or more parameters (arguments). These parameters allow you to pass data to the function when it is called.

# Function definition with parameters
def greet(name):
    print(f"Hello, {name}!")

# Function call with argument
greet("Alice")
greet("Bob")

Output:

Hello, Alice!
Hello, Bob!

In this example:

  • The function greet() accepts a parameter name and uses it to customize the greeting message.
  • When calling the function, we pass the actual values "Alice" and "Bob" to the function.

Example 3: Function with Return Value

A function can also return a value using the return keyword. The return value can be any type of data (string, integer, list, etc.).

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

# Function call with arguments
sum_result = add_numbers(5, 3)
print("The sum is:", sum_result)

Output:

The sum is: 8

In this example:

  • The function add_numbers(a, b) takes two parameters and returns their sum.
  • The result of the function call is stored in the variable sum_result, and we print the sum.

Function with Multiple Parameters:

You can pass multiple parameters to a function. These parameters can be used in various calculations or operations.

# Function definition with multiple parameters
def calculate_area(length, width):
    area = length * width
    return area

# Function call with multiple arguments
area = calculate_area(10, 5)
print("The area of the rectangle is:", area)

Output:

The area of the rectangle is: 50

Default Arguments:

Functions can also have default arguments. If the caller does not pass a value for a parameter with a default, the function will use the default value.

# Function with default argument
def greet(name="Guest"):
    print(f"Hello, {name}!")

# Function calls
greet("Alice")
greet()  # Uses the default value for name

Output:

Hello, Alice!
Hello, Guest!

In this example:

  • The parameter name has a default value of "Guest".
  • If no argument is passed when calling greet(), it will use "Guest" as the default value.

Keyword Arguments:

When calling a function, you can use keyword arguments to explicitly assign values to specific parameters. This makes the code more readable, especially when a function has multiple parameters.

# Function with keyword arguments
def display_info(name, age):
    print(f"Name: {name}, Age: {age}")

# Function call with keyword arguments
display_info(age=25, name="John")

Output:

Name: John, Age: 25

In this example:

  • We pass the values for name and age as keyword arguments.
  • The order of arguments doesn’t matter because we explicitly name the parameters.

Return Multiple Values:

A Python function can return multiple values as a tuple. This allows you to return more than one result from a function.

# Function returning multiple values
def get_user_info():
    name = "Alice"
    age = 30
    return name, age

# Function call
user_info = get_user_info()
print("Name:", user_info[0], "Age:", user_info[1])

Output:

Name: Alice Age: 30

In this example:

  • The function get_user_info() returns two values: name and age.
  • The returned values are stored as a tuple and accessed using indexing.

Summary:

  • Defining Functions: Functions are defined using the def keyword, followed by the function name, optional parameters, and the function body.
  • Calling Functions: You call a function by using its name and passing the required arguments.
  • Return Values: A function can return a value using the return keyword.
  • Parameters: Functions can take parameters to allow for more flexible behavior.
    • Default Parameters: Functions can have default values for parameters.
    • Keyword Arguments: Arguments can be passed by explicitly naming the parameter.
  • Multiple Return Values: Functions can return multiple values as a tuple.

By using functions, you can modularize your code, making it more reusable, maintainable, and easier to understand. Functions are a crucial part of writing efficient Python code.

Commenting is not enabled on this course.