Lesson 1 • Intermediate
Functions in Python
Learn to organize, reuse, and simplify your code with Python functions.
What You'll Learn in This Lesson
- ✓What a function is and why it's the #1 tool for code reuse
- ✓How to define functions with def and call them
- ✓How to pass data into functions using parameters
- ✓How to get results back from functions with return
- ✓Default parameters and keyword arguments
- ✓How to return multiple values at once
1. What Are Functions?
A function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, you write it once in a function and call it whenever you need it.
Why Use Functions?
- Reusability — Write once, use many times
- Organization — Break complex programs into smaller pieces
- Easier debugging — Fix bugs in one place, not everywhere
- Readability — Code is easier to understand
2. Defining a Function
Use the def keyword to create a function:
| Part | Meaning |
|---|---|
| def | Keyword that starts a function definition |
| function_name | The name you give your function (use snake_case) |
| () | Parentheses for parameters (empty if none) |
| : | Colon to start the function body |
| Indented code | The code that runs when you call the function |
Try It: Your First Function
Define a function and call it
# Define a simple function
def greet():
print("Hello, World!")
# Call the function
greet()
# You can call it multiple times
greet()
greet()greet()3. Parameters — Giving Functions Inputs
Parameters are variables listed inside the parentheses when defining a function. They allow you to pass information into the function.
• Parameter = the variable in the function definition (like a placeholder)
• Argument = the actual value you pass when calling the function
Try It: Parameters
Pass information into functions
# Function with one parameter
def greet(name):
print(f"Hello, {name}!")
# Call with different arguments
greet("Alice")
greet("Bob")
greet("Charlie")
# Function with multiple parameters
def introduce(name, age):
print(f"I'm {name} and I'm {age} years old.")
introduce("Alice", 25)
introduce("Bob", 30)4. Return Values — Getting Results Back
The return keyword sends a value back to the code that called the function. This lets you use the result!
def add(a, b):
print(a + b)
result = add(5, 3)
# Prints: 8
# result is None!def add(a, b):
return a + b
result = add(5, 3)
# result is 8
print(result * 2) # 16•
print() displays output but returns None•
return sends a value back that you can store and use laterTry It: Return Values
Get results back from functions
# Function that returns a value
def add(a, b):
return a + b
# Store the result
result = add(5, 3)
print(f"5 + 3 = {result}")
# Use the result in another calculation
doubled = result * 2
print(f"Doubled: {doubled}")
# Use directly in expressions
total = add(10, 20) + add(5, 5)
print(f"Total: {total}")5. Default Parameter Values
You can give parameters default values. If no argument is passed, the default is used:
Try It: Default Parameters
Make parameters optional with defaults
# Function with default parameter
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Uses default
greet("Alice") # Uses provided value
# Multiple defaults
def create_user(name, role="user", active=True):
print(f"Created: {name} ({role}), Active: {active}")
create_user("Alice")
create_user("Bob", "admin")
create_user("Charlie", "mod", False)def func(a, b="default") ✓def func(a="default", b) ✗ Error!6. Positional vs Keyword Arguments
When calling a function, you can pass arguments in two ways:
| Type | Example | Description |
|---|---|---|
| Positional | func("Alice", 25) | Arguments matched by position/order |
| Keyword | func(name="Alice", age=25) | Arguments matched by name (any order) |
Try It: Argument Types
Positional and keyword arguments
def describe_pet(animal, name):
print(f"I have a {animal} named {name}.")
# Positional arguments (order matters)
describe_pet("dog", "Rex")
describe_pet("cat", "Whiskers")
# Keyword arguments (order doesn't matter)
describe_pet(name="Buddy", animal="hamster")
describe_pet(animal="fish", name="Nemo")
# Mixing: positional first, then keyword
describe_pet("bird", name="Tweety")7. Returning Multiple Values
Python functions can return multiple values at once! They're returned as a tuple.
Try It: Multiple Returns
Return multiple values from a function
# Return multiple values
def calculate(a, b):
sum_val = a + b
diff = a - b
product = a * b
return sum_val, diff, product
# Unpack the results
s, d, p = calculate(10, 5)
print(f"Sum: {s}, Difference: {d}, Product: {p}")
# Or store as tuple
results = calculate(20, 3)
print(f"All results: {results}")
print(f"Just the sum: {results[0]}")8. Variable Scope — Local vs Global
Scope determines where a variable can be accessed:
| Scope | Where Defined | Where Accessible |
|---|---|---|
| Local | Inside a function | Only inside that function |
| Global | Outside all functions | Everywhere in the file |
Try It: Variable Scope
Understand local and global variables
# Global variable
message = "Hello from outside!"
def my_function():
# Local variable
local_msg = "Hello from inside!"
print(local_msg) # Works - local variable
print(message) # Works - can read global
my_function()
print(message) # Works - global variable
# print(local_msg) # ERROR - local_msg doesn't exist here!9. Docstrings — Documenting Your Functions
A docstring is a special string that describes what your function does. Put it right after the def line:
Try It: Docstrings
Document your functions properly
def calculate_area(width, height):
"""
Calculate the area of a rectangle.
Parameters:
width: The width of the rectangle
height: The height of the rectangle
Returns:
The area (width * height)
"""
return width * height
# Access the docstring
print(calculate_area.__doc__)
# Use help() to see it
help(calculate_area)10. Common Mistakes to Avoid
| Mistake | Wrong | Correct |
|---|---|---|
| Forgetting parentheses | greet | greet() |
| Forgetting colon | def greet() | def greet(): |
| Missing indentation | def greet(): print("Hi") | def greet(): print("Hi") |
| Using print instead of return | print(a + b) | return a + b |
| Wrong argument count | add(5) | add(5, 3) |
11. Practical Examples
Example 1: Temperature Converter
Temperature Converter
Convert between Celsius and Fahrenheit
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
# Test the functions
print(f"0°C = {celsius_to_fahrenheit(0)}°F")
print(f"100°C = {celsius_to_fahrenheit(100)}°F")
print(f"98.6°F = {fahrenheit_to_celsius(98.6):.1f}°C")Example 2: Grade Calculator
Grade Calculator
Convert numeric scores to letter grades
def calculate_grade(score):
"""Return letter grade based on score."""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
# Test with different scores
scores = [95, 82, 73, 65, 45]
for score in scores:
grade = calculate_grade(score)
print(f"Score: {score} → Grade: {grade}")Example 3: Simple Calculator
Simple Calculator
Basic arithmetic functions with error handling
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Cannot divide by zero"
return a / b
# Use the calculator functions
print(f"10 + 5 = {add(10, 5)}")
print(f"10 - 5 = {subtract(10, 5)}")
print(f"10 × 5 = {multiply(10, 5)}")
print(f"10 ÷ 5 = {divide(10, 5)}")
print(f"10 ÷ 0 = {divide(10, 0)}")Summary: Quick Reference
| Concept | Syntax | Example |
|---|---|---|
| Define function | def name(): | def greet(): |
| With parameter | def name(param): | def greet(name): |
| Return value | return value | return a + b |
| Default param | param="default" | def greet(name="Guest"): |
| Keyword arg | param=value | greet(name="Alice") |
| Multiple returns | return a, b | x, y = func() |
| Docstring | """text""" | """Calculate area.""" |
Lesson 6 done — you can now write reusable code like a pro!
Functions are the single most important concept in all of programming. You now know how to define them, pass data in, get results out, set defaults, and return multiple values.
🚀 Up next: Lists — learn to store and manage collections of data, the backbone of most real programs.
Sign up for free to track which lessons you've completed and get learning reminders.