Close

Python – The For-Loop

Here is a simple for loop which we'll demonstrate using the range function.

In Pyth+on, a block of code is indicated by white space indents rather than encasing it brackets.

[python]
=>=>=> for i in range(5):
... x = i * 10 # note the 4 space indent
... print(x)
...
0
10
20
30
40
=>=>=>
[/python]

The ":" colon indicates the start of the new block.

There are a couple of conventions regarding white spaces:

  1. indents should be 4 spaces long
  2. always use space rather than tab to create the whitespace. Also never mix tabs with spaces.

These conventions are documeted in Python Enhancement Proposals peps, in particular pep 8.

 

Also long lines can be broken over multiple lines by wrapping expressions in parentheses.