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.
# 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
usepython = True if soft in usingpython else False
print usepython
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:
len_software = [(soft, len(soft)) for soft in gis]
len_software
List comprehension with a if condition
len_software = [(soft, len(soft)) for soft in gis if soft in opensource]
len_software
Using the list comprehension return a list of tuple with the pairs key and value, of contact. [2 minutes], like:
[('pietro', 333123808), ('jonh', 123123123)]
contact = {'pietro': 333123808, 'jonh': 123123123}
Possible solutions are:
Use %timeit to see the difference!
x = 0
while x < 4:
print 'a' * x
x += 1
Sometimes is useful interupt the cycle:
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'
Python allow to manage the errors:
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!"