CodingNic

Getting Started with Python

Boolean Logic

Getting Started with Python 20 min read

Boolean Logic

Objectives

By the end of this chapter, you should be able to:

  • Write conditional logic with if/elif/else
  • Use and, or, and not
  • List examples of falsey values
  • Explain the difference between == and is

💡 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:

python
user = "sam"
if user == "sam":
    print("Awesome!")
elif user == "jordan":
    print("Cool!")
else:
    print("Nope!")

Indentation Defines the Block

python
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.

python
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:

python
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():

python
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:

python
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.

python
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

python
name = input("What is your name? ")

input() always returns a string.

Try It

  1. Write an if/elif/else chain checking a variable against three values.
  2. Confirm three falsey values with bool().
  3. Create two lists with identical contents. Compare them with == and is. Explain the difference.

Recap

  • if/elif/else control which code runs. Indentation determines what’s inside the block.
  • Falsey values include False, 0, None, and empty strings, lists, and dicts.
  • == compares value; is compares identity.

Next lesson: put Module 1 into practice with a set of exercises.