78
Libraries 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.

Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Libraries

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.

Page 2: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

A function is a way to turn a bunch of related

statements into a single "chunk"

Python Libraries

Page 3: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

Python Libraries

Page 4: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

Python Libraries

Page 5: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

A library does the same thing for related functions

Python Libraries

Page 6: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

A library does the same thing for related functions

Hierarchical organization

Python Libraries

Page 7: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

A library does the same thing for related functions

Hierarchical organization

Python Libraries

family library

genus function

species statement

Page 8: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Every Python file can be used as a library

Python Libraries

Page 9: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Every Python file can be used as a library

Use import to load it

Python Libraries

Page 10: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Every Python file can be used as a library

Use import to load it

# halman.py# halman.py

defdefdefdef threshold(signal):

returnreturnreturnreturn 1.0 / sum(signal)

Python Libraries

Page 11: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Every Python file can be used as a library

Use import to load it

# halman.py# halman.py

defdefdefdef threshold(signal):

returnreturnreturnreturn 1.0 / sum(signal)

# program.py

importimportimportimport halman

readings = [0.1, 0.4, 0.2]

printprintprintprint 'signal threshold is', halman.threshold(readings)

Python Libraries

printprintprintprint 'signal threshold is', halman.threshold(readings)

Page 12: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Every Python file can be used as a library

Use import to load it

# halman.py# halman.py

defdefdefdef threshold(signal):

returnreturnreturnreturn 1.0 / sum(signal)

# program.py

importimportimportimport halman

readings = [0.1, 0.4, 0.2]

printprintprintprint 'signal threshold is', halman.threshold(readings)

Python Libraries

printprintprintprint 'signal threshold is', halman.threshold(readings)

$$$$ python program.py

signal threshold is 1.42857

Page 13: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When a module is imported, Python:

Python Libraries

Page 14: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When a module is imported, Python:

1. Executes the statements it contains

Python Libraries

Page 15: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

Python Libraries

Page 16: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

# noisy.py

printprintprintprint 'is this module being loaded?'

NOISE_LEVEL = 1./3.

Python Libraries

Page 17: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

# noisy.py

printprintprintprint 'is this module being loaded?'

NOISE_LEVEL = 1./3.

Python Libraries

>>>>>>>>>>>> import noisy

is this module being loaded?

Page 18: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

# noisy.py

printprintprintprint 'is this module being loaded?'

NOISE_LEVEL = 1./3.

Python Libraries

>>>>>>>>>>>> import noisy

is this module being loaded?

>>>>>>>>>>>> print noisy.NOISE_LEVEL

0.33333333

Page 19: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

Python Libraries

Page 20: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

function

Python Libraries

Page 21: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

modulemodule

function

Python Libraries

Page 22: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

global

modulemodule

function

Python Libraries

Page 23: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Page 24: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

>>>>>>>>>>>> NAME = 'Hamunaptra'

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Page 25: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

>>>>>>>>>>>> NAME = 'Hamunaptra'

>>>>>>>>>>>> import module

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Page 26: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

>>>>>>>>>>>> NAME = 'Hamunaptra'

>>>>>>>>>>>> import module

>>>>>>>>>>>> print module.func('!!!')

Transylvania !!!

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Transylvania !!!

Page 27: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Python comes with many standard libraries

Python Libraries

Page 28: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Python comes with many standard libraries

>>> import math

Python Libraries

Page 29: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Python comes with many standard libraries

>>> import math

>>> >>> >>> >>> printprintprintprint math.sqrt(2)

1.41421356237309511.4142135623730951

Python Libraries

Page 30: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Python comes with many standard libraries

>>> import math

>>> >>> >>> >>> printprintprintprint math.sqrt(2)

1.41421356237309511.4142135623730951

>>> >>> >>> >>> print print print print math.hypot(2, 3) # sqrt(x**2 + y**2)

3.6055512754639891

Python Libraries

Page 31: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Python comes with many standard libraries

>>> import math

>>> >>> >>> >>> printprintprintprint math.sqrt(2)

1.41421356237309511.4142135623730951

>>> >>> >>> >>> print print print print math.hypot(2, 3) # sqrt(x**2 + y**2)

3.6055512754639891

>>> >>> >>> >>> print print print print math.e, math.pi # as accurate as possible

2.7182818284590451 3.1415926535897931

Python Libraries

Page 32: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Python also provides a help function

Python Libraries

Page 33: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Python also provides a help function

>>> >>> >>> >>> import import import import math

>>> >>> >>> >>> help(math)Help on module math:Help on module math:NAME

mathFILE

/usr/lib/python2.5/lib-dynload/math.soMODULE DOCS

http://www.python.org/doc/current/lib/module-math.htmlDESCRIPTION

This module is always available. It provides access to themathematical functions defined by the C standard.

Python Libraries

mathematical functions defined by the C standard.FUNCTIONS

acos(...)acos(x)Return the arc cosine (measured in radians) of x.

Page 34: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

And some nicer ways to do imports

Python Libraries

Page 35: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

Python Libraries

Page 36: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0

Python Libraries

Page 37: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0>>> >>> >>> >>> fromfromfromfrom math importimportimportimport *

>>> >>> >>> >>> sin(pi)

1.2246063538223773e-16>>>>>>>>>>>>

Python Libraries

>>>>>>>>>>>>

Page 38: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0>>> >>> >>> >>> fromfromfromfrom math importimportimportimport *

>>> >>> >>> >>> sin(pi)

1.2246063538223773e-16>>>>>>>>>>>>

Generally a bad idea

Python Libraries

>>>>>>>>>>>>

Page 39: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0>>> >>> >>> >>> fromfromfromfrom math importimportimportimport *

>>> >>> >>> >>> sin(pi)

1.2246063538223773e-16>>>>>>>>>>>>

Generally a bad idea

Someone could add to

the library after you

Python Libraries

>>>>>>>>>>>>the library after you

start using it

Page 40: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Almost every program uses the sys library

Python Libraries

Page 41: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

Python Libraries

Page 42: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]

Python Libraries

Page 43: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]>>>>>>>>>>>> printprintprintprint sys.platform

win32

Python Libraries

Page 44: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]>>>>>>>>>>>> printprintprintprint sys.platform

win32>>>>>>>>>>>> printprintprintprint sys.maxint

2147483647

Python Libraries

Page 45: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]>>>>>>>>>>>> printprintprintprint sys.platform

win32>>>>>>>>>>>> printprintprintprint sys.maxint

2147483647

>>> >>> >>> >>> printprintprintprint sys.path

['',

Python Libraries

['','C:\\WINDOWS\\system32\\python27.zip',

'C:\\Python27\\DLLs', 'C:\\Python27\\lib','C:\\Python27\\lib\\plat-win',

'C:\\Python27', 'C:\\Python27\\lib\\site-packages']

Page 46: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.argv holds command-line arguments

Python Libraries

Page 47: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.argv holds command-line arguments

Script name is sys.argv[0]

Python Libraries

Page 48: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.argv holds command-line arguments

Script name is sys.argv[0]

# echo.py# echo.py

importimportimportimport sys

forforforfor i inininin range(len(sys.argv)):

printprintprintprint i, '"' + sys.argv[i] + '"'

Python Libraries

Page 49: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.argv holds command-line arguments

Script name is sys.argv[0]

# echo.py# echo.py

importimportimportimport sys

forforforfor i inininin range(len(sys.argv)):

printprintprintprint i, '"' + sys.argv[i] + '"'

$ $ $ $ python echo.py

0 echo.py

$$$$

Python Libraries

$$$$

Page 50: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.argv holds command-line arguments

Script name is sys.argv[0]

# echo.py# echo.py

importimportimportimport sys

forforforfor i inininin range(len(sys.argv)):

printprintprintprint i, '"' + sys.argv[i] + '"'

$ $ $ $ python echo.py

0 echo.py

$$$$ python echo.py first second

Python Libraries

$$$$ python echo.py first second

0 echo.py

1 first

2 second

$$$$

Page 51: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.stdin is standard input (e.g., the keyboard)

Python Libraries

Page 52: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.stdin is standard input (e.g., the keyboard)

sys.stdout is standard output (e.g., the screen)

Python Libraries

Page 53: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.stdin is standard input (e.g., the keyboard)

sys.stdout is standard output (e.g., the screen)

sys.stderr is standard error (usually also the screen)sys.stderr is standard error (usually also the screen)

Python Libraries

Page 54: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

sys.stdin is standard input (e.g., the keyboard)

sys.stdout is standard output (e.g., the screen)

sys.stderr is standard error (usually also the screen)sys.stderr is standard error (usually also the screen)

See the Unix shell lecture for more information

Python Libraries

Page 55: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

Python Libraries

Page 56: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

Python Libraries

Page 57: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

Python Libraries

Page 58: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

$$$$ python count.py < a.txt

48

$$$$

Python Libraries

$$$$

Page 59: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

$$$$ python count.py < a.txt

48

$$$$ python count.py b.txt

Python Libraries

$$$$ python count.py b.txt

227

$$$$

Page 60: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

The more polite way

'''Count lines in files. If no filename arguments given,

read from standard input.'''

importimportimportimport sys

defdefdefdef count_lines(reader):

'''Return number of lines in text read from reader.'''

returnreturnreturnreturn len(reader.readlines())

ifififif __name__ == '__main__':

Python Libraries

ifififif __name__ == '__main__':

...as before...

Page 61: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

The more polite way

'''Count lines in files. If no filename arguments given,

read from standard input.'''

importimportimportimport sys

defdefdefdef count_lines(reader):

'''Return number of lines in text read from reader.'''

returnreturnreturnreturn len(reader.readlines())

ifififif __name__ == '__main__':

Python Libraries

ifififif __name__ == '__main__':

...as before...

Page 62: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

The more polite way

'''Count lines in files. If no filename arguments given,

read from standard input.'''

importimportimportimport sys

defdefdefdef count_lines(reader):

'''Return number of lines in text read from reader.'''

returnreturnreturnreturn len(reader.readlines())

ifififif __name__ == '__main__':

Python Libraries

ifififif __name__ == '__main__':

...as before...

Page 63: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

If the first statement in a module or function is

a string, it is saved as a docstring

Python Libraries

Page 64: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

Python Libraries

Page 65: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

# adder.py

'''Addition utilities.'''

defdefdefdef add(a, b):

'''Add arguments.'''

returnreturnreturnreturn a+b

Python Libraries

returnreturnreturnreturn a+b

Page 66: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

# adder.py

'''Addition utilities.'''

defdefdefdef add(a, b):

'''Add arguments.'''

returnreturnreturnreturn a+b

>>> >>> >>> >>> import adder

>>>>>>>>>>>> help(adder)

NAME

adder - Addition utilities.

FUNCTIONSadd(a, b)

Python Libraries

returnreturnreturnreturn a+b add(a, b)Add arguments.

>>>>>>>>>>>>

Page 67: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

# adder.py

'''Addition utilities.'''

defdefdefdef add(a, b):

'''Add arguments.'''

returnreturnreturnreturn a+b

>>> >>> >>> >>> import adder

>>>>>>>>>>>> help(adder)

NAME

adder - Addition utilities.

FUNCTIONSadd(a, b)

Python Libraries

returnreturnreturnreturn a+b add(a, b)Add arguments.

>>>>>>>>>>>> help(adder.add)

add(a, b)

Add arguments.>>>>>>>>>>>>

Page 68: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When Python loads a module, it assigns a value

to the module-level variable __name__

Python Libraries

Page 69: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

When Python loads a module, it assigns a value

to the module-level variable __name__

main program

'__main__'

Python Libraries

Page 70: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

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

Page 71: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

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...

Python Libraries

ifififif __name__ == '__main__':

...run as main program...

Page 72: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

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

Python Libraries

ifififif __name__ == '__main__':

...run as main program...

Page 73: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

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

Python Libraries

ifififif __name__ == '__main__':

...run as main program... Only executed when

file run directly

Page 74: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# stats.py

'''Useful statistical tools.'''

defdefdefdef average(values):

'''Return average of values or None if no data.''''''Return average of values or None if no data.'''

ifififif values:

returnreturnreturnreturn sum(values) / len(values)

else:else:else:else:

return Nonereturn Nonereturn Nonereturn None

if if if if __name__ == '__main__':

printprintprintprint 'test 1 should be None:', average([])

Python Libraries

printprintprintprint 'test 1 should be None:', average([])

printprintprintprint 'test 2 should be 1:', average([1])

printprintprintprint 'test 3 should be 2:', average([1, 2, 3])

Page 75: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# test-stats.py

from from from from stats importimportimportimport average

printprintprintprint 'test 4 should be None:', average(set())

printprintprintprint 'test 5 should be -1:', average({0, -1, -2})

Python Libraries

Page 76: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# test-stats.py

from from from from stats importimportimportimport average

printprintprintprint 'test 4 should be None:', average(set())

printprintprintprint '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

Page 77: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

# test-stats.py

from from from from stats importimportimportimport average

printprintprintprint 'test 4 should be None:', average(set())

printprintprintprint '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

test 5 should be -1: -1

$$$$

Page 78: Python - Software Carpentry · Return the arc cosine (measured in radians) of x. ... >>> euclid(3, 4) 5.0 Python Libraries. And some nicer ways to do imports >>> fromfrom math import

October 2010

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.