2️⃣

3.2 Logic Operators

Logic Operators

Logic operators are used to combine "truth values", or booleans.

  • "and" returns True if both of the booleans are True and False if either is False
    • Ex: Say your mom promised you to buy cookies and chips. If she buys both items, then she didn't break the promise. If she didn't, then she broke the promise. In this case, breaking the promise is equivalent to False while fulfilling the promise is equivalent to True.
  • "or" returns True if either of the booleans is True. It only returns False if both booleans are False
    • Ex: Say your dad promised to buy you a computer or a bike for your 14th birthday. If your dad buys either the computer or the bike, then he fulfilled the promise. Only if your dad didn't buy either did he break his promise. Breaking the promise is equivalent to False while fulfilling the promise is equivalent to True.
  • "not" returns the opposite of something
    • Ex: If your sister promised not to touch your computer and she did, the she would've broken her promise. If she didn't touch your computer, she would've fulfilled it. Breaking the promise is equivalent to False while fulfilling the promise is equivalent to True.

logic_operators.py

# Logic Operators

# and
were_cookies_bought = True
were_chips_bought = True
print(
    "Were both cookies and chips bought? "
    + str(were_cookies_bought and were_chips_bought)
)

# or
was_computer_bought = True
was_bike_bought = False
print("Was a computer or bike bought? " + str(was_computer_bought or was_bike_bought))

# not
is_raining = False
print("Is it NOT raining? " + str(not is_raining))

Practice

Decisions 1

Write in Python syntax what you would say if you wanted either 5 dollars OR (2 drinks AND 1 snack)

Decisions 2

Write in Python syntax what you would say if you wanted Not a drink OR Not a cookie

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.