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.

PYTHON
# 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:

TEXT
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:

PYTHON
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

PYTHON
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:

PYTHON
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)

PYTHON
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
▶ Try it Yourself

3. Return Values

Functions can use return to send a result back to the caller:

PYTHON
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 returns None. This is different from "no return value" — it does return something, just None.

Multiple Return Values

Python can return multiple values at once (essentially returning a tuple):

PYTHON
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:

PYTHON
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)

PYTHON
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
▶ Try it Yourself

4. Docstrings

The comment on the first line after a function definition, written with """, is the docstring — it explains what the function does:

PYTHON
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:

PYTHON
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:

TEXT
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


FAQ

Q What's the difference between return and print()?
A 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.
Q Can a function have multiple return statements?
A Yes. A function can have multiple 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.
Q Must a function have parameters?
A No. Functions without parameters are perfectly valid. For example, 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


Exercises

  1. Beginner (Difficulty: Star): Write a function is_even(n) that takes an integer and returns True if it's even, False otherwise. Use the % operator.

  2. 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.

  3. Advanced (Difficulty: Star-Star-Star): Write three functions add(), subtract(), multiply(). Then write a fourth function calculate(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, return None.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏