Function Basics
So far, your code has been executing line by line. But what if you need to reuse the same functionality? Copy and paste every time? Functions solve this problem — package a block of code, give it a name, and call it whenever you need. This is the first step from "writing code" to "organizing code."
1. What is a Function
A function is a named block of code that you can call at any time.
# Define a function
def say_hello():
print("Hello!")
print("Welcome to Python!")
# Call the function
say_hello()
say_hello() # Can call it multiple times
Output:
Hello!
Welcome to Python!
Hello!
Welcome to Python!
Tip: Why use functions? 1. Avoid code repetition (DRY = Don't Repeat Yourself). 2. Code is easier to understand — a good function name is more useful than a large comment. 3. Modify in one place, all calls update automatically.
2. Parameters: Passing Data to Functions
Functions can accept parameters to make them more flexible:
def greet(name):
"""Greet a person by name"""
print(f"Hello, {name}! Welcome to Python.")
greet("Zhang San") # Hello, Zhang San! Welcome to Python.
greet("Li Si") # Hello, Li Si! Welcome to Python.
Multiple Parameters
def introduce(name, age, city):
print(f"My name is {name}, I'm {age} years old, from {city}.")
introduce("Zhang San", 25, "Beijing")
introduce("Li Si", 30, "Shanghai")
Parameter Order: Positional Arguments
When calling a function, arguments are matched by position:
def create_user(name, age, is_admin):
print(f"Creating user: {name}, Age: {age}, Admin: {is_admin}")
create_user("Zhang San", 25, False) # Matched by order
create_user(False, "Zhang San", 25) # Wrong order — mismatched!
Example: Calculator Functions (Difficulty: Star)
def add(a, b):
print(f"{a} + {b} = {a + b}")
def multiply(a, b):
print(f"{a} * {b} = {a * b}")
add(5, 3) # 5 + 3 = 8
multiply(5, 3) # 5 * 3 = 15
3. Return Values
Functions can use return to send a result back to the caller:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Return values can be used directly in expressions
total = add(10, 20) + add(30, 40)
print(total) # 100
Warning: If a function has no
return, it returnsNone. This is different from "no return value" — it does return something, justNone.
Multiple Return Values
Python can return multiple values at once (essentially returning a tuple):
def get_min_max(numbers):
return min(numbers), max(numbers)
result = get_min_max([3, 1, 4, 1, 5])
print(result) # (1, 5)
# Directly unpack the result
low, high = get_min_max([3, 1, 4, 1, 5])
print(f"Min: {low}, Max: {high}")
How return Works
return immediately ends the function's execution; code after it won't run:
def check_age(age):
if age < 0:
return "Age cannot be negative!" # Early return
if age < 18:
return "Minor"
return "Adult"
print(check_age(-5)) # Age cannot be negative!
print(check_age(15)) # Minor
print(check_age(25)) # Adult
Example: Temperature Conversion Tool (Difficulty: Star-Star)
def celsius_to_fahrenheit(c):
"""Convert Celsius to Fahrenheit"""
return c * 9 / 5 + 32
def fahrenheit_to_celsius(f):
"""Convert Fahrenheit to Celsius"""
return (f - 32) * 5 / 9
# Test
print(f"0°C = {celsius_to_fahrenheit(0):.1f}°F") # 32.0°F
print(f"100°C = {celsius_to_fahrenheit(100):.1f}°F") # 212.0°F
print(f"32°F = {fahrenheit_to_celsius(32):.1f}°C") # 0.0°C
print(f"212°F = {fahrenheit_to_celsius(212):.1f}°C") # 100.0°C
4. Docstrings
The comment on the first line after a function definition, written with """, is the docstring — it explains what the function does:
def calculate_bmi(weight, height):
"""
Calculate Body Mass Index (BMI)
Parameters:
weight (float): Body weight in kg
height (float): Body height in m
Returns:
float: BMI value
"""
return weight / (height ** 2)
# View the docstring
print(calculate_bmi.__doc__)
help(calculate_bmi)
Tip: Good habit: Write a docstring when you create a function, even if it's just one line. Without one: 1)
help(your_function)shows nothing; 2) Two months later, even you won't remember what the function does. The format isn't enforced, but it's recommended to include parameter descriptions and return value descriptions.
5. Function Call Stack
When a function calls another function, Python maintains a "call stack" in memory:
def a():
print("Entering a")
b()
print("Exiting a")
def b():
print("Entering b")
c()
print("Exiting b")
def c():
print("Entering c")
print("Exiting c")
a()
Output:
Entering a
Entering b
Entering c
Exiting c
Exiting b
Exiting a
Like a stack of plates — the last one placed is the first one taken. This "last in, first out" structure is called a stack. Deeply nested function calls can cause a "stack overflow" (e.g., recursion without a termination condition).
Common Use Cases
- Code reuse: Extract repeated logic into functions, define once and call from multiple places.
- Modular programming: Each function does one thing (single responsibility), making testing and maintenance easier.
- Calculation logic encapsulation: Encapsulate math formulas, data transformations, format validations, etc., into functions.
- Flow control: Use multi-return-value functions to handle multiple scenarios (errors, empty values, normal results).
FAQ
return and print()?return sends the result back to the caller; print() only displays output on the console. A function needs return to pass a value out. With print(), you can only see it — you can't use it.return statements?return statements, but only the first one encountered will execute — it immediately ends the function. This is common in conditional logic: different conditions return different values.def get_current_time(): needs no parameters and directly returns the current time (using the datetime module). The number of parameters depends on whether the function needs external data.Summary
- Functions are defined with
def, packaging code into reusable named blocks - Parameters make functions flexible; they are matched by position
returnsends back a result and ends the function; multiple return values are essentially a tuple- Functions without
returnreturnNone - Docstrings use
"""to describe functions; viewed withhelp() - The function call stack is a last-in-first-out structure; deep nesting can cause stack overflow
Exercises
-
Beginner (Difficulty: Star): Write a function
is_even(n)that takes an integer and returnsTrueif it's even,Falseotherwise. Use the%operator. -
Intermediate (Difficulty: Star-Star): Write a function
grade(score)that takes a score (0-100) and returns the corresponding letter grade: 90+ returns "A", 80-89 returns "B", 70-79 returns "C", 60-69 returns "D", below 60 returns "F". Use if-elif to implement. -
Advanced (Difficulty: Star-Star-Star): Write three functions
add(),subtract(),multiply(). Then write a fourth functioncalculate(a, b, operator)that takes two numbers and an operator string ("+", "-", "*"), calls the corresponding function, and returns the result. If the operator is not supported, returnNone.



