Python is quite unusual in that blocks of statements are defined not with the usual markers, { and }, or begin and end, but by the actual indention of the code itself.
#!/usr/bin/python3 # # Python program to generate a random number with commentary. # # Import is much like Java's. This gets the random number generator. import random # Generate a random integer in the range 10 to 49. i = random.randrange(10,50) print('Your number is', i) # Carefully analyze the number for important properties. if i < 20: print("That is less than 20.") if i % 3 == 0: print("It is divisible by 3.") elif i == 20: print("That is exactly twenty. How nice for you.") else: if i % 2 == 1: print("That is an odd number.") else: print("That is twice", i / 2, '.') print("Wow! That's more than 20!")
Below is a summary of the rules. Note that blank lines and comments are ignored, so “line” in this discussion means only the non-blank, non-comment lines.
- The first line starts the first block and must not be indented. Indenting the first line is a syntax error.
- A line which is indented the same as the one immediately before belongs to the same block.
- A line which is indented more than the one immediately before it starts a new block.
- A line y which is indented less than the line x immediately before it closes x‘s block and belongs to an earlier block. Specifically:
- Line y is matched with the most recent line a which has the same indent.
- If there is no such line a, or if some line between a and y has a lesser indent, y is a syntax error. Otherwise:
- Line y belongs to the same block as a.
- All blocks started between a and y (including the one x belongs to) are closed.
- The end-of-file closes all open blocks.