If Statements
Narrated by Tilda,
self-taught developer
So far we've:
- Created Expressions
- Used Variables
- Made Our Own Functions
Next Step:
- Write code that will only run on a certain condition
- For example, only display "Game Over" when we've run out of lives
The "If" Statement
- Also called a "conditional" statement
- Allows the computer to decide what code to run based on a condition
Basic Comparisons
Flowcharts
Flowcharts
# Basic comparisons
if a < b:
print("a is less than b")
if a > b:
print("a is greater than b")
print("Done")
More Comparison Types
if a ≤ b:
Indentation
Using And/Or
Boolean Variables
George Boole
(1815 - 1864)
Credited for Boolean Algebra
The "input" Function
"Else" and "Else If"
Text Comparisons
Multiple Text Possibilities
Case-Insensitive Comparisons
Review
# If statements
if a < b:
print("a is less than b")
# If statements
if a < b:
print("a is less than b")
elif a > b:
print("a is greater than b")
else:
print("a is equal to be")
# Assignment operator uses one equals
# You are TELLING it the value
a = 5
# Comparison operator uses two equals
# You are ASKING if it is the value
if a == 5:
print("a is five")
# Boolean values store True or False
is_rainy = True
# If statements can operate on these
if is_rainy:
print("Open umbrella")
if not is_rainy:
print("Water garden")
If Statements
By Paul Craven
If Statements
- 1,281