if Statement
if x < 0:
# Action 1
elif x == 0:
# Action 2
elif x == 1:
# Action 3
else:
# Action 4
for Statement
devices = ['computer', 'phone', 'printer']
for elements in devices:
print elements, len(elements)
# Output:
computer 8
phone 5
printer 7
range() Function
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions:
range(10)
# Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(5, 10)
# Output:
[5, 6, 7, 8, 9]
range(0, 10, 3)
# Output:
[0, 3, 6, 9]
range(-10, -100, -30)
# Output:
[-10, -40, -70]
To iterate over the indices of a sequence, combine range() and len() as follows:
sentence = ['Tom', 'is', 'a', 'nice', 'guy']
for i in range(len(sentence)):
print i, sentence[i]
# Output:
0 Tom
1 is
2 a
3 nice
4 guy
Defining Functions
We can create a function like follows:
def sum(a,b): # returns a+b
return a+b
# Now call the function we just defined:
sum(2,43)
# Output:
45
