Notes
Booleans and comparisons
- A Boolean is
TrueorFalse. Comparison operators:==,!=,<,>,<=,>=. Remember=assigns and==compares.
If, elif, else
ifruns a block when its condition is True.elifis checked only if earlier conditions were False.elseruns when none matched. Blocks are indented and conditions end with a colon.- Separate
ifstatements are each checked; anif/elif/elsechain runs at most one block.
Logic
andneeds both True;orneeds at least one True;notflips a value. Order:not,and,or.- Truth tables list all input combinations (2 to the n rows for n inputs). De Morgan:
not (A and B)equals(not A) or (not B).
temp = 30
if temp > 25 and temp < 35:
print("warm")
else:
print("other")
This prints warm.
Topics in this unit
Each topic has its own short notes and practice.
Practice
print(5 <= 5) display?5 is equal to 5, so "less than or equal" is True.
print(True or False) display?or is True when at least one side is True.
x = 10, which value does print(x > 3 and x < 8) produce?x < 8 is False, so the and is False.
if age < 13: then prints "child", elif age < 20: then prints "teen", else: prints "adult". What prints for age = 13?13 < 13 is False, 13 < 20 is True, so it prints teen.
not (a or b)?De Morgan: negating an or gives an and of the negations.
2 x 2 = 4 combinations.
Free response
Write your answer first, then open the scoring guide.
Free-response question
A theme park sets ticket prices by age. Children under 5 are free, ages 5 through 17 pay 10, and everyone 18 or older pays 15.
(a) Write an if/elif/else chain in Python that sets a variable price for a variable age.
Show the answer and scoring guide
if age < 5:
price = 0
elif age <= 17:
price = 10
else:
price = 15
Check off the points you earned:
(b) What is the value of price when age is 17? Explain which condition is the first to be True.
Show the answer and scoring guide
price is 10. age < 5 is False, and age <= 17 is True, so that block runs and the rest are skipped.
Check off the points you earned:
(c) Write one Boolean expression that is True when a visitor is eligible for the child price of 10.
Show the answer and scoring guide
age >= 5 and age <= 17
Check off the points you earned: