Master Python Functions: From Basics to Advanced Module Usage
This tutorial walks you through Python functions—definition, calling, parameters, return values, nested calls, debugging with PyCharm, documentation strings, and how to organize and reuse code with modules and compiled bytecode—providing hands‑on examples and best‑practice tips for every step.
Quick Introduction to Functions
A function is an independent block of code packaged as a small module that can be invoked when needed, improving development efficiency and code reuse.
Basic Usage
Defining a function follows the format:
<code>def function_name():
# function body
...
</code>Key points:
def is short for define .
The function name should clearly express its purpose and follow identifier rules (letters, underscores, digits; cannot start with a digit or clash with keywords).
Calling a function is as simple as writing function_name() .
First Function Example
<code>name = "小明"
def say_hello():
print("hello 1")
print("hello 2")
print("hello 3")
print(name)
say_hello()
print(name)
</code>Note that a function does nothing until it is explicitly called; otherwise a NameError will be raised.
Parameters
Parameters make functions reusable for different data. Define them inside the parentheses and separate multiple parameters with commas.
<code>def sum_2_num(num1, num2):
result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
sum_2_num(50, 20)
</code>Formal parameters (the ones in the definition) receive the values passed as actual arguments during the call.
Return Values
Use return to send a result back to the caller. The caller can capture it with a variable.
<code>def sum_2_num(num1, num2):
"""Add two numbers"""
return num1 + num2
result = sum_2_num(10, 20)
print("计算结果是 %d" % result)
</code>After a return statement, no further code in the function is executed.
Nested Calls
A function can call another function, creating nested execution.
<code>def test1():
print("*" * 50)
print("test 1")
print("*" * 50)
def test2():
print("-" * 50)
print("test 2")
test1()
print("-" * 50)
test2()
</code>Practical Exercises
Various print_line functions demonstrate parameter usage and code reuse:
<code>def print_line(char):
print("*" * 50)
def print_line(char):
print(char * 50)
def print_line(char, times):
print(char * times)
def print_lines(char, times):
row = 0
while row < 5:
print_line(char, times)
row += 1
</code>Using Functions from Modules
Modules are Python files ( .py ) that can contain variables and functions. Import them with import and access their contents via module_name.attribute .
<code>name = "程序员"
import hm_10_分隔线模块
hm_10_分隔线模块.print_line("-", 80)
print(hm_10_分隔线模块.name)
</code>When a module is imported, Python may generate a compiled byte‑code file ( .pyc ) in a __pycache__ directory. This speeds up subsequent runs by skipping the compilation step if the source has not changed.
Debugging with PyCharm
F8 (Step Over) executes a line, treating a function call as a single step.
F7 (Step Into) dives into the function body to debug line by line.
Documentation Strings
Place a triple‑quoted string immediately after the function definition to describe its purpose. Press Ctrl+Q in PyCharm to view the docstring while calling the function.
Note: Keep two blank lines before a function definition to separate it from other code or comments.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.