Python Basics 2
CptS 355 - Programming Language Design Washington State University |
|
Python miscellanyDictionary Operationslen (d) d[k] r exception keyError d.get(k, defaultValue) # no exception. defaultValue if k not in d d[k] = x del d[k] # keyError d.haskey(k) k in d d.items() #lue pairs d.keys() d.values() Sequence operations of interest
cmpfunc is an optional two-argument function returning -1, 0, 1 as the items compare less, equal, or greater, respectively. List comprehensions: a way to write a list that involves a common computation for each element: l1 = [1, 2, 3] [el * el for el in l] l2 = [10, 20, 30] [el1 * el2 for el1 in l1 for el2 in l2] or even [[el1*el2 for el1 in l1] for el2 in l2] ScopingPython uses static scoping, but it has no declarations. This raises an interesting question: what makes a variable local to a block. Answer: any assignment to a variable in a function creates a local binding in that function (at the time the function is called). Thus if a variable is assigned-to in a function and is read before the assignment it will be reported as an error at runtime. Read references use the usual static scope rules. Exception to the above. The global var, var, varforces both read references and assignments to the listed variables to be to outer-most scope (module scope). ModulesEach python file is a module; modules are part of packages (ignore for now). To use values from another module, first use theimport
statement
import modulenameThe modulename is just the filename containing the code without the .py suffix. Refer to names within a module by from mod import name, name, nameor even from mod import *which make the imported names behave as if they were local to the scope where they were imported. This can be a source of confusion. Especially
from mod import *.
Where are modules found? (Recall a module is just a python source code file.) By searching, directories on sys.path (you can change sys.path within a program) Outputprint expr, expr, exprprints the values of the provided expressions separated by spaces and followed by a newline. If you don't want the trailing newline end the print statement with a comma, i.e. print expr, File operationsTo open a file use theopen function:
f = open (filename [, mode = 'r'])Files can be opened in differen modes depending on what you want to do. Valid modes are 'r' -- read, 'w' -- write, and 'a'
append. An open file is an object with methods appropriate for the way it was opened.
For example, files opened for reading have methods such as read,
readline, and readlines.
An open file will also behave like a list in some contexts so you can write
for line in f:
process one line
or even
for line in open(filename):
process one line
String formatting expressions(template with % insertion points) % (tuple of values to insert) File directory operations
The module
Something to watch out for:
|
|