Code blocks

In Python, conditional statements, functions and loops are defined within code blocks, which have in common:

  • The block definition must end with :

  • The code inside the block must be indented to the right

  • When leaving the block, the code must be indented to the left

There is no begin/end statements, everything is handled by the indent

Common errors
Indent issues are very common at the beginning, be carefull
Text Editor issues
With some text editors, the tab keys would make your code incompatible with other systems. Use 4 spaces instead.

Conditional statements


Conditional statements allow to perform predifined actions depending on certain conditions.

Defining conditional statements

The general structure of a conditional statement is:

x = -10
y = -11
z = -12

# Care with the indent
if ((x==y) & (x==z)):
elif ((x <= y) & (y <= z)):
    print('Increasing order')
elif((x >= y) & (y >= z)):
    print('Decreasing order')
    print('No order')
Decreasing order

The use of brackets in not always necessary:

x = ['a', 'b', 'c']

if 'a' in x:
    print('a in list')
    print('a not in list')
if ('z' in x):
    print('z in list')
    print('z not in list')
a in list
z not in list

There is the possibility to write conditional statements in one line:

# possibility to write if statements in one line
print('a in list') if 'a' in x else print('a not in list')
print('z in list') if 'z' in x else print('z not in list')
if('a' in x): print('match')
a in list
z not in list

For imbricated conditions, the code need to be indented one extra time. Again, carefull with the indent.

x = y = -10
if(x == y):
    # starts a new block with new conditional testing
    if(x > 0):
        print('x == y and positive')
        print('x == y and negative')
x == y and negative