Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Click here to view code image


>>> import sys
>>> sys.builtin_module_names
('__main__', '_ast', '_bisect', '_codecs', '_collections', '_datetime',
'_elementtree', '_functools', '_heapq', '_io', '_locale', '_pickle',
'_posixsubprocess', '_random', '_socket', '_sre', '_string', '_struct',
'_symtable', '_thread', '_warnings', '_weakref', 'array', 'atexit',
'binascii', 'builtins', 'errno', 'fcntl', 'gc', 'grp', 'imp', 'itertools',
'marshal', 'math', 'operator', 'posix', 'pwd', 'pyexpat', 'select', 'signal',
'spwd', 'sys', 'syslog', 'time', 'unicodedata', 'xxsubtype', 'zipimport',
'zlib')
>>>

Compare the os module and the math module, which have been used in previous hours. The os
module’s functions are Python statements stored in a .py file. The math module is written in the C
programming language and is linked with the Python interpreter. Even though they are different
flavors of modules, as shown in Listing 13.2, both must be imported before their functions can be
used.


LISTING 13.2 Importing Different-Flavored Modules


Click here to view code image


1: >>> math.factorial(5)
2: Traceback (most recent call last):
3: File "<stdin>", line 1, in <module>
4: NameError: name 'math' is not defined
5: >>> import math
6: >>> math.factorial(5)
7: 120
8: >>> os.getcwd()
9: Traceback (most recent call last):
10: File "<stdin>", line 1, in <module>
11: NameError: name 'os' is not defined
12: >>> import os
13: >>> os.getcwd()
14: '/home/pi'
15: >>>

This is the standard syntax for using functions within modules:


module.function

To understand this syntax, look at line 6 in Listing 13.2. You can see that the module is math, and the
function (sometimes called a method or an operation) is factorial.


Did You Know: A Group of Modules
You can also gather a collection of modules in Python. This is called a package.

Using and creating Python modules have some strong benefits. They include manageability and
reusability. The term module is derived from the theory of “modular programming.” A script broken

Free download pdf