Monday 27 July 2015

Making Decisions: if-elif-else

#!/usr/bin/env python

# Programs normally execute one line after the other from top to bottom.
# But sometimes we need to make a decision while the program is running.
# Some of these decisions will send the program down one path or the other.

# To do this in Python we use the if-elif-else statements.

# The first thing to note is Python uses indentation to define code blocks
# rather than the {} notation found in C or Java. This means in Python
# indentation of code blocks is manditory. We also don't actually
# type "then" as in "if condition is true then do somemthing". Instead we use
# a colon ":". Because why not?

# Basic if statement.
A = 0 # Integer.
if A == 0: print A

# A more complex example with indentation defining a code block.

A = [1,2,3,4,5] # List of integers.
if A[0] != 0:
        print ("A at index 0 is equal to %d.") % A[0]
        print ("A at index 0 is equal to %d.") % A[1]
        print ("A at index 0 is equal to %d.") % A[2]
        print ("A at index 0 is equal to %d.") % A[3]
        print ("A at index 0 is equal to %d.") % A[4]      

# Both the examples above will only print the value of A if the condition is
# met. But often we need alternative actions to be taken when the condition
# has not been met. For this we add the else statement.

A = 1
if A == 0:
        print A
else:
        print ("A is not 0.")
       
# By adding additional if statements we can test for multiple possibilities.
# We do this in Python by using elif.

A = 2
if A == 0:
        print A
elif A == 1:
        print A
elif A == 2:
        print A
elif A == 3:
        print A
else:
        print ("The value of A does not match the test.")

No comments:

Post a Comment