Python: control structures

a = [0, 1, ‘hello’, ‘python’]
for i in a:
print i

for i, j in enumerate(a):
print i, j // Same as above, but prints the index

while i < 10:
i = i + 1

break and continue can be used to break out of the list

if i == 0:
print ‘zero’
elif i == 1:
print ‘one’
else:
print ‘other’

if i == 0 or (i == 1 and i + 1 == 2):

    print ‘0 or 1’

Try / Catch statements:

try:
a = 1 / 0
except Exception, e:
print ‘oops: %s’ % e
else:
print ‘no problem here’
finally:
print ‘done’

You can have more than one except statement (for different kinds of exceptions)

 

Leave a Reply

Your email address will not be published. Required fields are marked *