Source: Luuk Wouters on Unsplash
Functions are defined using the def
keyword, followed by the function name, parentheses ()
for parameters, and a colon :
. To execute a function, you call it by its name followed by parentheses. The pass
keyword is used as a placeholder when you define a function without any code yet.
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
def do_nothing():
pass # Placeholder. Will not cause an error.
Functions can return values using the return
keyword. The returned value can then be used in other parts of your code.
def add(x, y):
"""This function returns the sum of two numbers."""
sum_result = x + y
return sum_result
result = add(5, 3)
print(f"The sum is: {result}") # Output: The sum is: 8
Functions can accept arguments (inputs) to perform operations on. Arguments can be positional (based on order), keyword (specified by name), or have default values.
def describe_pet(animal_type, pet_name):
"""Describes a pet."""
print(f"I have a {animal_type} named {pet_name}.")
describe_pet("hamster", "Harry") # Positional arguments
describe_pet(animal_type="dog", pet_name="Rover") # Keyword arguments
describe_pet(pet_name="Whiskers", animal_type="cat") # Keyword arguments out of order
def power(base, exponent=2):
"""This function returns the base raised to the power of the exponent.
The exponent has a default value of 2.
"""
return base ** exponent
print(power(4)) # Output: 16 (exponent is 2 by default)
print(power(4, 3)) # Output: 64 (exponent is explicitly set to 3)
The *args
syntax allows a function to accept any number of positional arguments. These arguments are packed into a tuple named args
inside the function.
def print_all_args(*args):
"""This function prints all the positional arguments passed to it."""
for arg in args:
print(arg)
print_all_args("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry
def sum_all_args(*numbers):
"""This function returns the sum of all positional arguments."""
total = 0
for num in numbers:
total += num
return total
print(sum_all_args(1, 2, 3, 4, 5)) # Output: 15
The **kwargs
syntax allows a function to accept any number of keyword arguments. These arguments are packed into a dictionary named kwargs
inside the function.
def print_keyword_args(**kwargs):
"""This function prints all the keyword arguments passed to it."""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_keyword_args(name="Bob", age=30, city="New York")
# Output:
# name: Bob
# age: 30
# city: New York
def create_profile(**info):
"""This function creates a profile dictionary from keyword arguments."""
return info
profile = create_profile(occupation="Engineer", hobbies=["reading", "hiking"])
print(profile) # Output: {'occupation': 'Engineer', 'hobbies': ['reading', 'hiking']}
You can use both *args
and **kwargs
in the same function definition to handle both positional and keyword arguments.
def print_both(*args, **kwargs):
"""This function prints both positional and keyword arguments."""
print("Positional arguments (*args):")
for arg in args:
print(arg)
print("
Keyword arguments (**kwargs):")
for key, value in kwargs.items():
print(f"{key}: {value}")
print_both(1, 2, "three", name="Charlie", country="USA")
# Output:
# Positional arguments (*args):
# 1
# 2
# three
#
# Keyword arguments (**kwargs):
# name: Charlie
# country: USA