Conditional Statements
• Think of conditional statement as a test
• Returns True or False
Python if syntax
if expression_1:
statements…
elif expression_2:
statements…
else:
statements…
• Python evaluates the if and elif statements starting with the first and proceeding to the last
• If any of expressions evaluate to True, it runs the block of statements associated with that if/elif clause and then skips the rest of the clauses and continues with the next statement after the if-block
#!/usr/bin/bash/env python3
my_name = "Dave"
my_age = 30
# Tests --these are basic logic
# What would the REPL say after you typed these in?
# Equality
my_name == 'Dave'
# Inequality
my_name != 'Steve'
# Greater than / Less than
my_age > 60
my_age < 60
# GTE, LTE
my_age >= 60
my_age <= 60
# Combinations
# PEMDAS
# AND OR
age > 16 and age < 100
16 < age < 100 # better
True and False
True and True
True or False # the 2nd one 'False' never evaluated
False or True # evaluates both
# Booleans -- the thing we're actually dealing with
0 == False
1 == True
is_authenticated = True
is_admin = False
If Elif and Else
#!/usr/bin/env python3
# Simple Structure
# if conditional_statement:
# statement()
# Example
command = "destroy datacores"
if command == "destroy datacores":
print("Destroying all datacores")
# Optional Else
if command == "hello" and 8 > 1:
pass
else:
print("This executes only if the first conditinal was False")
# Optional Elif (between original conditional test and 'else' keyword)
command = input("How would you like to proceed?\n").lower()
if command == "destroy datacores":
print("Destroying all datacores")
elif command == "shut down":
print("Shutting the system down")
elif command == "premabork the frambulator":
print("Are you sure? You will not be able to unbork this later..")
# None of the others evaluated to True...
else:
print("Command not understood")
Only the First Elif Runs
• Some language will execute both elif per example below but not python
# The first one to evaluate to True 'wins'
if 3 !=3:
print('strange...')
elif 8 == 8:
print('First True elif found...')
elif 8 > 4:
print('Second True elif found...')
# Output
# First True elif found...
Nested If Elif and Else
print("This happens before the 'if' block.")
user_is_admin = True
# What conditionals allow you to do
if user_is_admin:
print("Access Granted.")
command = input("How would you like to proceed? ")
command = command.lower()
if command = "destroy datacores":
print("Destroying all datacores")
elif command == "exit":
print("You don't have the guts, do you?")
else:
print("Access Denied.")
print("This happens after the 'if' block.")
Index