Boolean Logic
Objectives
By the end of this chapter, you should be able to:
- Write conditional logic with
if/elif/else - Use
and,or, andnot - List examples of falsey values
- Explain the difference between
==andis
💡 Why this matters: Deciding what to do based on a condition is most of what code actually does.
if / elif / else
Every condition needs a trailing colon:
user = "sam"
if user == "sam":
print("Awesome!")
elif user == "jordan":
print("Cool!")
else:
print("Nope!")
Indentation Defines the Block
name = "sam"
if name == "sam":
print("Your name is sam")
print("Bye!")
Both lines run here. The second print isn’t indented, so it’s outside the if block and always runs.
and, or, not
and needs both sides true, or needs at least one, not flips a value.
if 1 > 2 or 2 > 1:
print("cool!")
if 1 == 1 and 2 == 2:
print("nice!")
if not False:
print("it is true!")
Chain comparisons directly:
if 1 < 2 < 3:
print("this works!")
This is shorthand for 1 < 2 and 2 < 3.
Falsey Values
These all evaluate to False when passed to bool():
bool(False) # False
bool(0) # False
bool(None) # False
bool("") # False
bool([]) # False
bool({}) # False
This matters because you can check a value directly in an if, without comparing it to anything:
name = ""
if not name:
print("Name is empty.")
not name is True here because name is an empty string, so the message prints.
is vs. ==
== compares value. is compares identity, whether two names point to the exact same object.
list1 = [1, 2]
list2 = [1, 2]
list3 = list1
list1 == list2 # True, same value
list1 is list2 # False, different objects
list1 is list3 # True, same object
Use == unless you specifically need identity.
Getting User Input
name = input("What is your name? ")
input() always returns a string.
Try It
- Write an
if/elif/elsechain checking a variable against three values. - Confirm three falsey values with
bool(). - Create two lists with identical contents. Compare them with
==andis. Explain the difference.
Recap
if/elif/elsecontrol which code runs. Indentation determines what’s inside the block.- Falsey values include
False,0,None, and empty strings, lists, and dicts. ==compares value;iscompares identity.
Next lesson: put Module 1 into practice with a set of exercises.