Python Lesson 5 - Selection
Python Lesson 5 - Selection
Lesson 5
• A variable name can only be one word
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
•
• Start Python and type in the following code in the script mode window.
• Run your program.
Pyphone 360
Answer: it prints the
What does this text “Pyphone 360”
line of code do? on the screen.
passcode = input("Enter your passcode:")
Welcome – Pyphone
unlocked
else:
print("Incorrect passcode")
Incorrect passcode
• This Python program is an example of selection.
• In Python, as with many other programming languages, we use the keywords if and else.
1. The keywords if and else must be in lower case (not UPPER CASE).
5. Notice how the lines of code after if and else are indented.
Indentation is very important in Python.
6. Python IDLE will automatically create indentation for you on the next line when you
use a colon correctly.
if passcode == "1234":
print("Welcome - Pyphone unlocked")
else:
print("Incorrect passcode")
Our last program only had two choices: the passcode was either correct or
incorrect. What if we wanted to have more than two choices?
• Solution: in Python we can use the elif keyword, which means else-if.
• Type in the following code in the script mode window and run.
Key Terms
An error in a computer program is known as a bug. Try and
find out why. The process of finding and then fixing errors
in computer programs is often called debugging. Many IDEs
such as Python IDLE have inbuilt debugging tools.
Selection
Selection is when computers make decisions.
A computer can be programmed to make a selection between two or more
choices, depending on the condition (the question).
To program selection in Python we use the key words if, elif and else.
elif means ‘else if’. For every if statement, we can include any
number of elif statements. else can be thought of as meaning
‘none of the above’. For every if statement, we can include a single
else statement, or no else statements (else is optional).
Indentation
Indentation is very important in Python. Each block of code after an if, elif or else
statement must be indented. There should always be a colon : at the end of every line of
code containing if, elif or else statements. Python IDLE will then automatically indent
the next line of code when we use a colon correctly.
if something == True:
# stuff that happens if something is true
elif something else == True:
# stuff that happens if something else is true
else:
# stuff that happens if none are true
Success Criteria