Lecture#2
.pdfNaming
First symbol
_ (underscore) or letter
Symbols
_ (underscore), letters, digits
_myfunc __somemagic generate_file generate-file 6func fancy#name
Numbers
Integer
32 bit -2147483648...2147483647 long - arbitrary
boolean - True, False
Float
double precision, no support for single precision
Complex
two double precision numbers
Sequences
List (mutable)
[1,2,”Hello World”, True]
Tuple (immutable)
(1,2,”Hello World”, True)
String (immutable)
“HPC”, ‘new string’, ‘’’Some multiline string’’’
Mappings
Dictionary (mutable)
key-value storage
my_dict = {‘a’:2, ‘string’:42, (1,2,3): [1,2,3]} my_dict[‘a’] == 2 #True
my_dict[(1,2,3)] == [1,2,3] #True
Only immutable types can be a key
Logic
and, or, not
non-zero numbers, non-empty objects: True zero-numbers, empty-objects, None: False comparison and equality: True or False and, or: return operand
if … elif ... else statement
a if b else c statement
Blocks
Blocks are intended (with spaces, not tabs!) if x > y:
print “x > y”
x = y
elif x == y: print “X = Y” else: print “X < Y”
Empty block: pass
Linebreaks
Break the line:
x = [1, 2, \ 3,4]
a = ‘’’Some multiline string’’’
x = [1, 2, 3,4]
x = (1, 2, 3,4)
x = {‘a’:1, ‘b’:4)
x = {‘a’:1, ‘b’:4)
Iterations
for i in some_iterable: do_something(i)
some_iterable:
list, tuple, string, set, other iterable objects
while (x > 5):
do_something(x) x += 1
Functions
def my_func(a, b=None):
print ‘a and b are positional arguments’ print ‘b has default value’
my_func(1) #the same as my_func(1, None) my_func(1, 2)
Can have variable number of arguments
Files
f = open(filename, mode), f.close()
mode:
‘r’ - read (default),
‘w’ - write (existing file is erased), ‘a’ - append,
‘r+’ - read and write
f.read() or f.read(size) #read entire file (be careful) or size bytes
f.readline() #read line
Iterate over file: for line in f:
print line