Python code layout and control flow¶

In Python, the layout of the source code is very important : the different blocks are NOT delimited by braces or parenthesis, but by the indentation.

The recommended Python code layout, and the recommended coding style in general, are defined in PEP 8. A Python specialized editor should check and help to apply them :

  • Do not use tabulations.
  • Use 4 spaces per indentation level.
  • Limit all lines to a maximum of 79 characters.
  • ...

if, elif, else¶

...will execute a block of code if the expression between if|elif and : is true.

In [1]:
a = 2
b = 3
if a > b:
    print('a>b')
elif a == b:
    print('a==b')
else:
    print('a<b')
a<b

An expression is true if its value is:

  • True
  • any non-empty collection
  • a non-zero number

An expression is false if its value is:

  • False or None
  • any empty collection
  • a zero integer or float or complex

Try those ones:

In [2]:
condition = False
if condition:
    print("true")
else:
    print("false")
false
In [3]:
condition = [ None ]
if condition:
    print("true")
else:
    print("false")
true

Values comparison operators:

  • ==, !=
  • <, <=, >, >=
In [4]:
a=1 ; b=3 ; print(a<b)
a="hello" ; b = "world" ;  print(a>b) # alphabetical order
True
False
In [5]:
print(["a", 2, "b"] == [1, 2, 3])
False
In [6]:
print([a, 2, b] == [1, 2, 3])
False
In [7]:
a=[1, 2] ; b=[1, 2] ; print(a == b)
True

Objects comparison operators:

  • is : this is the same object # DANGEROUS ! (unlesss with None)
  • in : the element is member of the collection
In [8]:
a=[1, 2] ; b=[1, 2] ; print(a is b)
False
In [9]:
condition = None
if condition is None :
    print("no condition")
else:
    print("condition:", condition)
no condition
In [11]:
2 in [1, 2, 3]
Out[11]:
True

Logical operators: not, and, or.

In [12]:
a=12
print(a>10 and a<20)
print(10<a<20)
True
True

while¶

...repeat a block of code, as long as the expression between while and : is true..

In [13]:
a = 0
maxval = 4
while a < maxval:
    print(a)
    a += 1
0
1
2
3

The keywork continue jumps to next iteration.

In [14]:
a = 0
maxval = 4
while a < maxval:
    if a == 2:
        a += 1
        continue
    print(a)
    a += 1
0
1
3

The keywork break jumps outside of the while.

In [15]:
a = 0
maxval = 4
while a < maxval:
    if a == 2:
        break
    print(a)
    a += 1
0
1

for¶

The statement for can repeat a block of code for all the elements of any structure which is iterable: list, tuple, dict, str, ...

In [16]:
for i in ['a', 'b', 'c']:
    print(i)
a
b
c

The strings (type str) are iterable sequences of characters:

In [17]:
for i in "abc":
    print(i)
a
b
c

When iterating over a dictionary (type dict), the iterating value receive the keys of the dictionary:

In [18]:
dictionary = { 'a': 5, 'b': 6, 'c': 7 }
for key in dictionary:
    print(key, dictionary[key])
a 5
b 6
c 7

The keywords continue and break are also usable in a for loop.

Helpers functions¶

When iterating on a sequence of integers, we often use the range()function:

In [19]:
for i in range(5):
    print(i)
0
1
2
3
4

If you want to access the elements of a sequence through their ranks, you can combine len() and range():

In [20]:
values = 'a', 'b', 'c'
for rank in range(len(values)):
    print(rank, values[rank])
0 a
1 b
2 c

It may be easier to use the enumerate() function, which returns some pairs (tuple of two elements) with the rank and the value:

In [21]:
values = 'a', 'b', 'c'
for rank, value in enumerate(values):
    print(rank, value)
0 a
1 b
2 c

What do you think will happen when using enumerate() with a dict ?

In [22]:
dictionary = { 'a': 5, 'b': 6, 'c': 7 }
for value1, value2 in enumerate(dictionary):
    print(value1, value2)
0 a
1 b
2 c

If you want to iterate over the pairs / of a dictionary, rather use the items() method from the dictionary object:

In [23]:
dictionary = { 'a': 5, 'b': 6, 'c': 7 }
for value1, value2 in dictionary.items():
    print(value1, value2)
a 5
b 6
c 7

Questions ?¶

See also:

  • Coding Style : PEP 8