SlideShare a Scribd company logo
1 of 78
Download to read offline
Python 
Libraries 
Copyright © Software Carpentry 2010 
This work is licensed under the Creative Commons Attribution License 
See http://software-carpentry.org/license.html for more information.
A function is a way to turn a bunch of related 
statements into a single "chunk" 
Python Libraries
A function is a way to turn a bunch of related 
statements into a single "chunk" 
–– AAvvooiidd dduupplliiccaattiioonn 
Python Libraries
A function is a way to turn a bunch of related 
statements into a single "chunk" 
–– AAvvooiidd dduupplliiccaattiioonn 
– Make code easier to read 
Python Libraries
A function is a way to turn a bunch of related 
statements into a single "chunk" 
–– AAvvooiidd dduupplliiccaattiioonn 
– Make code easier to read 
A library does the same thing for related functions 
Python Libraries
A function is a way to turn a bunch of related 
statements into a single "chunk" 
–– AAvvooiidd dduupplliiccaattiioonn 
– Make code easier to read 
A library does the same thing for related functions 
Hierarchical organization 
Python Libraries
A function is a way to turn a bunch of related 
statements into a single "chunk" 
–– AAvvooiidd dduupplliiccaattiioonn 
– Make code easier to read 
A library does the same thing for related functions 
Hierarchical organization 
family library 
genus function 
species statement 
Python Libraries
Every Python file can be used as a library 
Python Libraries
Every Python file can be used as a library 
Use import to load it 
Python Libraries
Every Python file can be used as a library 
Use import to load it 
# halman.py 
ddddeeeeffff threshold(signal): 
rrrreeeettttuuuurrrrnnnn 1.0 / sum(signal) 
Python Libraries
Every Python file can be used as a library 
Use import to load it 
# halman.py 
ddddeeeeffff threshold(signal): 
rrrreeeettttuuuurrrrnnnn 1.0 / sum(signal) 
# program.py 
iiiimmmmppppoooorrrrtttt halman 
readings = [0.1, 0.4, 0.2] 
pppprrrriiiinnnntttt 'signal threshold is', halman.threshold(readings) 
Python Libraries
Every Python file can be used as a library 
Use import to load it 
# halman.py 
ddddeeeeffff threshold(signal): 
rrrreeeettttuuuurrrrnnnn 1.0 / sum(signal) 
# program.py 
iiiimmmmppppoooorrrrtttt halman 
readings = [0.1, 0.4, 0.2] 
pppprrrriiiinnnntttt 'signal threshold is', halman.threshold(readings) 
$ python program.py 
signal threshold is 1.42857 
Python Libraries
When a module is imported, Python: 
Python Libraries
When a module is imported, Python: 
1. Executes the statements it contains 
Python Libraries
When a module is imported, Python: 
1. Executes the statements it contains 
2. Creates an object that stores rreeffeerreenncceess ttoo 
the top-level items in that module 
Python Libraries
When a module is imported, Python: 
1. Executes the statements it contains 
2. Creates an object that stores rreeffeerreenncceess ttoo 
the top-level items in that module 
# noisy.py 
pppprrrriiiinnnntttt 'is this module being loaded?' 
NOISE_LEVEL = 1./3. 
Python Libraries
When a module is imported, Python: 
1. Executes the statements it contains 
2. Creates an object that stores rreeffeerreenncceess ttoo 
the top-level items in that module 
# noisy.py 
pppprrrriiiinnnntttt 'is this module being loaded?' 
NOISE_LEVEL = 1./3. 
>>>>>>>>>>>> import noisy 
is this module being loaded? 
Python Libraries
When a module is imported, Python: 
1. Executes the statements it contains 
2. Creates an object that stores rreeffeerreenncceess ttoo 
the top-level items in that module 
# noisy.py 
pppprrrriiiinnnntttt 'is this module being loaded?' 
NOISE_LEVEL = 1./3. 
>>>>>>>>>>>> import noisy 
is this module being loaded? 
>>>>>>>>>>>> print noisy.NOISE_LEVEL 
0.33333333 
Python Libraries
Each module is a namespace 
Python Libraries
Each module is a namespace 
function 
Python Libraries
Each module is a namespace 
mmoodduullee 
function 
Python Libraries
Each module is a namespace 
global 
mmoodduullee 
function 
Python Libraries
Each module is a namespace 
global 
module 
# module.py 
NAME = 'Transylvania' 
ddddeeeeffff func(arg): 
function 
rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg 
Python Libraries
Each module is a namespace 
global 
module 
# module.py 
NAME = 'Transylvania' 
ddddeeeeffff func(arg): 
function 
>>>>>>>>>>>> NAME = 'Hamunaptra' 
rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg 
Python Libraries
Each module is a namespace 
global 
module 
# module.py 
NAME = 'Transylvania' 
ddddeeeeffff func(arg): 
function 
>>>>>>>>>>>> NAME = 'Hamunaptra' 
>>>>>>>>>>>> import module 
rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg 
Python Libraries
Each module is a namespace 
global 
module 
# module.py 
NAME = 'Transylvania' 
ddddeeeeffff func(arg): 
function 
>>>>>>>>>>>> NAME = 'Hamunaptra' 
>>>>>>>>>>>> import module 
>>>>>>>>>>>> print module.func('!!!') 
Transylvania !!! 
rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg 
Python Libraries
Python comes with many standard libraries 
Python Libraries
Python comes with many standard libraries 
>>> import math 
Python Libraries
Python comes with many standard libraries 
>>> import math 
>>>>>>>>>>>> pppprrrriiiinnnntttt math.sqrt(2) 
1.4142135623730951 
Python Libraries
Python comes with many standard libraries 
>>> import math 
>>>>>>>>>>>> pppprrrriiiinnnntttt math.sqrt(2) 
1.4142135623730951 
>>>>>>>>>>>> pppprrrriiiinnnntttt math.hypot(2, 3) # sqrt(x**2 + y**2) 
3.6055512754639891 
Python Libraries
Python comes with many standard libraries 
>>> import math 
>>>>>>>>>>>> pppprrrriiiinnnntttt math.sqrt(2) 
1.4142135623730951 
>>>>>>>>>>>> pppprrrriiiinnnntttt math.hypot(2, 3) # sqrt(x**2 + y**2) 
3.6055512754639891 
>>>>>>>>>>>> pppprrrriiiinnnntttt math.e, math.pi # as accurate as possible 
2.7182818284590451 3.1415926535897931 
Python Libraries
Python also provides a help function 
Python Libraries
Python also provides a help function 
>>>>>>>>>>>> iiiimmmmppppoooorrrrtttt math 
>>>>>>>>>>>> help(math) 
HHeellpp oonn mmoodduullee mmaatthh:: 
NAME 
math 
FILE 
/usr/lib/python2.5/lib-dynload/math.so 
MODULE DOCS 
http://www.python.org/doc/current/lib/module-math.html 
DESCRIPTION 
This module is always available. It provides access to the 
mathematical functions defined by the C standard. 
FUNCTIONS 
acos(...) 
acos(x) 
Return the arc cosine (measured in radians) of x. 
⋮ 
Python Libraries
And some nicer ways to do imports 
Python Libraries
And some nicer ways to do imports 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt 
>>>>>>>>>>>> sqrt(3) 
1.7320508075688772 
Python Libraries
And some nicer ways to do imports 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt 
>>>>>>>>>>>> sqrt(3) 
1.7320508075688772 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid 
>>>>>>>>>>>> euclid(3, 4) 
5.0 
Python Libraries
And some nicer ways to do imports 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt 
>>>>>>>>>>>> sqrt(3) 
1.7320508075688772 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid 
>>>>>>>>>>>> euclid(3, 4) 
5.0 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt * 
>>>>>>>>>>>> sin(pi) 
1.2246063538223773e-16 
>>>>>>>>>>>> 
Python Libraries
And some nicer ways to do imports 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt 
>>>>>>>>>>>> sqrt(3) 
1.7320508075688772 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid 
>>>>>>>>>>>> euclid(3, 4) 
5.0 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt * 
>>>>>>>>>>>> sin(pi) 
1.2246063538223773e-16 
>>>>>>>>>>>> 
Generally a bad idea 
Python Libraries
And some nicer ways to do imports 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt 
>>>>>>>>>>>> sqrt(3) 
1.7320508075688772 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid 
>>>>>>>>>>>> euclid(3, 4) 
5.0 
>>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt * 
>>>>>>>>>>>> sin(pi) 
1.2246063538223773e-16 
>>>>>>>>>>>> 
Generally a bad idea 
Someone could add to 
the library after you 
start using it 
Python Libraries
Almost every program uses the sys library 
Python Libraries
Almost every program uses the sys library 
>>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys 
Python Libraries
Almost every program uses the sys library 
>>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 
2.7 (r27:82525, Jul 4 2010, 09:01:59) 
[MSC v.1500 32 bit (Intel)] 
Python Libraries
Almost every program uses the sys library 
>>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 
2.7 (r27:82525, Jul 4 2010, 09:01:59) 
[MSC v.1500 32 bit (Intel)] 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.platform 
win32 
Python Libraries
Almost every program uses the sys library 
>>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 
2.7 (r27:82525, Jul 4 2010, 09:01:59) 
[MSC v.1500 32 bit (Intel)] 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.platform 
win32 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.maxint 
2147483647 
Python Libraries
Almost every program uses the sys library 
>>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 
2.7 (r27:82525, Jul 4 2010, 09:01:59) 
[MSC v.1500 32 bit (Intel)] 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.platform 
win32 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.maxint 
2147483647 
>>>>>>>>>>>> pppprrrriiiinnnntttt sys.path 
['', 
'C:WINDOWSsystem32python27.zip', 
'C:Python27DLLs', 'C:Python27lib', 
'C:Python27libplat-win', 
'C:Python27', 'C:Python27libsite-packages'] 
Python Libraries
sys.argv holds command-line arguments 
Python Libraries
sys.argv holds command-line arguments 
Script name is sys.argv[0] 
Python Libraries
sys.argv holds command-line arguments 
Script name is sys.argv[0] 
# echo.py 
iiiimmmmppppoooorrrrtttt sys 
ffffoooorrrr i iiiinnnn range(len(sys.argv)): 
pppprrrriiiinnnntttt i, '"' + sys.argv[i] + '"' 
Python Libraries
sys.argv holds command-line arguments 
Script name is sys.argv[0] 
# echo.py 
iiiimmmmppppoooorrrrtttt sys 
ffffoooorrrr i iiiinnnn range(len(sys.argv)): 
pppprrrriiiinnnntttt i, '"' + sys.argv[i] + '"' 
$$$$ python echo.py 
0 echo.py 
$ 
Python Libraries
sys.argv holds command-line arguments 
Script name is sys.argv[0] 
# echo.py 
iiiimmmmppppoooorrrrtttt sys 
ffffoooorrrr i iiiinnnn range(len(sys.argv)): 
pppprrrriiiinnnntttt i, '"' + sys.argv[i] + '"' 
$$$$ python echo.py 
0 echo.py 
$ python echo.py first second 
0 echo.py 
1 first 
2 second 
$ 
Python Libraries
sys.stdin is standard input (e.g., the keyboard) 
Python Libraries
sys.stdin is standard input (e.g., the keyboard) 
sys.stdout is standard output (e.g., the screen) 
Python Libraries
sys.stdin is standard input (e.g., the keyboard) 
sys.stdout is standard output (e.g., the screen) 
sys.stderr is standard error (usually aallssoo tthhee ssccrreeeenn)) 
Python Libraries
sys.stdin is standard input (e.g., the keyboard) 
sys.stdout is standard output (e.g., the screen) 
sys.stderr is standard error (usually aallssoo tthhee ssccrreeeenn)) 
See the Unix shell lecture for more information 
Python Libraries
# count.py 
iiiimmmmppppoooorrrrtttt sys 
iiiiffff len(sys.argv) == 1: 
count_lines(sys.stdin) 
eeeeeeeellllllllsssssssseeeeeeee:::::::: 
rd = open(sys.argv[1], 'r') 
count_lines(rd) 
rd.close() 
Python Libraries
# count.py 
iiiimmmmppppoooorrrrtttt sys 
iiiiffff len(sys.argv) == 1: 
count_lines(sys.stdin) 
eeeeeeeellllllllsssssssseeeeeeee:::::::: 
rd = open(sys.argv[1], 'r') 
count_lines(rd) 
rd.close() 
Python Libraries
# count.py 
iiiimmmmppppoooorrrrtttt sys 
iiiiffff len(sys.argv) == 1: 
count_lines(sys.stdin) 
eeeeeeeellllllllsssssssseeeeeeee:::::::: 
rd = open(sys.argv[1], 'r') 
count_lines(rd) 
rd.close() 
Python Libraries
# count.py 
iiiimmmmppppoooorrrrtttt sys 
iiiiffff len(sys.argv) == 1: 
count_lines(sys.stdin) 
eeeeeeeellllllllsssssssseeeeeeee:::::::: 
rd = open(sys.argv[1], 'r') 
count_lines(rd) 
rd.close() 
$ python count.py < a.txt 
48 
$ 
Python Libraries
# count.py 
iiiimmmmppppoooorrrrtttt sys 
iiiiffff len(sys.argv) == 1: 
count_lines(sys.stdin) 
eeeeeeeellllllllsssssssseeeeeeee:::::::: 
rd = open(sys.argv[1], 'r') 
count_lines(rd) 
rd.close() 
$ python count.py < a.txt 
48 
$ python count.py b.txt 
227 
$ 
Python Libraries
The more polite way 
'''Count lines in files. If no filename arguments given, 
read from standard input.''' 
iiiimmmmppppoooorrrrtttt sys 
ddddeeeeffff count_lines(reader): 
'''Return number of lines in text read from reader.''' 
rrrreeeettttuuuurrrrnnnn len(reader.readlines()) 
iiiiffff __name__ == '__main__': 
...as before... 
Python Libraries
The more polite way 
'''Count lines in files. If no filename arguments given, 
read from standard input.''' 
iiiimmmmppppoooorrrrtttt sys 
ddddeeeeffff count_lines(reader): 
'''Return number of lines in text read from reader.''' 
rrrreeeettttuuuurrrrnnnn len(reader.readlines()) 
iiiiffff __name__ == '__main__': 
...as before... 
Python Libraries
The more polite way 
'''Count lines in files. If no filename arguments given, 
read from standard input.''' 
iiiimmmmppppoooorrrrtttt sys 
ddddeeeeffff count_lines(reader): 
'''Return number of lines in text read from reader.''' 
rrrreeeettttuuuurrrrnnnn len(reader.readlines()) 
iiiiffff __name__ == '__main__': 
...as before... 
Python Libraries
If the first statement in a module or function is 
a string, it is saved as a docstring 
Python Libraries
If the first statement in a module or function is 
a string, it is saved as a docstring 
Used for online ((aanndd oofffflliinnee)) hheellpp 
Python Libraries
If the first statement in a module or function is 
a string, it is saved as a docstring 
Used for online ((aanndd oofffflliinnee)) hheellpp 
# adder.py 
'''Addition utilities.''' 
ddddeeeeffff add(a, b): 
'''Add arguments.''' 
rrrreeeettttuuuurrrrnnnn a+b 
Python Libraries
If the first statement in a module or function is 
a string, it is saved as a docstring 
Used for online ((aanndd oofffflliinnee)) hheellpp 
# adder.py 
'''Addition utilities.''' 
ddddeeeeffff add(a, b): 
'''Add arguments.''' 
rrrreeeettttuuuurrrrnnnn a+b 
>>>>>>>>>>>> import adder 
>>>>>>>>>>>> help(adder) 
NAME 
adder - Addition utilities. 
FUNCTIONS 
add(a, b) 
Add arguments. 
>>>>>>>>>>>> 
Python Libraries
If the first statement in a module or function is 
a string, it is saved as a docstring 
Used for online ((aanndd oofffflliinnee)) hheellpp 
# adder.py 
'''Addition utilities.''' 
ddddeeeeffff add(a, b): 
'''Add arguments.''' 
rrrreeeettttuuuurrrrnnnn a+b 
>>>>>>>>>>>> import adder 
>>>>>>>>>>>> help(adder) 
NAME 
adder - Addition utilities. 
FUNCTIONS 
add(a, b) 
Add arguments. 
>>>>>>>>>>>> help(adder.add) 
add(a, b) 
Add arguments. 
>>>>>>>>>>>> 
Python Libraries
When Python loads a module, it assigns a value 
to the module-level variable __name__ 
Python Libraries
When Python loads a module, it assigns a value 
to the module-level variable __name__ 
main program 
'__main__' 
Python Libraries
When Python loads a module, it assigns a value 
to the module-level variable __name__ 
main program loaded as library 
'__main__' module name 
Python Libraries
When Python loads a module, it assigns a value 
to the module-level variable __name__ 
main program loaded as library 
'__main__' module name 
...module definitions... 
iiiiffff __name__ == '__main__': 
...run as main program... 
Python Libraries
When Python loads a module, it assigns a value 
to the module-level variable __name__ 
main program loaded as library 
'__main__' module name 
...module definitions... Always executed 
iiiiffff __name__ == '__main__': 
...run as main program... 
Python Libraries
When Python loads a module, it assigns a value 
to the module-level variable __name__ 
main program loaded as library 
'__main__' module name 
...module definitions... Always executed 
iiiiffff __name__ == '__main__': 
...run as main program... Only executed when 
file run directly 
Python Libraries
# stats.py 
'''Useful statistical tools.''' 
ddddeeeeffff average(values): 
'''Return average of values or None if no data.''' 
iiiiffff values: 
rrrreeeettttuuuurrrrnnnn sum(values) / len(values) 
eeeellllsssseeee:::: 
rrrreeeettttuuuurrrrnnnn NNNNoooonnnneeee 
iiiiffff __name__ == '__main__': 
pppprrrriiiinnnntttt 'test 1 should be None:', average([]) 
pppprrrriiiinnnntttt 'test 2 should be 1:', average([1]) 
pppprrrriiiinnnntttt 'test 3 should be 2:', average([1, 2, 3]) 
Python Libraries
# test-stats.py 
ffffrrrroooommmm stats iiiimmmmppppoooorrrrtttt average 
pppprrrriiiinnnntttt 'test 4 should be None:', average(set()) 
pppprrrriiiinnnntttt 'test 5 should be -1:', average({0, -1, -2}) 
Python Libraries
# test-stats.py 
ffffrrrroooommmm stats iiiimmmmppppoooorrrrtttt average 
pppprrrriiiinnnntttt 'test 4 should be None:', average(set()) 
pppprrrriiiinnnntttt 'test 5 should be -1:', average({0, -1, -2}) 
$ python stats.py 
test 1 should be None: None 
test 2 should be 1: 1 
test 3 should be 2: 2 
$ 
Python Libraries
# test-stats.py 
ffffrrrroooommmm stats iiiimmmmppppoooorrrrtttt average 
pppprrrriiiinnnntttt 'test 4 should be None:', average(set()) 
pppprrrriiiinnnntttt 'test 5 should be -1:', average({0, -1, -2}) 
$ python stats.py 
test 1 should be None: None 
test 2 should be 1: 1 
test 3 should be 2: 2 
$ python test-stats.py 
test 4 should be None: None 
test 5 should be -1: -1 
$ 
Python Libraries
created by 
Greg Wilson 
October 2010 
Copyright © Software Carpentry 2010 
This work is licensed under the Creative Commons Attribution License 
See http://software-carpentry.org/license.html for more information.

More Related Content

What's hot

Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administrationvceder
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginnersKálmán "KAMI" Szalai
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
Argparse: Python command line parser
Argparse: Python command line parserArgparse: Python command line parser
Argparse: Python command line parserTimo Stollenwerk
 
Python 3000
Python 3000Python 3000
Python 3000Bob Chao
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for PythonTimo Stollenwerk
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basicsLuigi De Russis
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekinge2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekingeProf. Wim Van Criekinge
 
What Shazam doesn't want you to know
What Shazam doesn't want you to knowWhat Shazam doesn't want you to know
What Shazam doesn't want you to knowRoy van Rijn
 
Sequences: Strings, Lists, and Files
Sequences: Strings, Lists, and FilesSequences: Strings, Lists, and Files
Sequences: Strings, Lists, and FilesEdwin Flórez Gómez
 
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RRModule Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RRSasmitoh Rahmad Riady
 

What's hot (20)

Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
 
Python- strings
Python- stringsPython- strings
Python- strings
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Argparse: Python command line parser
Argparse: Python command line parserArgparse: Python command line parser
Argparse: Python command line parser
 
Python 3000
Python 3000Python 3000
Python 3000
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for Python
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basics
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekinge2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekinge
 
What Shazam doesn't want you to know
What Shazam doesn't want you to knowWhat Shazam doesn't want you to know
What Shazam doesn't want you to know
 
Python 101
Python 101Python 101
Python 101
 
Sequences: Strings, Lists, and Files
Sequences: Strings, Lists, and FilesSequences: Strings, Lists, and Files
Sequences: Strings, Lists, and Files
 
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RRModule Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
Module Workshop NSC "Raspberry pi3 with Python" - Sanusi & Sasmitoh RR
 

Similar to Libraries

Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptRedenOriola
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for BioinformaticsJosé Héctor Gálvez
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txvishwanathgoudapatil1
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxsushil155005
 
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and ModulesRaginiJain21
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3Nick Efford
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With SpoonGérard Paligot
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Edureka!
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdfgmadhu8
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptxLecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptxAbdulQadeerBilal
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxRameshMishra84
 

Similar to Libraries (20)

Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .ppt
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Python1
Python1Python1
Python1
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
 
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With Spoon
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
Wait, IPython can do that?
Wait, IPython can do that?Wait, IPython can do that?
Wait, IPython can do that?
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
 
Python
PythonPython
Python
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptxLecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docx
 
Python arch wiki
Python   arch wikiPython   arch wiki
Python arch wiki
 

Recently uploaded

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Libraries

  • 1. Python Libraries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information.
  • 2. A function is a way to turn a bunch of related statements into a single "chunk" Python Libraries
  • 3. A function is a way to turn a bunch of related statements into a single "chunk" –– AAvvooiidd dduupplliiccaattiioonn Python Libraries
  • 4. A function is a way to turn a bunch of related statements into a single "chunk" –– AAvvooiidd dduupplliiccaattiioonn – Make code easier to read Python Libraries
  • 5. A function is a way to turn a bunch of related statements into a single "chunk" –– AAvvooiidd dduupplliiccaattiioonn – Make code easier to read A library does the same thing for related functions Python Libraries
  • 6. A function is a way to turn a bunch of related statements into a single "chunk" –– AAvvooiidd dduupplliiccaattiioonn – Make code easier to read A library does the same thing for related functions Hierarchical organization Python Libraries
  • 7. A function is a way to turn a bunch of related statements into a single "chunk" –– AAvvooiidd dduupplliiccaattiioonn – Make code easier to read A library does the same thing for related functions Hierarchical organization family library genus function species statement Python Libraries
  • 8. Every Python file can be used as a library Python Libraries
  • 9. Every Python file can be used as a library Use import to load it Python Libraries
  • 10. Every Python file can be used as a library Use import to load it # halman.py ddddeeeeffff threshold(signal): rrrreeeettttuuuurrrrnnnn 1.0 / sum(signal) Python Libraries
  • 11. Every Python file can be used as a library Use import to load it # halman.py ddddeeeeffff threshold(signal): rrrreeeettttuuuurrrrnnnn 1.0 / sum(signal) # program.py iiiimmmmppppoooorrrrtttt halman readings = [0.1, 0.4, 0.2] pppprrrriiiinnnntttt 'signal threshold is', halman.threshold(readings) Python Libraries
  • 12. Every Python file can be used as a library Use import to load it # halman.py ddddeeeeffff threshold(signal): rrrreeeettttuuuurrrrnnnn 1.0 / sum(signal) # program.py iiiimmmmppppoooorrrrtttt halman readings = [0.1, 0.4, 0.2] pppprrrriiiinnnntttt 'signal threshold is', halman.threshold(readings) $ python program.py signal threshold is 1.42857 Python Libraries
  • 13. When a module is imported, Python: Python Libraries
  • 14. When a module is imported, Python: 1. Executes the statements it contains Python Libraries
  • 15. When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores rreeffeerreenncceess ttoo the top-level items in that module Python Libraries
  • 16. When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores rreeffeerreenncceess ttoo the top-level items in that module # noisy.py pppprrrriiiinnnntttt 'is this module being loaded?' NOISE_LEVEL = 1./3. Python Libraries
  • 17. When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores rreeffeerreenncceess ttoo the top-level items in that module # noisy.py pppprrrriiiinnnntttt 'is this module being loaded?' NOISE_LEVEL = 1./3. >>>>>>>>>>>> import noisy is this module being loaded? Python Libraries
  • 18. When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores rreeffeerreenncceess ttoo the top-level items in that module # noisy.py pppprrrriiiinnnntttt 'is this module being loaded?' NOISE_LEVEL = 1./3. >>>>>>>>>>>> import noisy is this module being loaded? >>>>>>>>>>>> print noisy.NOISE_LEVEL 0.33333333 Python Libraries
  • 19. Each module is a namespace Python Libraries
  • 20. Each module is a namespace function Python Libraries
  • 21. Each module is a namespace mmoodduullee function Python Libraries
  • 22. Each module is a namespace global mmoodduullee function Python Libraries
  • 23. Each module is a namespace global module # module.py NAME = 'Transylvania' ddddeeeeffff func(arg): function rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg Python Libraries
  • 24. Each module is a namespace global module # module.py NAME = 'Transylvania' ddddeeeeffff func(arg): function >>>>>>>>>>>> NAME = 'Hamunaptra' rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg Python Libraries
  • 25. Each module is a namespace global module # module.py NAME = 'Transylvania' ddddeeeeffff func(arg): function >>>>>>>>>>>> NAME = 'Hamunaptra' >>>>>>>>>>>> import module rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg Python Libraries
  • 26. Each module is a namespace global module # module.py NAME = 'Transylvania' ddddeeeeffff func(arg): function >>>>>>>>>>>> NAME = 'Hamunaptra' >>>>>>>>>>>> import module >>>>>>>>>>>> print module.func('!!!') Transylvania !!! rrrreeeettttuuuurrrrnnnn NAME + ' ' + arg Python Libraries
  • 27. Python comes with many standard libraries Python Libraries
  • 28. Python comes with many standard libraries >>> import math Python Libraries
  • 29. Python comes with many standard libraries >>> import math >>>>>>>>>>>> pppprrrriiiinnnntttt math.sqrt(2) 1.4142135623730951 Python Libraries
  • 30. Python comes with many standard libraries >>> import math >>>>>>>>>>>> pppprrrriiiinnnntttt math.sqrt(2) 1.4142135623730951 >>>>>>>>>>>> pppprrrriiiinnnntttt math.hypot(2, 3) # sqrt(x**2 + y**2) 3.6055512754639891 Python Libraries
  • 31. Python comes with many standard libraries >>> import math >>>>>>>>>>>> pppprrrriiiinnnntttt math.sqrt(2) 1.4142135623730951 >>>>>>>>>>>> pppprrrriiiinnnntttt math.hypot(2, 3) # sqrt(x**2 + y**2) 3.6055512754639891 >>>>>>>>>>>> pppprrrriiiinnnntttt math.e, math.pi # as accurate as possible 2.7182818284590451 3.1415926535897931 Python Libraries
  • 32. Python also provides a help function Python Libraries
  • 33. Python also provides a help function >>>>>>>>>>>> iiiimmmmppppoooorrrrtttt math >>>>>>>>>>>> help(math) HHeellpp oonn mmoodduullee mmaatthh:: NAME math FILE /usr/lib/python2.5/lib-dynload/math.so MODULE DOCS http://www.python.org/doc/current/lib/module-math.html DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. ⋮ Python Libraries
  • 34. And some nicer ways to do imports Python Libraries
  • 35. And some nicer ways to do imports >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt >>>>>>>>>>>> sqrt(3) 1.7320508075688772 Python Libraries
  • 36. And some nicer ways to do imports >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt >>>>>>>>>>>> sqrt(3) 1.7320508075688772 >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid >>>>>>>>>>>> euclid(3, 4) 5.0 Python Libraries
  • 37. And some nicer ways to do imports >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt >>>>>>>>>>>> sqrt(3) 1.7320508075688772 >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid >>>>>>>>>>>> euclid(3, 4) 5.0 >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt * >>>>>>>>>>>> sin(pi) 1.2246063538223773e-16 >>>>>>>>>>>> Python Libraries
  • 38. And some nicer ways to do imports >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt >>>>>>>>>>>> sqrt(3) 1.7320508075688772 >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid >>>>>>>>>>>> euclid(3, 4) 5.0 >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt * >>>>>>>>>>>> sin(pi) 1.2246063538223773e-16 >>>>>>>>>>>> Generally a bad idea Python Libraries
  • 39. And some nicer ways to do imports >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt sqrt >>>>>>>>>>>> sqrt(3) 1.7320508075688772 >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt hypot aaaassss euclid >>>>>>>>>>>> euclid(3, 4) 5.0 >>>>>>>>>>>> ffffrrrroooommmm math iiiimmmmppppoooorrrrtttt * >>>>>>>>>>>> sin(pi) 1.2246063538223773e-16 >>>>>>>>>>>> Generally a bad idea Someone could add to the library after you start using it Python Libraries
  • 40. Almost every program uses the sys library Python Libraries
  • 41. Almost every program uses the sys library >>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys Python Libraries
  • 42. Almost every program uses the sys library >>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys >>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] Python Libraries
  • 43. Almost every program uses the sys library >>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys >>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] >>>>>>>>>>>> pppprrrriiiinnnntttt sys.platform win32 Python Libraries
  • 44. Almost every program uses the sys library >>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys >>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] >>>>>>>>>>>> pppprrrriiiinnnntttt sys.platform win32 >>>>>>>>>>>> pppprrrriiiinnnntttt sys.maxint 2147483647 Python Libraries
  • 45. Almost every program uses the sys library >>>>>>>>>>>> iiiimmmmppppoooorrrrtttt sys >>>>>>>>>>>> pppprrrriiiinnnntttt sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] >>>>>>>>>>>> pppprrrriiiinnnntttt sys.platform win32 >>>>>>>>>>>> pppprrrriiiinnnntttt sys.maxint 2147483647 >>>>>>>>>>>> pppprrrriiiinnnntttt sys.path ['', 'C:WINDOWSsystem32python27.zip', 'C:Python27DLLs', 'C:Python27lib', 'C:Python27libplat-win', 'C:Python27', 'C:Python27libsite-packages'] Python Libraries
  • 46. sys.argv holds command-line arguments Python Libraries
  • 47. sys.argv holds command-line arguments Script name is sys.argv[0] Python Libraries
  • 48. sys.argv holds command-line arguments Script name is sys.argv[0] # echo.py iiiimmmmppppoooorrrrtttt sys ffffoooorrrr i iiiinnnn range(len(sys.argv)): pppprrrriiiinnnntttt i, '"' + sys.argv[i] + '"' Python Libraries
  • 49. sys.argv holds command-line arguments Script name is sys.argv[0] # echo.py iiiimmmmppppoooorrrrtttt sys ffffoooorrrr i iiiinnnn range(len(sys.argv)): pppprrrriiiinnnntttt i, '"' + sys.argv[i] + '"' $$$$ python echo.py 0 echo.py $ Python Libraries
  • 50. sys.argv holds command-line arguments Script name is sys.argv[0] # echo.py iiiimmmmppppoooorrrrtttt sys ffffoooorrrr i iiiinnnn range(len(sys.argv)): pppprrrriiiinnnntttt i, '"' + sys.argv[i] + '"' $$$$ python echo.py 0 echo.py $ python echo.py first second 0 echo.py 1 first 2 second $ Python Libraries
  • 51. sys.stdin is standard input (e.g., the keyboard) Python Libraries
  • 52. sys.stdin is standard input (e.g., the keyboard) sys.stdout is standard output (e.g., the screen) Python Libraries
  • 53. sys.stdin is standard input (e.g., the keyboard) sys.stdout is standard output (e.g., the screen) sys.stderr is standard error (usually aallssoo tthhee ssccrreeeenn)) Python Libraries
  • 54. sys.stdin is standard input (e.g., the keyboard) sys.stdout is standard output (e.g., the screen) sys.stderr is standard error (usually aallssoo tthhee ssccrreeeenn)) See the Unix shell lecture for more information Python Libraries
  • 55. # count.py iiiimmmmppppoooorrrrtttt sys iiiiffff len(sys.argv) == 1: count_lines(sys.stdin) eeeeeeeellllllllsssssssseeeeeeee:::::::: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close() Python Libraries
  • 56. # count.py iiiimmmmppppoooorrrrtttt sys iiiiffff len(sys.argv) == 1: count_lines(sys.stdin) eeeeeeeellllllllsssssssseeeeeeee:::::::: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close() Python Libraries
  • 57. # count.py iiiimmmmppppoooorrrrtttt sys iiiiffff len(sys.argv) == 1: count_lines(sys.stdin) eeeeeeeellllllllsssssssseeeeeeee:::::::: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close() Python Libraries
  • 58. # count.py iiiimmmmppppoooorrrrtttt sys iiiiffff len(sys.argv) == 1: count_lines(sys.stdin) eeeeeeeellllllllsssssssseeeeeeee:::::::: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close() $ python count.py < a.txt 48 $ Python Libraries
  • 59. # count.py iiiimmmmppppoooorrrrtttt sys iiiiffff len(sys.argv) == 1: count_lines(sys.stdin) eeeeeeeellllllllsssssssseeeeeeee:::::::: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close() $ python count.py < a.txt 48 $ python count.py b.txt 227 $ Python Libraries
  • 60. The more polite way '''Count lines in files. If no filename arguments given, read from standard input.''' iiiimmmmppppoooorrrrtttt sys ddddeeeeffff count_lines(reader): '''Return number of lines in text read from reader.''' rrrreeeettttuuuurrrrnnnn len(reader.readlines()) iiiiffff __name__ == '__main__': ...as before... Python Libraries
  • 61. The more polite way '''Count lines in files. If no filename arguments given, read from standard input.''' iiiimmmmppppoooorrrrtttt sys ddddeeeeffff count_lines(reader): '''Return number of lines in text read from reader.''' rrrreeeettttuuuurrrrnnnn len(reader.readlines()) iiiiffff __name__ == '__main__': ...as before... Python Libraries
  • 62. The more polite way '''Count lines in files. If no filename arguments given, read from standard input.''' iiiimmmmppppoooorrrrtttt sys ddddeeeeffff count_lines(reader): '''Return number of lines in text read from reader.''' rrrreeeettttuuuurrrrnnnn len(reader.readlines()) iiiiffff __name__ == '__main__': ...as before... Python Libraries
  • 63. If the first statement in a module or function is a string, it is saved as a docstring Python Libraries
  • 64. If the first statement in a module or function is a string, it is saved as a docstring Used for online ((aanndd oofffflliinnee)) hheellpp Python Libraries
  • 65. If the first statement in a module or function is a string, it is saved as a docstring Used for online ((aanndd oofffflliinnee)) hheellpp # adder.py '''Addition utilities.''' ddddeeeeffff add(a, b): '''Add arguments.''' rrrreeeettttuuuurrrrnnnn a+b Python Libraries
  • 66. If the first statement in a module or function is a string, it is saved as a docstring Used for online ((aanndd oofffflliinnee)) hheellpp # adder.py '''Addition utilities.''' ddddeeeeffff add(a, b): '''Add arguments.''' rrrreeeettttuuuurrrrnnnn a+b >>>>>>>>>>>> import adder >>>>>>>>>>>> help(adder) NAME adder - Addition utilities. FUNCTIONS add(a, b) Add arguments. >>>>>>>>>>>> Python Libraries
  • 67. If the first statement in a module or function is a string, it is saved as a docstring Used for online ((aanndd oofffflliinnee)) hheellpp # adder.py '''Addition utilities.''' ddddeeeeffff add(a, b): '''Add arguments.''' rrrreeeettttuuuurrrrnnnn a+b >>>>>>>>>>>> import adder >>>>>>>>>>>> help(adder) NAME adder - Addition utilities. FUNCTIONS add(a, b) Add arguments. >>>>>>>>>>>> help(adder.add) add(a, b) Add arguments. >>>>>>>>>>>> Python Libraries
  • 68. When Python loads a module, it assigns a value to the module-level variable __name__ Python Libraries
  • 69. When Python loads a module, it assigns a value to the module-level variable __name__ main program '__main__' Python Libraries
  • 70. When Python loads a module, it assigns a value to the module-level variable __name__ main program loaded as library '__main__' module name Python Libraries
  • 71. When Python loads a module, it assigns a value to the module-level variable __name__ main program loaded as library '__main__' module name ...module definitions... iiiiffff __name__ == '__main__': ...run as main program... Python Libraries
  • 72. When Python loads a module, it assigns a value to the module-level variable __name__ main program loaded as library '__main__' module name ...module definitions... Always executed iiiiffff __name__ == '__main__': ...run as main program... Python Libraries
  • 73. When Python loads a module, it assigns a value to the module-level variable __name__ main program loaded as library '__main__' module name ...module definitions... Always executed iiiiffff __name__ == '__main__': ...run as main program... Only executed when file run directly Python Libraries
  • 74. # stats.py '''Useful statistical tools.''' ddddeeeeffff average(values): '''Return average of values or None if no data.''' iiiiffff values: rrrreeeettttuuuurrrrnnnn sum(values) / len(values) eeeellllsssseeee:::: rrrreeeettttuuuurrrrnnnn NNNNoooonnnneeee iiiiffff __name__ == '__main__': pppprrrriiiinnnntttt 'test 1 should be None:', average([]) pppprrrriiiinnnntttt 'test 2 should be 1:', average([1]) pppprrrriiiinnnntttt 'test 3 should be 2:', average([1, 2, 3]) Python Libraries
  • 75. # test-stats.py ffffrrrroooommmm stats iiiimmmmppppoooorrrrtttt average pppprrrriiiinnnntttt 'test 4 should be None:', average(set()) pppprrrriiiinnnntttt 'test 5 should be -1:', average({0, -1, -2}) Python Libraries
  • 76. # test-stats.py ffffrrrroooommmm stats iiiimmmmppppoooorrrrtttt average pppprrrriiiinnnntttt 'test 4 should be None:', average(set()) pppprrrriiiinnnntttt 'test 5 should be -1:', average({0, -1, -2}) $ python stats.py test 1 should be None: None test 2 should be 1: 1 test 3 should be 2: 2 $ Python Libraries
  • 77. # test-stats.py ffffrrrroooommmm stats iiiimmmmppppoooorrrrtttt average pppprrrriiiinnnntttt 'test 4 should be None:', average(set()) pppprrrriiiinnnntttt 'test 5 should be -1:', average({0, -1, -2}) $ python stats.py test 1 should be None: None test 2 should be 1: 1 test 3 should be 2: 2 $ python test-stats.py test 4 should be None: None test 5 should be -1: -1 $ Python Libraries
  • 78. created by Greg Wilson October 2010 Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information.