Conditions

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 nano conditions.py and type the following;

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

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

    else:
        print("%d 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!")
    sys.exit(-1)

(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("%d is negative." % n)

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

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

    print("Blast off!")

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

else:
    print("What is %d?" % n)

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


Compare with Perl


Previous Up Next