Selection Non-Linear Programs

Selection
Non-Linear Programs
Introduction to Python
Introduction to Python
L3 Selection
Learning Objectives
• All to use selection statements if, else and elif
in a program
• Most to learn how to use different comparison
operators
• Some to use indentation correctly to define a
block of code
Introduction to Python
L3 Selection
What exactly does this program do?
#Password Checker
print("Welcome to PGO Security Systems")
print("*******************************")
password = input("Enter your password: ")
if password == "abcd1234":
print("Access Granted")
else:
print("Access Denied")
print("Press ENTER to exit the program")
Introduction to Python
L3 Selection
Indentation!
•
•
•
Python requires indentation as part of the syntax
Indentation signifies the start and end of a block of code
Programs will not run without correct indentation
if password == "abcd1234":
print("Access Granted")
else:
print("Access Denied")
print("Press ENTER to exit the program")
Introduction to Python
L3 Selection
Using an IF Statement
• An IF Statement uses Selection
• IF forces a decision
• If condition Then do this Else do that
If nobody saw me do it Then
might get away with it
Else
busted
Introduction to Python
L3 Selection
IF Syntax
age = int(input("Enter age: "))
if age >= 18:
print ("Adult")
else:
print ("Child")
Introduction to Python
L3 Selection
Comparison operators
Operator
Meaning
Example
Evaluates to
==
equal to
7==7
True
!=
not equal to
6!=7
True
>
Greater than
7>6
True
<
Less than
5<8
True
>=
Greater than or equal to
6>=8
False
<=
Less than or equal to
7<=7
True
Introduction to Python
L3 Selection
Who uses IF statements?
• Thinking of a
mobile phone,
for example,
where might an
IF Statement
appear in its
coding?
Iphone 5s
Introduction to Python
L3 Selection
Write a program
• Write a simple program that might be used
inside a police speed camera.
The Requirements are:
– It must accept the driver’s
speed
– IF the speed is over 70mph, a
message “Issue Fine” should
appear on the speed gun
– Otherwise it should display
“No Action”
Introduction to Python
L3 Selection
The ELIF Statement
• If gives you two
options
• ELIF stands for
Else, If and gives
you more options
• You can use it as
many times as
you like
if grade >= 80:
print("Distinction")
elif grade >= 70:
print("Merit")
elif grade >= 60:
print("Pass")
else:
print("Fail")
Introduction to Python
L3 Selection
Using the ELIF statement
• Add an ELIF statement to
the Speeding program.
• Issue a warning between
70 and 75mph
• Only issue a fine for
75mph and over
Introduction to Python
L3 Selection
Finally…
• Complete the plenary questions to show me
what you have learnt today.