Syntax

The indentation (4 spaces) in python it's important

The main Syntax are:

- if, elif, else;
- for and list-comprehension;
- while;
- break and continue;
- function;
- decorator;
- class.

if, elif, else

In [ ]:
# define some sets
gis = set(['arcgis', 'mapinfo', 'qgis', 'grass', 'udig'])
opensource = set(['qgis', 'grass', 'udig'])
usingpython = set(['qgis', 'grass', 'arcgis'])


soft = 'arcgs'
if soft in gis:
    print 'it is a GIS software'
elif soft in opensource:
    print 'it is opensource'
elif soft in usingpython:
    print 'it use python'
else:
    print 'something else...'

Use a if condition to assign a variable

In [ ]:
usepython = True if soft in usingpython else False
print usepython

for

In [ ]:
for soft in gis:
    print soft, '\n', '=' * len(soft)
    if soft in opensource:
        print 'it is opensource'
    else:
        print 'it is propretary'
    if soft in usingpython:
        print 'it use python'
    else:
        print 'it use something else'
    print '\n'

List comprehension:

In [ ]:
len_software = [(soft, len(soft)) for soft in gis]
len_software

List comprehension with a if condition

In [ ]:
len_software = [(soft, len(soft)) for soft in gis if soft in opensource]
len_software

Exercise 7

Using the list comprehension return a list of tuple with the pairs key and value, of contact. [2 minutes], like:

[('pietro', 333123808), ('jonh', 123123123)]
In [ ]:
contact = {'pietro': 333123808, 'jonh': 123123123}

Possible solutions are:

In [ ]:
 

Use %timeit to see the difference!

while

In [ ]:
x = 0
while x < 4:
    print 'a' * x
    x += 1

continue and break

Sometimes is useful interupt the cycle:

In [ ]:
for soft in gis:
    print soft, '\n', '=' * len(soft)
    if soft in opensource:
        print 'it is opensource'
        break
    else:
        print 'it is propretary'
    if soft in usingpython:
        print 'it use python'
        continue
    else:
        print 'it use something else'
    print '\n'

Try and except

Python allow to manage the errors:

In [ ]:
numerator = 1
denominator = 0.5 # change to 0
try:
    print numerator/denominator
except ZeroDivisionError:
    print "Divide a number with 0 is not a valid operation!"
In [ ]: