Libraries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See

Slides:



Advertisements
Similar presentations
Input and Output Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Advertisements

15. Python - Modules A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez May 19, 2005.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez June 23, 2005.
Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –
Structured programming
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
Introduction Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
Introduction to Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
The Python interpreter CSE 140 University of Washington Michael Ernst.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
Fixtures Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
This Week The string type Modules print statement Writing programs if statements (time permitting) The boolean type (time permitting)
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Modules and Decomposition UW CSE 190p Summer 2012 download examples from the calendar.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
Python, Toolboxes, Tools & Script Tools
Python From the book “Think Python”
Invasion Percolation: Assembly Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Pipes and Filters Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
…and how to do stuff with them Copyright © The University of Southampton 2011 This work is licensed under the Creative Commons Attribution License See.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
First-Class Functions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
CS2021 Python Programming Week 3 Systems Programming PP-Part II.
Chapter 15. Modules Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Dictionaries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
CSx 4091 – Python Programming Spring 2013 Lecture L2 – Introduction to Python Page 1 Help: To get help, type in the following in the interpreter: Welcome.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
Python Documentation Fran Fitzpatrick. Overview  Comments  Documentation Strings  Pydoc  Comments  Documentation Strings  Pydoc.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Fundamentals of Programming I Overview of Programming
G. Pullaiah College of Engineering and Technology
Lecture 2 Python Basics.
Introduction to Programming
Functions CIS 40 – Introduction to Programming in Python
Introduction to Programming
Functions, Procedures, and Abstraction
Introduction to Programming
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Python 19 Mr. Husch.
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Value-Returning Functions: Generating Random Numbers
Terminal-Based Programs
Browsing Directories Using walk
Python 19 Mr. Husch.
The Python interpreter
The Python interpreter
Functions, Procedures, and Abstraction
Using Modules.
Presentation transcript:

Libraries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information. Python

Libraries A function is a way to turn a bunch of related statements into a single "chunk"

PythonLibraries A function is a way to turn a bunch of related statements into a single "chunk" –Avoid duplication

PythonLibraries A function is a way to turn a bunch of related statements into a single "chunk" –Avoid duplication –Make code easier to read

PythonLibraries A function is a way to turn a bunch of related statements into a single "chunk" –Avoid duplication –Make code easier to read A library does the same thing for related functions

PythonLibraries A function is a way to turn a bunch of related statements into a single "chunk" –Avoid duplication –Make code easier to read A library does the same thing for related functions Hierarchical organization

PythonLibraries A function is a way to turn a bunch of related statements into a single "chunk" –Avoid duplication –Make code easier to read A library does the same thing for related functions Hierarchical organization familylibrary genusfunction speciesstatement

PythonLibraries Every Python file can be used as a library

PythonLibraries Every Python file can be used as a library Use import to load it

PythonLibraries Every Python file can be used as a library Use import to load it # halman.py def threshold(signal): return 1.0 / sum(signal)

PythonLibraries Every Python file can be used as a library Use import to load it # halman.py def threshold(signal): return 1.0 / sum(signal) # program.py import halman readings = [0.1, 0.4, 0.2] print 'signal threshold is', halman.threshold(readings)

PythonLibraries Every Python file can be used as a library Use import to load it # halman.py def threshold(signal): return 1.0 / sum(signal) # program.py import halman readings = [0.1, 0.4, 0.2] print 'signal threshold is', halman.threshold(readings) $ python program.py signal threshold is

PythonLibraries When a module is imported, Python:

PythonLibraries When a module is imported, Python: 1. Executes the statements it contains

PythonLibraries When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores references to the top-level items in that module

PythonLibraries When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores references to the top-level items in that module # noisy.py print 'is this module being loaded?' NOISE_LEVEL = 1./3.

PythonLibraries When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores references to the top-level items in that module # noisy.py print 'is this module being loaded?' NOISE_LEVEL = 1./3. >>> import noisy is this module being loaded?

PythonLibraries When a module is imported, Python: 1. Executes the statements it contains 2. Creates an object that stores references to the top-level items in that module # noisy.py print 'is this module being loaded?' NOISE_LEVEL = 1./3. >>> import noisy is this module being loaded? >>> print noisy.NOISE_LEVEL

PythonLibraries Each module is a namespace

PythonLibraries Each module is a namespace function

PythonLibraries Each module is a namespace module function

PythonLibraries Each module is a namespace global module function

PythonLibraries # module.py NAME = 'Transylvania' def func(arg): return NAME + ' ' + arg Each module is a namespace global module function

PythonLibraries # module.py NAME = 'Transylvania' def func(arg): return NAME + ' ' + arg Each module is a namespace global module function >>> NAME = 'Hamunaptra'

PythonLibraries # module.py NAME = 'Transylvania' def func(arg): return NAME + ' ' + arg Each module is a namespace global module function >>> NAME = 'Hamunaptra' >>> import module

PythonLibraries # module.py NAME = 'Transylvania' def func(arg): return NAME + ' ' + arg Each module is a namespace global module function >>> NAME = 'Hamunaptra' >>> import module >>> print module.func('!!!') Transylvania !!!

PythonLibraries Python comes with many standard libraries

PythonLibraries Python comes with many standard libraries >>> import math

PythonLibraries Python comes with many standard libraries >>> import math >>> print math.sqrt(2)

PythonLibraries Python comes with many standard libraries >>> import math >>> print math.sqrt(2) >>> print math.hypot(2, 3) # sqrt(x**2 + y**2)

PythonLibraries Python comes with many standard libraries >>> import math >>> print math.sqrt(2) >>> print math.hypot(2, 3) # sqrt(x**2 + y**2) >>> print math.e, math.pi # as accurate as possible

PythonLibraries Python also provides a help function

PythonLibraries Python also provides a help function >>> import math >>> help(math) Help on module math: NAME math FILE /usr/lib/python2.5/lib-dynload/math.so MODULE DOCS 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. ⋮

PythonLibraries And some nicer ways to do imports

PythonLibraries And some nicer ways to do imports >>> from math import sqrt >>> sqrt(3)

PythonLibraries And some nicer ways to do imports >>> from math import sqrt >>> sqrt(3) >>> from math import hypot as euclid >>> euclid(3, 4) 5.0

PythonLibraries And some nicer ways to do imports >>> from math import sqrt >>> sqrt(3) >>> from math import hypot as euclid >>> euclid(3, 4) 5.0 >>> from math import * >>> sin(pi) e-16 >>>

PythonLibraries And some nicer ways to do imports >>> from math import sqrt >>> sqrt(3) >>> from math import hypot as euclid >>> euclid(3, 4) 5.0 >>> from math import * >>> sin(pi) e-16 >>> Generally a bad idea

PythonLibraries And some nicer ways to do imports >>> from math import sqrt >>> sqrt(3) >>> from math import hypot as euclid >>> euclid(3, 4) 5.0 >>> from math import * >>> sin(pi) e-16 >>> Generally a bad idea Someone could add to the library after you start using it

PythonLibraries Almost every program uses the sys library

PythonLibraries Almost every program uses the sys library >>> import sys

PythonLibraries Almost every program uses the sys library >>> import sys >>> print sys.version 2.7 (r27:82525, Jul , 09:01:59) [MSC v bit (Intel)]

PythonLibraries Almost every program uses the sys library >>> import sys >>> print sys.version 2.7 (r27:82525, Jul , 09:01:59) [MSC v bit (Intel)] >>> print sys.platform win32

PythonLibraries Almost every program uses the sys library >>> import sys >>> print sys.version 2.7 (r27:82525, Jul , 09:01:59) [MSC v bit (Intel)] >>> print sys.platform win32 >>> print sys.maxint

PythonLibraries Almost every program uses the sys library >>> import sys >>> print sys.version 2.7 (r27:82525, Jul , 09:01:59) [MSC v bit (Intel)] >>> print sys.platform win32 >>> print sys.maxint >>> print sys.path ['', 'C:\\WINDOWS\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']

PythonLibraries sys.argv holds command-line arguments

PythonLibraries sys.argv holds command-line arguments Script name is sys.argv[0]

PythonLibraries sys.argv holds command-line arguments Script name is sys.argv[0] # echo.py import sys for i in range(len(sys.argv)): print i, '"' + sys.argv[i] + '"'

PythonLibraries sys.argv holds command-line arguments Script name is sys.argv[0] # echo.py import sys for i in range(len(sys.argv)): print i, '"' + sys.argv[i] + '"' $ python echo.py 0 echo.py $

PythonLibraries sys.argv holds command-line arguments Script name is sys.argv[0] # echo.py import sys for i in range(len(sys.argv)): print i, '"' + sys.argv[i] + '"' $ python echo.py 0 echo.py $ python echo.py first second 0 echo.py 1 first 2 second $

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

PythonLibraries sys.stdin is standard input (e.g., the keyboard) sys.stdout is standard output (e.g., the screen)

PythonLibraries 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)

PythonLibraries 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) See the Unix shell lecture for more information

PythonLibraries # count.py import sys if len(sys.argv) == 1: count_lines(sys.stdin) else: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close()

PythonLibraries # count.py import sys if len(sys.argv) == 1: count_lines(sys.stdin) else: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close()

PythonLibraries # count.py import sys if len(sys.argv) == 1: count_lines(sys.stdin) else: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close()

PythonLibraries # count.py import sys if len(sys.argv) == 1: count_lines(sys.stdin) else: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close() $ python count.py < a.txt 48 $

PythonLibraries # count.py import sys if len(sys.argv) == 1: count_lines(sys.stdin) else: rd = open(sys.argv[1], 'r') count_lines(rd) rd.close() $ python count.py < a.txt 48 $ python count.py b.txt 227 $

PythonLibraries The more polite way '''Count lines in files. If no filename arguments given, read from standard input.''' import sys def count_lines(reader): '''Return number of lines in text read from reader.''' return len(reader.readlines()) if __name__ == '__main__':...as before...

PythonLibraries The more polite way '''Count lines in files. If no filename arguments given, read from standard input.''' import sys def count_lines(reader): '''Return number of lines in text read from reader.''' return len(reader.readlines()) if __name__ == '__main__':...as before...

PythonLibraries The more polite way '''Count lines in files. If no filename arguments given, read from standard input.''' import sys def count_lines(reader): '''Return number of lines in text read from reader.''' return len(reader.readlines()) if __name__ == '__main__':...as before...

PythonLibraries If the first statement in a module or function is a string, it is saved as a docstring

PythonLibraries If the first statement in a module or function is a string, it is saved as a docstring Used for online (and offline) help

PythonLibraries If the first statement in a module or function is a string, it is saved as a docstring Used for online (and offline) help # adder.py '''Addition utilities.''' def add(a, b): '''Add arguments.''' return a+b

PythonLibraries If the first statement in a module or function is a string, it is saved as a docstring Used for online (and offline) help # adder.py '''Addition utilities.''' def add(a, b): '''Add arguments.''' return a+b >>> import adder >>> help(adder) NAME adder - Addition utilities. FUNCTIONS add(a, b) Add arguments. >>>

PythonLibraries If the first statement in a module or function is a string, it is saved as a docstring Used for online (and offline) help # adder.py '''Addition utilities.''' def add(a, b): '''Add arguments.''' return a+b >>> import adder >>> help(adder) NAME adder - Addition utilities. FUNCTIONS add(a, b) Add arguments. >>> help(adder.add) add(a, b) Add arguments. >>>

PythonLibraries When Python loads a module, it assigns a value to the module-level variable __name__

PythonLibraries When Python loads a module, it assigns a value to the module-level variable __name__ main program '__main__'

PythonLibraries When Python loads a module, it assigns a value to the module-level variable __name__ main programloaded as library '__main__'module name

PythonLibraries When Python loads a module, it assigns a value to the module-level variable __name__ main programloaded as library '__main__'module name...module definitions... if __name__ == '__main__':...run as main program...

PythonLibraries When Python loads a module, it assigns a value to the module-level variable __name__ main programloaded as library '__main__'module name...module definitions... if __name__ == '__main__':...run as main program... Always executed

PythonLibraries When Python loads a module, it assigns a value to the module-level variable __name__ main programloaded as library '__main__'module name...module definitions... if __name__ == '__main__':...run as main program... Always executed Only executed when file run directly

PythonLibraries # stats.py '''Useful statistical tools.''' def average(values): '''Return average of values or None if no data.''' if values: return sum(values) / len(values) else: return None if __name__ == '__main__': print 'test 1 should be None:', average([]) print 'test 2 should be 1:', average([1]) print 'test 3 should be 2:', average([1, 2, 3])

PythonLibraries # test-stats.py from stats import average print 'test 4 should be None:', average(set()) print 'test 5 should be -1:', average({0, -1, -2})

PythonLibraries # test-stats.py from stats import average print 'test 4 should be None:', average(set()) print '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 $

PythonLibraries # test-stats.py from stats import average print 'test 4 should be None:', average(set()) print '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 $

October 2010 created by Greg Wilson Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information.