Master the art of writing reusable, modular code with Python functions
Functions are defined using the def keyword:
def greet():
"""This is a docstring - it describes what the function does."""
print("Hello, World!")
# Calling the function
greet() # Output: Hello, World!Variables listed in the function definition
def greet(name): # 'name' is a parameter
print(f"Hello, {name}!")Actual values passed when calling the function
greet("Alice") # 'Alice' is an argument
# Output: Hello, Alice!Functions can return values using the return statement:
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
result = add(5, 3)
print(result) # Output: 8Parameters can have default values:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Bob")) # Output: Hello, Bob!
print(greet("Bob", "Hi")) # Output: Hi, Bob!Document your functions with triple-quoted strings:
def calculate_area(radius):
"""
Calculate the area of a circle.
Args:
radius (float): The radius of the circle
Returns:
float: The area of the circle
"""
return 3.14159 * radius ** 2Create and test your own Python functions!
Your function will appear here...
x = 10 # Global variable
def outer_function():
y = 20 # Enclosing scope
def inner_function():
z = 30 # Local scope
print(f"x={x}, y={y}, z={z}")
inner_function()
outer_function()def factorial(n):
"""Calculate factorial recursively."""
if n <= 1: # Base case
return 1
return n * factorial(n - 1) # Recursive casedef greet(first, last):
return f"Hi {first} {last}"
print(greet("John", "Doe"))
# Output: Hi John Doedef greet(first, last):
return f"Hi {first} {last}"
print(greet(last="Doe", first="John"))
# Output: Hi John Doedef power(base, exp=2):
return base ** exp
print(power(3)) # 9
print(power(3, 3)) # 27def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5))
# Output: 15def print_info(**kwargs):
for key, val in kwargs.items():
print(f"{key}: {val}")
print_info(name="Alice", age=30)def func(pos, *args, key=0, **kwargs):
return (pos, args, key, kwargs)
print(func(1, 2, 3, key=4, x=5))
# (1, (2, 3), 4, {'x': 5})Short, one-line functions without a name:
# Regular function
def square(x):
return x ** 2
# Lambda equivalent
square = lambda x: x ** 2
print(square(5)) # Output: 25
# Common use with map, filter, sorted
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]Functions are objects - they can be assigned, passed as arguments, and returned:
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def apply_formatter(func, text):
"""Apply a formatting function to text."""
return func(text)
print(apply_formatter(shout, "hello")) # HELLO
print(apply_formatter(whisper, "HELLO")) # helloFunctions that remember values from their enclosing scope:
def make_multiplier(n):
"""Returns a function that multiplies by n."""
def multiplier(x):
return x * n
return multiplier
times_3 = make_multiplier(3)
times_5 = make_multiplier(5)
print(times_3(10)) # 30
print(times_5(10)) # 50Functions that modify other functions:
def uppercase_decorator(func):
def wrapper():
result = func()
return result.upper()
return wrapper
@uppercase_decorator
def greet():
return "hello"
print(greet()) # HELLOAnswer all questions and click "Submit Quiz" to see your score!