Control flows

  • if
  • for
  • while

if statements


In [19]:
x = -5

if x < 0:
    x = 0
    print 'Negative changed to zero'
elif x == 0:
    print 'Zero'
elif x == 1:
    print 'Single'
else:
    print 'More'
    
print x


Negative changed to zero
0
  • the body of the if is indented
    • indentation is python 's way to grouping statement (code block). C using brackets for grouping.
    • each line within a code block must be indented by the same about.
    • you should use only tab to indent or spaces to indent
  • There can be zero or more elif parts, and the else part is optional

In [27]:
x = -5
if x < 0:
    print "X is negative"


X is negative

In [1]:
x = 5
if x == 0: print 'X is zero'

for statements

  • the for statement in python differs with the other languages.

  • No loop over an arithmetic progression of numbers. e.g: cannot write

    for(int i = 0; i < 10; i++)

  • only loop over the items of any sequence


In [5]:
for pet in ['cat', 'dog', 'pig']:
    print 'I own a', pet


I own a cat
I own a dog
I own a pig
  • if you need to iterate over a sequence of numbers, using built-in function range() function

In [31]:
print range(10)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [32]:
print range(5, 10)


[5, 6, 7, 8, 9]

In [33]:
print range(0, 10, 3)


[0, 3, 6, 9]
  • Iterate over the indices of a sequence, you can combine range() and len() as follows:

In [7]:
a = ['Mary', 'had', 'a', 'little', 'lamb']

In [9]:
range(len(a))


Out[9]:
[0, 1, 2, 3, 4]

In [10]:
for i in range(len(a)):
    print i, a[i]


0 Mary
1 had
2 a
3 little
4 lamb

break and continue statements

  • Borrowed from C
  • In case you don't know... In the loop when encounter:
    • break: the loop is immediately terminated and the program control resumes at the next statement following the loop.

In [7]:
for n in [1, 2, 3, 4, 5]:
    if n % 2 == 0:
        print 'Found an even number', n
        break


Found an even number 2
  • In the loop when encounter
    • continue: instead of forcing termination like break. The continue however, forces the next iteration of the loop to take place, skipping any code in between.

In [9]:
for n in [1, 2, 3, 4, 5]:
    if n % 2 == 1:
        continue
    print 'Even number:', n


Even number: 2
Even number: 4

while statements

  • Like while in C

In [24]:
i = 0
while i < 5:
    print i,
    i = i + 1


0 1 2 3 4

exercise

Calculate dot product of two vector [1, 5, 8, 9, 10] and [9, 2, 5, 7, 3]


In [11]:
x = [1, 5, 8, 9, 10]
y = [9, 2, 5, 7, 3]
result = 0

for i in range(len(x)):
    result = result + x[i] * y[i]

print result


152