More on Python
Lexical Issues - Identifiers and Case
- Identifier: (Letter, "_") {Letter, Digit, "_"}
- Python is case sensitive
Lexical Issues - Indentation and Tabs
- Indent rule 1: Increased nesting requires increased indentation
- Indent rule 2: Nested statements with same parent require identical indentation
- Tabs: Increase indent between 1 and 8 spaces, to an indent divisible by 8
Lexical Issues - Strings
- Strings have implicit concatenation (eg x = 'ab' 'cd')
- Example: x = 'ab' 'cd' identical to x = 'abcd'
- print removes quotes from strings
- Strings must be opened and closed with same delimiter
- No difference between strings created with ' and "
- Strings created with ''' can contain ' and "
- Strings created with ''' can span multiple lines
Lexical Issues - Multiple Lines
- Strings created with ''' can span multiple lines
- Code within (), [], and {} can span multiple lines
- Continuation: code on a line that ends with "\" continues on the next line
- Indentation on continuing lines is ignored
Types
- Types are properties of values, not names
- Some built-in types include
- Numeric: int, long (eg 0L or 12345678901), float, double
- bool
- False values: False, 0, 0.0, empty sequences and maps (ie "", (), [], {}), None
- True values: True, non-zero numbers, non-empty sequences and maps
- Sequence: str, list, tuple
- Mapping: dict
- NoneType - contains only value None
- File - returned by open command
- Module - add something here
Type Coercion and Manipulation
- Use name of type to do explicit coercion
- Examples: str(), int(), long(), bool()
- round()
- Character/int: chr(), ord()
- Convert sequence types: tuple(), list()
- type() returns type
- Implicit: done where possible
- int to float
- effectively int to bool
- coerce(tuple) - returns tuple of values coerced to same type if possible
- eval(string) - evaluate string [another way to convert string to int]
Operators
- Numeric: +, -, *, **, /, //, %
- Relational: <, >, <=, >=,, ==, !=, <> (deprecated)
- is, is not - object identity
- Logical: and, or, not
- in - Examples: 'a' in 'abc', 3 in [1,2,3,4]
- Bit operators: <<, >>, &, |, ^, ~
- Assignment: =, +=, -=, ...
Control Flow
- break
- continue
- pass - add an example --
Sequences
- Sequences are indexable, starting at 0
- Immutable:
- Mutable
Sequence Operations
- The operations below are common to all sequences:
- s[i]
- s[i:j]
- len(s)
- min(s)
- max(s)
- s.count(x)
- s.index(x)
List
- list(s) converts sequence s into a list
- Create an array of size 5: a = [None] * 5
- the following modify s and return None (unless otherwise specified):
- s.append(x) - append x to end of s
- s.extend(l) - extend list s with list l
- s.insert(i, x) - insert x at position i
- s.pop() - remove and return last element
- s.pop(i) - remove and return element i
- s.remove(x) - remove x from s
- s.reverse() - reverse s
- s.sort() - sort s
- s.sort(comp) - sort s with compare function comp
String Operations
- Many string functions are available, of the form s.f()
- Strings are immutable, and so they return a new string rather than modifying
the existing string
- Examples: isalnum(), isalpha(), isdigit(), isspace(), split(), strip()
Map Functions
- len(m)
- m[k]
- m[k] = v
- del m[k]
- m.clear()
- m.copy()
- m.has_key(k)
- m.items() - returns list of (key, value) pairs
- m.keys() - returns list of key values
- m.values() - returns list of all values in m
References and Values
- Lists are mutable, and so assignment for lists creates an alias:
a = [1, 2, 3]
b = a # Reference
c = a[:] # Creates a copy
a[0] = 99
print b # [99, 2, 3]
print c # [1, 2, 3]
Arguments are passed as references
copy.copy(x) - creates a copy of x containing references to elements of x
copy.deepcopy(x) - creates a copy of the references in x
import copy
a = [1, 2]
b = [a, 3]
c = b
d = b[:]
e = copy.copy(b)
f = copy.deepcopy(b)
a[0] = 4
b[1] = 5
print c # [[4, 2], 5]
print d # [[4, 2], 3]
print e # [[4, 2], 3]
print f # [[1, 2], 3]
== vs is
- == compares values
- is compares references
a = [1,2,3]
b = a
c = a[:]
print a == a # True
print a is a # True
print a == b # True
print a is b # True
print a == c # True
print a is c # False
Files and I/O
f = open('filename') # open for reading, return a file
f = open('filename', 'w') # open for writing, return a file
f.read() # return a single character
f.read(n) # return n or fewer characters
f.readline() # return next line of input
f.readlines() # return entire file as list of strings
f.writeline(s) # write string s to f
f.writelines(l) # write list of strings to f
f.close() # close f
s = raw_input(p) # print p and return input string
n = input(p) # print p and return eval(input string)
# ie convert "33" to 33
Output
- print removes "" from strings
- c-like format specifiers can be used
Sets
- Set properties:
- Examples:
- print set([1, 2, 3, 2, 3]) # set([1, 2, 3])
- print 2 in set([1, 2, 3, 2, 3]) # True
- s1 = set([1,2,3,2,1]); s2 = s1.union(set([2,4])) # set([1,2,3,4])
- Other ops:
- s.intersection(t), s.symmetric_difference(t), s.difference(t)
- s.issubset(t), s.issuperset(t)
- x in s, len(s), s.copy()
Scope
- LEGB - Search for definition in this order:
- Local
- Enclosing
- Global
- Built-in
# Example shows local and global
def f():
x = 2
print x # 2 local
print y # 1 global
# back to top level
y = 1
f()
I
- Functions can be nested
- Use enclosing scope
# Example shows local and global
def f():
def nested():
w = 3
print w # 3 local
print x # 2 enclosing
print y # 1 global
x = 2
nested()
# back to top level
y = 1
f()
Think of scope as nested boxes: search outward and use first definition found
Hiding
- A local variable hides a global one
# Example shows local and global
def f():
y = 2 # y is now local, hiding global y
print y # 2 local
# back to top level
y = 1
f()
print y # 1 global
Global Keyword
- Declaring a variable global to refer to global instance
# Example shows local and global
def f():
global y
y = 2 # y is now global, no local y exists
print y # 2 global
# back to top level
y = 1
f()
print y # 2 global
Modules
- A module is just a python file
-
import mymodule
- reads file and creates a dictionary of definitions
- Access that dictionary with
mymodule.somefunction()
- Can add to local scope with
from mymodule import mymethod
- Using
import mymodule
for a second time does nothing
- Can use
reload mymodule
to redo the import
- Module search path - ??
Parameters
- Keyword parameters
- Default values for parameters
Functional Features
- Appy function: apply function f to args
- apply(f, [arglist])
-
apply(f, [], {keyword arg map})
- anonymous functions:
f = lambda x: x + 3
-
map(f, l)
- apply f to each element of l
-
map(lambda x: x+1, [1,2,3]) # [2,3,4]
-
filter(lambda x: x%2 != 0, [1,2,3]) # [1,3]
-
reduce(lambda x, y: x+y, [1,2,3]) # 6
Reflection
- type(x) - returns type of x
- local() - returns local variables
- global() - local variables
- dir() - returns current scope
- dir(somefunction) - returns scope of somefunction
- dir(somemodule) - returns scope of somemodule