Back to Python

Python Functions

Introduction to Functions

Functions are reusable blocks of code that perform a specific task. They help organize code into manageable sections and promote code reuse.

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

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

Defining Functions

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

# Basic function definition
def function_name(parameters):
    """docstring""" # Optional documentation
    # function body
    return # optional return value

Parameters and Arguments

Functions can accept parameters (variables listed in the function definition) and arguments (values passed to the function when called).

# Function with parameters
def add_numbers(a, b):
    return a + b

# Calling with arguments
result = add_numbers(5, 3)
print(result) # Output: 8

# Default parameter values
def greet(name="Guest"):
    print(f"Hello, {name}")

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

Return Values

Functions can return values using the return statement. A function can return multiple values as a tuple.

# Function with return value
def square(number):
    return number ** 2

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

# Returning multiple values
def min_max(numbers):
    return min(numbers), max(numbers)

min_val, max_val = min_max([5, 2, 9, 1])
print(f"Min: {min_val}, Max: {max_val}") # Output: Min: 1, Max: 9

Variable Scope

Variables defined inside a function are local to that function. Global variables can be accessed but need the global keyword to be modified.

# Global vs local scope
global_var = "I'm global"

def scope_demo():
    local_var = "I'm local"
    print(global_var) # Access global variable
    print(local_var) # Access local variable

scope_demo()
print(global_var) # Works
# print(local_var) # Would cause an error

Lambda Functions

Lambda functions are small anonymous functions defined with the lambda keyword.

# Regular function
def square(x):
    return x * x

# Equivalent lambda function
square = lambda x: x * x

print(square(5)) # Output: 25

# Using lambda with built-in functions
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]

Python Function Videos

Master Python functions with these handpicked YouTube tutorials:

Basic Functions

Learn function fundamentals:

Parameters & Returns

Working with inputs and outputs:

Advanced Concepts

Deep dive into function techniques:

Practical Projects

Real-world function applications:

Python Functions Quiz