Python has "if", for loop, and while loop.

The conditional if statement is generally written as


In [ ]:
if (expression):
    stmt1
    stmt2
    ...
    stmtN

The expression is followed by one or more statements, indented in some way. All the statements in the same block must be indented in the same way, else python will get confused. Mixing tabs & spaces will cause confusion, so choose only one.

If you need an else block, then the usage looks like. This property also makes it difficult to copy-paste python code easily.


In [ ]:
if (expression):
    stmt1
    stmt2
    ...
    stmtN
else:
    stmt1
    stmt2
    ...
    stmtN

In python, "else if" becomes "elif"


In [ ]:
if (expression):
    stmt1
    stmt2
    ..
elif (expression):
    stmt1
    ...

If the body of the if needs only one statement, then this can be written as


In [ ]:
if (expression): stmt

The while loop looks like the following. The while loop exits when the expression evaluates to false, of if a "break" is encountered.


In [ ]:
while (expression):
    stmt1
    stmt2
    ...
    stmtN

There's also a for loop. This iterates over a sequence of items. The loop finishes when there are no ore items in the sequence. The loop can be exited with the "break" statement.


In [ ]:
for var in iterable:
    stmt1
    stmt2
    ...
    stmtN

A for loop over a list iterates over it


In [1]:
for i in range(5):
    print i


0
1
2
3
4

Here, the range() built-in function returns a list of numbers


In [2]:
range(5)


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

In [3]:
range(1,5)


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

In [4]:
range(1,5,2)


Out[4]:
[1, 3]