Calling Functions

Basic Function Call

To call a function, you use the function’s name followed by parentheses. If the function requires arguments, you place them inside the parentheses.


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

# Calling the function
message = greet("Alice")
print(message)  # Output: Hello, Alice!

Function with Multiple Arguments

Functions can accept multiple arguments, which should be provided in the same order as defined.


def add(a, b):
    return a + b

# Calling the function
result = add(5, 3)
print(result)  # Output: 8

Keyword Arguments

Keyword arguments allow you to call a function with arguments in any order by specifying the parameter names.


def describe_pet(pet_name, animal_type='dog'):
    return f"I have a {animal_type} named {pet_name}."

# Calling the function with keyword arguments
description = describe_pet(animal_type='hamster', pet_name='Harry')
print(description)  # Output: I have a hamster named Harry.

Default Arguments

Default arguments provide default values for parameters, allowing the function to be called without explicitly providing those arguments.


def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# Calling the function with and without the default argument
print(greet("Alice"))  # Output: Hello, Alice!
print(greet("Bob", "Hi"))  # Output: Hi, Bob!

Variable-Length Arguments

Python allows functions to accept an arbitrary number of arguments using *args for non-keyword arguments and **kwargs for keyword arguments.

Example with *args

def summarize(*numbers):
    return sum(numbers)

# Calling the function with a variable number of arguments
print(summarize(1, 2, 3))  # Output: 6
print(summarize(4, 5))  # Output: 9

Example with **kwargs

def build_profile(**user_info):
    profile = {}
    for key, value in user_info.items():
        profile[key] = value
    return profile

# Calling the function with keyword arguments
user_profile = build_profile(first_name='John', last_name='Doe', age=30)
print(user_profile)  # Output: {'first_name': 'John', 'last_name': 'Doe', 'age': 30}