You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Functions are reusable blocks of code that perform a specific task. They help you organise your code, avoid repetition, and make programs easier to read, test, and maintain. Functions are one of the most important concepts in programming.
Use the def keyword:
def greet(name):
"""Greet a person by name."""
print(f"Hello, {name}!")
# Call the function
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!
Anatomy of a function:
def — keyword to define a functiongreet — the function name(name) — parameter(s)""" docstring """ — optional documentationgreet("Alice")Functions can return values using the return statement:
def add(a, b):
"""Return the sum of a and b."""
return a + b
result = add(3, 5)
print(result) # 8
# Functions without return statement return None
def say_hello():
print("Hello!")
x = say_hello() # prints "Hello!"
print(x) # None
def get_stats(numbers):
"""Return the min, max, and average of a list."""
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = get_stats([4, 2, 9, 1, 7])
print(f"Min: {low}, Max: {high}, Avg: {avg:.1f}")
# Min: 1, Max: 9, Avg: 4.6
Arguments are matched by position:
def power(base, exponent):
return base ** exponent
print(power(2, 10)) # 1024
print(power(10, 2)) # 100 — order matters!
Specify arguments by name for clarity:
print(power(base=2, exponent=10)) # 1024
print(power(exponent=10, base=2)) # 1024 — order doesn't matter
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
Important: Default values are evaluated once when the function is defined, not each time it is called. Avoid using mutable defaults:
# BAD — the default list is shared across all calls
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b'] — not ['b']!
# GOOD — use None as default
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['b'] — correct!
*args — Variable Positional Argumentsdef total(*args):
"""Sum any number of arguments."""
print(f"Received: {args}") # args is a tuple
return sum(args)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 100
**kwargs — Variable Keyword Argumentsdef print_info(**kwargs):
"""Print key-value pairs."""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=20, city="London")
# name: Alice
# age: 20
# city: London
def example(a, b, *args, greeting="Hello", **kwargs):
print(f"a={a}, b={b}")
print(f"args={args}")
print(f"greeting={greeting}")
print(f"kwargs={kwargs}")
example(1, 2, 3, 4, greeting="Hi", x=10, y=20)
# a=1, b=2
# args=(3, 4)
# greeting=Hi
# kwargs={'x': 10, 'y': 20}
Variables created inside a function exist only within that function:
def my_function():
local_var = "I'm local"
print(local_var)
my_function() # I'm local
# print(local_var) # NameError: name 'local_var' is not defined
Variables created outside functions are accessible everywhere:
global_var = "I'm global"
def my_function():
print(global_var) # can READ global variables
my_function() # I'm global
global KeywordSubscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.