Loops provide a means to execute part of the script multiple times. Conditions provide the route to choose whether or not to execute part of a script. Open a new Python script called and type the following;

for i in range(1, 11):
    if i < 5:
        print("%s is less than 5." % i)

    elif i > 5:
        print("%s is greater than 5." % i)

        print("%s is equal to 5." % i)

This script loops i over all values from 1 to 10, and uses an if block to test each value of i. There are three sections to the if block:

if blocks can be used, for example, to correct input, e.g.

import sys

n = int(sys.argv[1])

if n < 0:
    print("We cannot process negative numbers!")

(in this case we use the sys.exit function to exit from the script with the return value -1)

if blocks are very powerful. For example type and run the below script; (you may want to use copy-and-paste rather than typing it in by hand!)

import sys

n = int(sys.argv[1])

if n < 0:
    print("%s is negative." % n)

elif n > 100:
    print("%s is large and positive." % n)

elif n == 10:
    for i in range(n, 0, -1):
        print("%s..." % i)

    print("Blast off!")

elif n == 42:
    print("The answer to life, the universe and everything!")

    print("What is %s?" % n)

Can you work out what it does before you run it? Run it with some different arguments. Does it do what you expect?

Previous Up Next