beginner⏱30 minutesLesson 9 of 10
Functions and Scope
Create reusable code with functions: parameters, return values, scope, default arguments, and best practices
Functions and Scope
Functions are reusable blocks of code that perform a specific task. They help you organize code, avoid repetition, and build complex programs from simple pieces.
Defining and Calling Functions
python
def greet():
print("Hello, World!")
greet() # Call the functionParameters and Arguments
python
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # "Hello, Alice!"Multiple Parameters
python
def add(a, b):
result = a + b
return result
sum_result = add(5, 3) # 8The return Statement
Functions can return values (or None by default):
python
def square(x):
return x * x
result = square(4) # 16
# Multiple return values (as tuple)
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
q, r = divide(17, 5) # q=3, r=2Default Arguments
python
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # "Hello, Alice!"
print(greet("Bob", "Hi")) # "Hi, Bob!"Warning
Never use mutable default arguments (lists, dicts). They're created once and shared across calls!
python
def bad_append(item, list=[]): # Wrong!
list.append(item)
return list
def good_append(item, list=None): # Correct
if list is None:
list = []
list.append(item)
return listKeyword Arguments
python
def create_user(name, age, country):
return f"{name}, {age}, from {country}"
# Positional
user1 = create_user("Alice", 25, "USA")
# Keyword (order doesn't matter)
user2 = create_user(age=30, country="Canada", name="Bob")Variable Scope
Local Scope
python
def my_func():
x = 10 # Local variable
print(x)
my_func() # 10
print(x) # NameError! x is not definedGlobal Scope
python
x = 10 # Global variable
def my_func():
print(x) # Can read global
my_func() # 10Modifying Globals (Use Sparingly!)
python
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1Note
Type Hints (Documentation)
python
def add(a: int, b: int) -> int:
return a + b
def greet(name: str) -> str:
return f"Hello, {name}"
def process(items: list[str]) -> None:
for item in items:
print(item)Docstrings
Document what your function does:
python
def calculate_bmi(weight: float, height: float) -> float:
"""Calculate Body Mass Index.
Args:
weight: Weight in kilograms
height: Height in meters
Returns:
BMI value
"""
return weight / (height ** 2)Real-World Example: Data Processing Functions
python
def clean_text(text: str) -> str:
"""Remove punctuation and normalize whitespace."""
import string
for char in string.punctuation:
text = text.replace(char, "")
return " ".join(text.split())
def word_frequency(text: str) -> dict:
"""Count word frequency in text."""
words = clean_text(text).lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
def top_words(freq: dict, n: int = 5) -> list:
"""Return the n most common words."""
return sorted(freq.items(), key=lambda x: x[1], reverse=True)[:n]
# Usage
text = "Hello world! Hello everyone. Welcome to the world of Python."
freq = word_frequency(text)
print(top_words(freq))Success
Functions are the building blocks of maintainable code: they hide complexity, prevent repetition, and make your programs modular.
Practice Questions
- Write a function that takes two numbers and returns their product.
- What's the difference between
printandreturnin a function? - What happens if a function doesn't have a return statement?
- Why is
def func(x=[])problematic? - Write a function with type hints that converts Celsius to Fahrenheit.
- What's the scope of a variable defined inside a function?
- How do you return multiple values from a function?
- Write a recursive function that calculates factorial.
- What does
globaldo inside a function? - Write a docstring for a function that validates an email address.
Progress90%