Python Notes - if

Contents   Installing Python   Variables   Input/Output   if   while   Functions - def   Scopes (local/global)   Function parameters   Lists (arrays)   Dictionaries   Tuples   Files   Libraries   Hints, tips  

Programs can make a choice, based on the values of variables. To do this we can use:
Comparison operatorsMeaning
== equals
> greater than
< less than
>= greater or equal
<= less or equal
!= not equals
and true if both true
or true if either true
not reverses condition

Note that we use a single = for assignment, and a double == equality for equality testing.

Boolean (True / False) values

Python has the values True, False. Note capitals. Examples:
a = 3
b = 4
age = 20
print b > a                    # prints True
print not(b>a)                 # False
print a == 3                   # True
print (a == 3) and (b == 4)    # True - both items are true
print (a == 3) and (b == 3)    # False - both not true
print (a == 3) or (b ==3)      # True - even when one is false
print (age>=16) and (age <=60) # True - between 16 to 65
result = (age>=16) and (age <=60)
if result == True:             #  the IF is True

Note that Python nis rather different from other languages in the way we can compare items. here we will adopt the approach of other languages.

if elif else

We can make choices with if. Here, we classify a mark: less than 40 is a fail, 60 or above is a credit, 80 or above is a distinction.

mark = input("Type exam mark: ")
if mark>=80:
    print "Distinction"
elif mark>=60:
    print "Credit"
elif mark>=40:
    print "Pass"
else:
    print "Fail"
print "Done"

Pictorially:

                                                            
                                 |                         
                                 |
       +--------------------------+-------------------------+ 
       |                     |                  |           |  
       |                     |                  |           | 
    distinction           credit              pass        otherwise
       |                     |                  |           |   
       |                     |                  |           |    
       +----------------------------------------------------+        
                                 |        
                                 |         
                               done                         

The instructions are processed from top to bottom. If the first condition is true, the mark is a distinction.
If >= 60, it is a credit, if >=40 a pass. If none of the above were true, the final else section is done, printing Fail.

Note that:

  • some of the code has been indented (shifted to the right). You Must do this in Python - layout is not optional like it is in most languages. In Idle, you can use the tab key, or (e.g) 4 spaces.
  • indented code is termed a 'block' of code. Above, we have one statement, but any number of statements can be in a block.
  • note the colon at the end of if elif (else if) else
  • when an if is found to be true, its matching block is obeyed. Then, the program moves to the end of the complete if/elif/else instruction. In our e.g, this means printing Done.
  • Consider the actions in our choice:
    print "Distinction"
    print "Credit"
    print "Pass"
    print "Fail"
    
    
    Because of the way if-elif-else works, only one of the above will be chosen. It is not possible to skip them all (due to the else default/catch all), and it is not possible to do more than one of them (because when one is performed, we then skip to the end of the whole lot.)
What if we put:

mark = input("Type exam mark: ")
if mark>=80:
    print "Distinction"
elif mark>=60:
    print "Credit"
elif mark>=40:
    print "Pass"
else:
    print "Fail"
    print "Done"

Note that the print "Done" will only be executed in the fail case, because of its indenting. When we have:

if x>0:
    y = 0
    c = 8
d = 4

the block has 2 instructions, and we can see its end because of the end of the indenting. The d = 4 line is 'outdented' or 'dedented'. The Idle program has menus to indent/dedent blocks.

One style of commenting is to mark the point where the branches re-join by a comment, such as #endif:


mark = input("Type exam mark: ")
if mark>=80:
    print "Distinction"
elif mark>=60:
    print "Credit"
elif mark>=40:
    print "Pass"
else:
    print "Fail"
#end if

print "Done"

The above code works, but depends on the order of the ifs. For example:
if mark>=60:

applies to 65, 85, 95. We could recode as:
if (mark >= 70) and (mark <= 79):

Now, the correctness does not depend on the order of the comparisons.

Finally, note that we do not always need an else:


if (account <=10) and (account>=0):
    print "Account is low: warning!)

When we have 2 choices, we don't need an elif:

if account < 0:
    print "Account has no money - can't withdraw"
else:
    account = account - withdrawAmount


Contents   Installing Python   Variables   Input/Output   if   while   Functions - def   Scopes (local/global)   Function parameters   Lists (arrays)   Dictionaries   Tuples   Files   Libraries   Hints, tips