 |
Basic Syntax
stmt: # trailing colon introduces
stmt2 # an indented statement or clause
# # comment
\ # line continuation
; # statement separator (like C)
if cash > price: Eggs(); Spam() # we eat both if we've enuff money
True False # note spelling (Python 2.3)
"abc" # strings can be enclosed
'abc' # in single or double quotes
s = 'abc'
s[0] = 'A' # wrong: strings are immutable
(n,n,...) # tuple
n,n,... # tuple
t = (1, 2, 3) # named tuple variable
n = t[0] # access tuple element
t = ('math',101) # create named tuple
(course,num) = t # unpack tuple
[n,n,...] # list
list = [ 'a', 'b', 'c' ] # list variable
list[1] # access element
list = [ 'eggs', 12 ] # heterogenous lists are supported by Python
# but using tuples as elements may be better
d = {'vorlon':0, 'shadow':1} # create dictionary
d['vorlon'] # access by key
None # NULL
not # logical/boolean not returns True/False
# Logical/boolean and/or
# For 'X or Y', returns X if it's true, else Y
# For 'X and Y', returns X if it's false, else Y
# Both return an object, not true/false nor 0/1!
a = 0; b = 2; plan = a or b # plan = 2 (not 1 as one might expect)
i = 0; L = []; z = i or L # z = [] (z = L)
i = 0; L = []; z = L or i # z = 0 (z = i)
& | ~ # bitwise
== != < > <= >= # equality, relational
is # object identity
is not
** # power (x^y)
// # floor division (truncates to integer)
pass # NOP
* # multiple meanings:
str = 2 * 'abc' # repeats a string: 'abcabc'
x = (1, 2, 3) # unpacks a tuple into individual values
func( *x ) # pass 3 separate args rather than a tuple
+= -= *= etc # shorthand like C
if <cond>: # conditional
[elif <cond>:]
[else:]
while <cond>: # while loop
[break] # break out of looping
[continue] # iterate to top of loop
[else:] # 'else' clause will execute when condition becomes false.
# To be exact, 'else' will execute unless 'break' was executed.
for item in sequence:
if item == sought:
break
else: # This is the Pythonic way of saying "if item not found".
print item, 'not found' # 'else' clause will execute unless 'break' was executed.
return # implicitly returns None
return (res1,res2) # a tuple can be used to return multiple values
try: # except clause executed if exception matches
[except [exception[,value]]]: # omitted name matches any exception
else: # else clause executed if no exception
def func( arg1, arg2 = 10 ) # second arg has a default
def func( *arg ) # arg is a tuple (arbitrary number of arguments)
func( (123, 456, 789) ) # arg = ( 123, 456, 789 )
foo( name='eggs', age='12' ) # args can be specified by name
def func( arg1, **arg2 ) # final arg is a dictionary
float(123) float('123.0') # convert integer/string to float
str(123) # convert to string (stringify)
`123` # convert to string (stringify) (deprecated)
int(1.5) # convert to integer (truncate)
bool(x) # convert to boolean
hex(15) # convert to string in hex format
int('101',2) # convert to int from binary number in string
# A list comprehension is a shorthand with two usual forms:
# [ x for x in seq ]
# [ x for x in seq if expr ]
# A list comprehension creates a new list by appending 'x'
# on every iteration of 'for x in seq'.
# If an optional 'if' clause is written, 'x' is only appended
# if the 'if' clause evaluates to true.
list = [ 1, 2, 3, 4, 5, 6 ]
result = [ 2*x for x in list] # new list whose elements are double
result = [ x for x in list if x % 2 == 0 ] # new list with even values
# lamba creates an anonymous function. Unlike 'def',
# formal args aren't parenthesized. A lambda is limited to
# being an expression and its result is implicitly returned.
sum = lambda a, b: a + b
x = sum(10,20)
# Class attributes have similarities to C++ static members.
# Inside a class block, they're set using their unqualified names.
# But inside a method, class attributes require class-qualified names
# to distinguish them from method local vars and instance attributes.
class Class:
msCnt = 0 # right
Class.msCnt = 0 # wrong (the class name isn't valid yet)
def __init__( self ):
print msCnt # wrong (non-existent local var)
print s.msCnt # technically wrong (will work): class attribute confused as instance attribute
print Class.msCnt # right
self.msCnt += 1 # wrong: changes this instance's attribute, not class attribute
Class.msCnt += 1 # right
|
 |