MC logo
If Statement
[^] Code Examples
<<List Operations if.py While Loop>>
# 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.")
    if i % 2 == 1:
        print("That is an odd number.")
        print("That is twice", i / 2, '.')
    print("Wow! That's more than 20!")

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. 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.

  1. The first line starts the first block and must not be indented. Indenting the first line is a syntax error.

  2. A line which is indented the same as the one immediately before belongs to the same block.

  3. A line which is indented more than the one immediately before it starts a new block.

  4. 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:
    1. Line y is matched with the most recent line a which has the same indent.
    2. 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:
    3. Line y belongs to the same block as a.
    4. All blocks started between a and y (including the one x belongs to) are closed.

  5. The end-of-file closes all open blocks.

You can find the more official description of all this, along with some examples, here.
<<List Operations While Loop>>