Functions - CameronAuler/python-devops GitHub Wiki

Table of Contents

Function Definition & Calling

Functions are defined using the def keyword followed by the function name and parentheses.

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

greet()   # Call the function
# Output:
Hello, World!

Function Arguments

Python functions can accept various types of arguments including positional, keyword, default, and arbitrary arguments.

Note: Parameters are the variables listed in a function's definition. They act as placeholders for the values that the function will receive when it is called. Arguments are the actual values or variables passed to a function when it is invoked. In the following example, a, b are parameters, 3, 5 are arguments.

Positional Arguments

These are passed in the order they are defined.

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

print(add(3, 5))
# Output:
8

Keyword Arguments

Arguments are passed using the parameter name for clarity.

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

greet(name="Alice", message="Good Morning")
# Output:
Good Morning, Alice!

Default Arguments

Default values are provided for parameters that can be omitted when calling the function.

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

greet("Alice")
# Output:
Hello, Alice!

Arbitrary Arguments

Used when the number of arguments is unknown. These are captured as a tuple (*args) or a dictionary (**kwargs).

Tuple:

def print_items(*args):
    for item in args:
        print(item)

print_items("apple", "banana", "cherry")
# Output:
apple
banana
cherry

Dictionary:

def describe_person(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

describe_person(name="Alice", age=30, city="New York")
# Output:
name: Alice
age: 30
city: New York

Return Values

Functions can return values using the return keyword. Functions without a return statement implicitly return None.

def square(num):
    return num ** 2

result = square(4)
print(result)
# Output:
16

Lambda Function

A lambda function is an anonymous, one-line function defined using the lambda keyword.

Syntax:

lambda arguments: expression

Example:

square = lambda x: x ** 2
print(square(5))
# Output:
25

Using Lambda with map() and filter():

nums = [1, 2, 3, 4, 5]

# map() applies the lambda function to each element
squared = map(lambda x: x ** 2, nums)
print(list(squared))

# filter() filters elements based on the lambda function condition
even = filter(lambda x: x % 2 == 0, nums)
print(list(even))
# Output:
[1, 4, 9, 16, 25]
[2, 4]