Introduction to Python Programming: Modules – The “Toolbox” and “Building Blocks” of the Code World

1. Introduction: Why Do We Need “Modules”?

When you first start learning Python, you typically write a few lines of code in a single file, such as printing “Hello World” or performing simple mathematical calculations. This is akin to jotting down notes on a sticky note, quick and easy.

However, as you learn more and the functionalities you want to implement become more complex (for example, developing a snake game or writing a program to automatically scrape images from web pages), your code may balloon to hundreds or even thousands of lines.

What happens if you cram all these thousands of lines of code into a single file?

  1. 1. Difficult to Read: Like a lengthy document without paragraphs or chapters, finding a specific functionality becomes extremely challenging.
  2. 2. Difficult to Maintain: Modifying one variable might inadvertently break another unrelated functionality.
  3. 3. Redundant Work: If you have written a great “calculator” function and want to use it in another program, you can only “copy and paste” it over.

To address these issues, Python introduces the concept of modules.

Simple Definition: In Python, every Python code file ending with <span>.py</span> is essentially a module.

Core Function: Modules act like a “storage box” or “toolbox” for code. We categorize similar functionalities (functions, variables, classes) into different <span>.py</span> files and retrieve them when needed.

2. Three Main Sources of Modules

As a beginner, you need to know that modules mainly come from three sources, just like the three ways we acquire tools:

2.1 Built-in Modules (Standard Library) – “The Swiss Army Knife Included”

After installing Python, the official distribution has thoughtfully prepared hundreds of commonly used modules for you. You don’t need to download them; they are ready to use. This is known as the “Battery Included” philosophy.

  • Examples: <span>math</span> (mathematical tools), <span>random</span> (generate random numbers), <span>time</span> (time handling).

2.2 Third-Party Modules (Third-Party Packages) – “Professional Tools from Online Stores”

This is where Python shines. Developers worldwide have written thousands of modules available online (usually on the PyPI website). Whether you want to do data analysis, web development, or artificial intelligence, there are ready-made modules available.

  • Examples: <span>pandas</span> (Excel processing tool), <span>requests</span> (simulate web browsing).
  • Note: These modules typically need to be installed using the <span>pip install</span> command before use.

2.3 User-defined Modules – “Custom-made Specialized Tools”

These are the <span>.py</span> files you write yourself. When you split your code into multiple files, these files become modules that relate to each other through import statements.

3. Practical Guide: How to Use Modules?

In Python, the keyword for using modules is <span>import</span> (to import). This is like telling the Python interpreter: “I’m going to get that toolbox now”.

To demonstrate, let’s assume Python comes with a mathematical toolbox called <span>math</span>.

3.1 Basic Usage: Bringing in the Whole Toolbox

Syntax:<span>import module_name</span>

This is the safest method. It imports the entire module, and you need to prefix the module name when using its functionalities to avoid confusion.

# This is a demonstration code that you can copy and run directly

import math  # Import the math module

# Use the functionalities in the module, must use the format "module_name.function_name"
# Calculate the square root of 4
result = math.sqrt(4)
print("The square root of 4 is:", result)

# Get the value of pi
print("The value of pi is:", math.pi)
  • Principle Analysis: Imagine you have two people named “Xiao Ming” at home, one is your cousin and the other is a delivery person. To distinguish them, you must say “cousin.Xiao Ming” or “delivery.Xiao Ming”. Here, <span>math.</span> serves this purpose, preventing name conflicts.

3.2 Advanced Usage: Only Bring the Tools You Need

Syntax:<span>from module_name import function_name</span>

If you are sure you only need a hammer from the toolbox and don’t want to carry the whole heavy box, you can use this method.

from math import sqrt, pi  # Only import the sqrt function and pi variable

# Note: At this point, you don’t need to add the "math." prefix
print("The value of pi is:", pi)
print("The square root of 9 is:", sqrt(9))
  • Risk Warning: This method, while concise, can lead to issues if you have defined a variable named <span>pi</span> in your own code, as the later import will overwrite the earlier definition. For beginners, it is recommended to use the first method <span>import module_name</span>, as it may require more typing but is less error-prone.

3.3 Alias Usage: Give the Toolbox a Nickname

Syntax:<span>import module_name as alias</span>

Some module names are very long, or you may prefer a shorter name for convenience.

import math as m  # From now on, m represents math

print(m.sqrt(16))  # Equivalent to math.sqrt(16)

4. Hands-on Experiment: Write Your First Custom Module

Just watching without practicing is useless. We need to create two files and place them in the same folder.

  • • File 1:<span>my_tools.py</span> (This is our created module/toolbox)
  • • File 2:<span>main.py</span> (This is our main program/entry point)

Step 1: Create the Module (<span>my_tools.py</span>)

Please create a file named <span>my_tools.py</span> and write the following code:

# File name: my_tools.py

# Define a function to greet

def say_hello(name):
    return "Hello, " + name + "! Welcome to the world of Python."

# Define a function to add numbers

def add_numbers(a, b):
    return a + b

# Define a variable
version = "1.0.0"

Step 2: Call the Module (<span>main.py</span>)

Create a new file named <span>main.py</span> in the same directory and write the following code:

# File name: main.py

import my_tools  # Import the file we just wrote (note: do not add the .py suffix)

# 1. Use the variable from the module
print("Current tool version:", my_tools.version)

# 2. Use the function from the module
message = my_tools.say_hello("Zhang San")
print(message)

# 3. Perform a calculation
result = my_tools.add_numbers(10, 20)
print("Calculation result:", result)

Expected Output: When you run <span>main.py</span>, the console will output:

Current tool version: 1.0.0
Hello, Zhang San! Welcome to the world of Python.
Calculation result: 30

Congratulations! You have successfully modularized your code.

5. Key Difficulties Explained:<span>__name__ == "__main__"</span><span> What Does It Mean?</span>

When reading others’ Python code, you will almost certainly encounter this mysterious line of code:

if __name__ == '__main__':
    # Some code...

For absolute beginners, this is often the most confusing part. Let’s explain it using a simple **”script analogy”**.

5.1 Scene Setting

Imagine you wrote a module <span>movie.py</span> (the movie script). This script defines many actions (functions), such as “dance” and “sing”.

This script has two uses:

  1. 1. Direct Shooting (Run as Main Program): The director takes the script and starts shooting directly.
  2. 2. Being Referenced (Imported as a Module): The screenwriter writes another play <span>drama.py</span> and references the “dance” segment from <span>movie.py</span>.

5.2 Problem Arises

If you wrote a line of code in <span>movie.py</span> that says <span>start_dancing()</span>.

  • • When you run <span>movie.py</span> directly, the actor starts dancing, which is correct.
  • • When you <span>import movie</span> in <span>drama.py</span>, Python will read through the code in <span>movie.py</span> from start to finish. As a result, <span>drama.py</span> hasn’t even started yet, but the “dance” starts unexpectedly in the background.

This is usually not what we want. We hope that:only when the file is run directly should the test code execute; when imported by others, it should only provide functionality without running unexpectedly.

5.3 Solution

Python provides a built-in variable called <span>__name__</span> (note the double underscores).

  • • When the file is run directly, the value of <span>__name__</span> equals <span>"__main__"</span> (meaning “I am in the main stage”).
  • • When the file is imported, the value of <span>__name__</span> equals <span>"module's name"</span> (meaning “I am in the guest stage”).

5.4 Code Demonstration

Modify your <span>my_tools.py</span>:

# File name: my_tools.py

def say_hello(name):
    return "Hello, " + name

# --- New Part ---
# The following code will only execute when you right-click and run my_tools.py directly
# If main.py imports this, the following code will be automatically ignored
if __name__ == '__main__':
    print("I am the my_tools module, and I am performing self-testing...")
    print(say_hello("Tester"))
  • Try 1: Run <span>my_tools.py</span> directly.
    • • Result: It will print “I am the my_tools module…”.
  • Try 2: Run <span>main.py</span> (which imports my_tools).
    • • Result:It will NOT print those test statements, only execute the logic in <span>main.py</span>.

Conclusion: The purpose of this code is to serve as a “module testing switch”.

6. Module Search Path (Knowledge Expansion)

You may ask:“Why can I find <span>import math</span>, and also find <span>import my_tools</span>, but sometimes it can’t find a random file?”

Python finds modules like searching for items; it has a specific search order (sys.path):

  1. 1. Current Directory: First, it checks if there are any in the folder where the currently running program is located.
  2. 2. Environment Variables: It checks if there are any in the PYTHONPATH set in the system.
  3. 3. Standard Library Path: It checks the library files in the Python installation directory.
  4. 4. Third-Party Library Path: It checks the <span>site-packages</span><code><span> folder (where pip installs packages).</span>

Advice for Beginners: During the initial learning phase, please ensure that your main program (<span>main.py</span>) and your custom module (<span>my_tools.py</span>) are placed in the same folder so that they can always be found.

7. Summary and Recommendations

Core Knowledge Points Review

  1. 1. Modules are Files: Any <span>.py</span> file can be a module.
  2. 2. Import is the Key: Use <span>import</span> to access functionalities within a module.
  3. 3. Three Sources: Built-in (included), third-party (downloaded), user-defined (written by yourself).
  4. 4. Testing Protection: Use <span>if __name__ == '__main__':</span> to distinguish between being run or imported.

Advice for Absolute Beginners

  1. 1. Don’t Reinvent the Wheel: When faced with complex problems (like handling dates, random numbers, file operations), first search for “Does Python have a module for xxx?” There’s usually a standard library available.
  2. 2. Read the Official Documentation: The official Python documentation provides detailed descriptions of modules (though it can be a bit challenging, it’s worth reading slowly).
  3. 3. Keep Files Clear: When writing code, develop good habits; if you find a file exceeding 300 lines or containing too many unrelated functionalities, consider splitting it into new modules.

Python’s popularity is largely due to its rich and active module ecosystem. Mastering “modules” gives you the ability to command a vast array of functionalities, no longer fighting alone!

Leave a Comment