DOC PREVIEW
Practical Python

This preview shows page 1-2-15-16-31-32 out of 32 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 32 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 32 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 32 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 32 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 32 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 32 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 32 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Practical PythonFundamentalsAssignmentNaming rulesExpressionsprintif and truth testingif teststruth testswhile and forwhile loopsbreak, continue, pass, elsefor loopsfunctionsWhy use functions?Slide 16Example function: intersecting sequencesScope rules for functionsPassing arguments to functionsOptional argumentsModulesWhy use modules?Slide 23Built-in functions and convenient modulesData convertersstring modulere moduleos moduletiming and profilingRunning Python scriptsHello, World!Hello, NamePractical PythonPractical PythonRichard P. MullerMay 18, 2000FundamentalsFundamentals© 2000 Richard P. Muller3AssignmentAssignment•The key to understanding Python is understanding assignment–Similar to pointers in C–Assignment creates references–Functions are pass-by-assignment–Names are created when first assigned–Names must be assigned before being referencedspam = 'Spam' #basic assignmentsspam, ham = 'yum','YUM' #tuple assignmentspam = ham = 'lunch'#multiple target–Can use the copy module for times when you want a new object rather than a pointer to an existing object© 2000 Richard P. Muller4Naming rulesNaming rules•Syntax: (underscore or letter) + (any number of digits or underscores)–_rick is a good name–2_rick is not•Case sensitive–Rick is different from rick•Reserved words:and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while© 2000 Richard P. Muller5ExpressionsExpressions•Function callsspam(ham, eggs)•List/dictionary referencespam[ham]•Method callsspam.hamspam.ham(eggs)•Compound expressionsspam < ham and ham != eggs•Range testsspam < ham < eggs© 2000 Richard P. Muller6printprint•The print command prints out variables to the standard output>>> print "a", "b"a b>>> print "a"+"b"ab>>> print "%s %s" % (a,b)a b•Notes–Print automatically puts in a new line; use print ..., to suppress–print(string) is equivalent to sys.stdout(string + '\n')if and truth testingif and truth testing© 2000 Richard P. Muller8if testsif tests•General format:if <test1>:<statements1>elif <test2>:<statements2>else:<statements3>•Example:x = 'killer rabbit' # Assignmentif x == 'roger':print 'How\'s Jessica?'elif x == 'bugs':print 'What\'s up, Doc?'else:print 'Run away! Run away!'© 2000 Richard P. Muller9truth teststruth tests•In general,–True means any nonzero number, or nonempty object–False means not true: zero number, empty object, or None–Comparisons and equality tests return 0 or 1–In additionX and Y #true if both X and Y is trueX or Y #true if either X or Y is truenot X #true if X is false–Comparisons2 < 3 # true3 <= 4 # true–Equality versus identityx == y # x and y have the same valuex is y # x and y are the same object# or x points to ywhile and forwhile and for© 2000 Richard P. Muller11while loopswhile loops•General format:while <test1>: # loop test<statements1> # loop bodyelse: # optional else<statements2> # run if loop didn't break•Exampleswhile 1: # infinite loopprint 'type Ctrl-C to stop me!' a,b = 0,10while a < b:print a,a = a + 1© 2000 Richard P. Muller12break, continue, pass, elsebreak, continue, pass, else•break–Jumps out of the enclosing loop•continue–Jumps to the end of the enclosing loop (next iteration)•pass–Does nothing (empty statement place holder)while <test>:<statements>if <test2>: breakif <test3>: continue<more statements>else:<still more statements>© 2000 Richard P. Muller13for loopsfor loops•for is a sequence iterator–Steps through items in a list, string, tuple, class, etc.for <target> in <object>:<statements>else: # optional, didn't hit a break<other statements>–Can use break, continue, pass as in while–Can be used with range to make counter loopsfor i in range(10):print ifunctionsfunctions© 2000 Richard P. Muller15Why use functions?Why use functions?•Code reuse–Package logic you want to use in more than one place•Procedural decomposition–Split complex task into series of tasks–Easier for reader to understand© 2000 Richard P. Muller16functionsfunctions•def creates a function and assigns it a name•return sends a result back to the caller•Arguments are passed by assignment•Arguments and return types are not declareddef <name>(arg1, arg2, ..., argN):<statements>return <value>def times(x,y):return x*y© 2000 Richard P. Muller17Example function: intersecting Example function: intersecting sequencessequencesdef intersect(seq1, seq2):res = [] # start emptyfor x in seq1:if x in seq2:res.append(x)return res© 2000 Richard P. Muller18Scope rules for functionsScope rules for functions•LGB rule:–Name references search at most 3 scopes: local, global, built-in–Assignments create or change local names by default–Can force arguments to be global with global command•Examplex = 99def func(Y):Z = X+Y #X is not assigned, so it's globalreturn Zfunc(1)© 2000 Richard P. Muller19Passing arguments to functionsPassing arguments to functions•Arguments are passed by assignment–Passed arguments are assigned to local names–Assignment to argument names don't affect the caller–Changing a mutable argument may affect the callerdef changer (x,y):x = 2 #changes local value of x onlyy[0] = 'hi' #changes shared object© 2000 Richard P. Muller20Optional argumentsOptional arguments•Can define defaults for arguments that need not be passeddef func(a, b, c=10, d=100):print a, b, c, d>>> func(1,2)1 2 10 100>>> func(1,2,3,4)1,2,3,4ModulesModules© 2000 Richard P. Muller22Why use modules?Why use modules?•Code reuse–Routines can be called multiple times within a program–Routines can be used from multiple programs•Namespace partitioning–Group data together with functions used for that data•Implementing shared services or data–Can provide global data structure that is accessed by multiple subprograms© 2000 Richard P. Muller23ModulesModules•Modules are functions and variables defined in separate files•Items are imported using from or importfrom module import functionfunction()import modulemodule.function()•Modules are namespaces–Can be used to organize variable names, i.e.atom.position = atom.position - molecule.positionBuilt-in functions and convenient Built-in functions and convenient modulesmodules© 2000 Richard P. Muller25Data convertersData converters•Most of these are fairly easy to understand–str(obj) Return the string


Practical Python

Download Practical Python
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Practical Python and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Practical Python 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?