Wednesday, 25 May 2011

Selection Structures

Selection structures are used to make decisions that allow us to control the path of execution.
This lesson covers the if selection structure.


A simple if statement has the following form

if expression:
    true_suite

If the expression is True, the statements indented under the if statement are executed. If the expression is False the program jumps to the next statement after the indented block.

It is important to use consistent indentation. Python uses indentation to signify its block structure.

The else structure allows us to execute one set of statements if the expression is true, and another if the expression is false. It has the following form:

if expression:
    true_suite
else:
    false_suite

Example:

if age >= 18:
    print('You can vote!') 
else:
    print('Sorry, you can't vote yet!')


The above example will display You can vote! if the variable, age, is equal to or greater than 18, else, it will display Sorry, you can't vote yet!.

The elif structure is used to check multiple criteria while keeping your code easy to read.

if mark >= 85:
    print('HD')
elif mark >= 75:
    print('D')
elif mark >= 65:
    print('C')
elif mark >= 55:
    print('P1')
elif mark >= 50:
    print('P2')
elif mark >= 40:
    print('F1')
else:
    print('F2')

Looking back on the previous exercise to create a program that generates a random number, we are going to modify it to ask the user to guess the random number, and if the user guesses it correctly, display "Well done - you guessed it!". If the guess is too low, display 'Too Low', or if it is too high, display 'Too High'.

The solution to this program can be found below, but try to do the work yourself first before looking.



Okay, so once you have that covered and are confident with the structures we will look at combining comparisons using a couple of examples.

and operator - true only if temperature is greater than zero and less than 40:

if temperature > 0 and temperature < 40:
    print('Normal Temperature')
else:
    print('Extreme Temperature')

or operator - true if either of the conditions are true, eg. if it is raining or highUV

raining = True   
highUV = True
if raining or highUV:
    print('Take an umbrella!')

If you are having any problems so far, read through again, look at the code, and just play around with different variables and values until you understand how the structures and output works. You can always post a comment and ask for help if you need it, I'm happy to help!

Continue on to: Repetition Structures

-Nathan (everythingPython)

1 comment:

  1. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.

    python training in bangalore|

    ReplyDelete