Sign in

Intro to Computer Science

Unit 5

Conditionals and Boolean Logic

5 topics · 21 practice questions · Free responseNot yet reviewed

Notes

Booleans and comparisons

  • A Boolean is True or False. Comparison operators: ==, !=, <, >, <=, >=. Remember = assigns and == compares.

If, elif, else

  • if runs a block when its condition is True. elif is checked only if earlier conditions were False. else runs when none matched. Blocks are indented and conditions end with a colon.
  • Separate if statements are each checked; an if/elif/else chain runs at most one block.

Logic

  • and needs both True; or needs at least one True; not flips 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

What does print(5 <= 5) display?
What does print(True or False) display?
With x = 10, which value does print(x > 3 and x < 8) produce?
A program checks if age < 13: then prints "child", elif age < 20: then prints "teen", else: prints "adult". What prints for age = 13?
Which expression is equivalent to not (a or b)?
How many rows are needed in a truth table with 2 inputs?

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: