Selection - Python

From TRCCompSci - AQA Computer Science
Revision as of 12:58, 20 June 2018 by Admin (talk | contribs) (Now Try)
Jump to: navigation, search

What is Selection

Selection is a key construct that exists in any programming language, and each language has a specific implementation but they are all relatively the same.The other key constructions are sequence (ie program runs in order) and iteration (loops).

If Statement in Python

Use the command ‘if’ followed by a condition & the colon ‘:’, The condition should equate to true or false. Instead of using brackets, in python you indent the code to run if true. Each line with the same indent will be run if true. The else can also be used followed by a colon ‘:’ and again the code to run in the else should be indented:

if true:
    line 1
    line 2
else:
    line 3
    line 4

Comparison Operators

The condition in the if statement must equate to true or false, so comparison operators are required. In python the comparison operators are:

Python comparison operators.gif

Example

The if...else statement can be used to make a decision:

age =  input("Please enter your age:")
if age>=18 :
     print("You are old enough to drink")
else :
     print("you are not old enough to drink")

Now Try

  1. Create the code to check if a person should receive the national living wage (25)
  2. Create a variable called answer & set it to a number. Ask the user to enter a guess and then check against the answer.

Logical Operators

If we want something to be False we can use not. It is a logical operator:

Not

x = False
if not x :
    print("condition met")
else:
    print("condition not met")

Two easy to understand operators are and and or. They do exactly what they sound like::

And

if 1 < 2 and 4 > 2:
    print("condition met")

if 1 > 2 and 4 < 10:
    print("condition not met")

Or

if 4 < 10 or 1 < 2:
    print("condition met")

You are not restricted to one logical operator. You can combine as may as you want.

Else If (elif)

In python the Else If is combined to be called elif. This can follow an if or another elif. So the if would check to see if something is true, the elif will check another condition with the values which failed the original if. For example:

mark = input("Please enter your mark")
if mark > 90:
     print("A*")
elif mark > 80:
     print("A")
elif mark > 70:
     print("B")
elif mark > 60:
     print("C")
elif mark > 50:
     print("D")
elif mark > 40:
     print("E")
else:
     print("U")

Now Try

  • Create a program to enter an age, and then This program should then decide:
    • 0-3 = Baby
    • 4-6 = Infant
    • 7-10 = Child
    • 11-14 = Young Teenager
    • 15-17 = Annoying Teenager
    • 18-21 = Less Annoying Teenager