Subsections

Control structures

Conditionals

Conditional operation is done in exactly the same way as in other languages:
if a > c:
    a = c
    c = c*2
print(c)
The indent of 4 characters indicates the conditionally executed commands. The same applies for do and while loops where the body has an indent. Here, print(c) is always executed because it doesn't have an indent.

Loops

Imagine you want to calculate the average of the array y.
s = 0.0
for i in range(len(y)):
    s = s + y[i]
print("Average:",s/len(y))
The “for” statement iterates through all elements of an array with the help of a list created by the “range” command. This is very much C-like. However Python, as for example in C++11 or Swift, allows iterating over the array elements themselves:
s = 0.0
for v in y:
    s = s + v
print("Average:",s/len(y))
which is a much more compact and safe way of coding as there will never be an out of bounds error.

Important: the indent indicates the commands which the loop iterates through. This is the general rule in python.

See the Python documentation for other ways of creating loops.



github / contact

Creative Commons License