- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
2.19 Modules
A module is a logical way to physically organize and distinguish related pieces of Python code into individual files. A module can contain executable code, functions, classes, or any and all of the above.
When you create a Python source file, the name of the module is the same as the file except without the trailing .py extension. Once a module is created, you may import that module for use from another module using the import statement.
How to Import a Module
import module_name
How to Call a Module Function or Access a Module Variable
Once imported, a module’s attributes (functions and variables) can be accessed using the familiar dotted attribute notation:
module.function() module.variable
We will now present our Hello World! example again, but using the output functions inside the sys module.
>>> import sys >>> sys.stdout.write('Hello World!\n') Hello World! >>> sys.platform 'win32' >>> sys.version '2.4.2 (#67, Sep 28 2005, 10:51:12) [MSC v.1310 32 bit (Intel)]'
This code behaves just like our original Hello World! using the print statement. The only difference is that the standard output write() method is called, and the NEWLINE character needs to be stated explicitly because, unlike the print statement, write() does not do that for you.
You can find out more information on modules and importing in Chapter 12.
We will cover all of the above topics in much greater detail throughout the text, but hopefully we have provided enough of a “quick dip in the pool” to facilitate your needs if your primary goal is to get started working with Python as quickly as possible without too much serious reading.