Python Training Course V
Modules, Packages and Programs
Standalone Programs
Modules and the import Statement
Packages
The Python Standard Library
More Batteries: Get Other Python Code
2
Standalone Programs
Save to [Link]
Save to [Link]
3
Modules and the import Statement
4
Import a Module A module is just a file
of Python code.
[Link]
[Link]
imported the choice() function
from the random module directly
5
Import a Module
what to import, but not where
to do the importing
You should consider importing
from outside the function if the
imported code might be used in
more than one place.
6
Import a Module with Another Name
You can import one or more
parts of a module. Each part
can keep its original name or
you can give it an alias.
7
Module Search Path
'' , which stands for the current directory
Python looks in the current directory
first when you try to import something
If you define a module named random and it’s in the
search path before the standard library, you won’t be
able to access the standard library’s random now.
8
Packages
9
Packages You’ll need one more thing in the
sources directory: a file named
__init__.py. This can be empty, but
Python needs it to treat the
directory containing it as a
package.
10
Function of enumerate
A new built-in function,
enumerate(), will make
certain loops a bit clearer.
enumerate(thing), where
thing is either an iterator
or a sequence, returns a
iterator that will return (0,
thing[0]), (1, thing[1]), (2,
thing[2]), and so forth.
The optional argument allows us
to tell enumerate from where to
start the index.
11
練習題
P.121 ~ 122 Things to Do 5.1 ~ 5.4
12
The Python Standard Library
13
Handle Missing Keys with setdefault()
如果不存在 key ‘Carbon’ 就加進
去
已存在 key ‘Helium’, 就維持原來的
value
14
Handle Missing Keys with defaultdict() (I)
defaultdict 的 argument 為
function ,
而 int() = 0
未來只要不存在的 key 其 value 就是
0
If you omit the argument, the initial
value of a new key will be set to None .
15
Handle Missing Keys with defaultdict() (II)
16
Count Items with Counter()
列出 top 1
17
Count Items with Counter()
18
The Python 3 Standard Library by Example
19
More Batteries: Get Other Python Code
PyPI Python Packages Index
[Link]
github
[Link]
readthedocs
[Link]
20
練習題
運用 standard library 中的 smtplib 寄一封
email 到自己的信箱
提示:請參考
The Python 3 Standard Library by Example 書
中的範例
or
官方網站
[Link]
21