# Initialize Otter
import otter
grader = otter.Notebook("03_decision_structures_boolean_logic.ipynb")
Decision Structures and Boolean Logic¶
Goal: Learn to make decisions in code using if/else statements, relational operators, and logical operators. Includes a review of less-intuitive arithmetic operators.
By the end of this notebook, you will be able to:
- Use floor division (
//), modulo (%), and exponentiation (**) - Handle floating-point precision issues with
round()andmath.isclose() - Create and use boolean values (
True/False) - Write
if,if-else, andif-elif-elsestatements - Combine conditions using
and,or, andnot
Reference: You can look back at 02_python_basics.ipynb from lecture for syntax help!
Important: Run cells in order from top to bottom. Later questions use variables from earlier questions.
# Validation: Check Python version and file location
import math
import os
import sys
# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if current_version not in SUPPORTED_VERSIONS:
raise EnvironmentError(
f"Python version mismatch!\n"
f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
f"Found: {current_version}\n"
f"Please use Python 3.12 or 3.13 for this course."
)
print(f"Python version: {current_version}")
# Expected filename for this assignment
EXPECTED_FILE = "03_decision_structures_boolean_logic.ipynb"
# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)
if required_path_segment not in current_path and not in_allowed_env:
raise EnvironmentError(
f"File location error!\n"
f"This notebook should be in: ~/Documents/CSC115/lecture_notebooks/\n"
f"Current location: {current_path}\n"
f"Please move this file to the correct directory."
)
# Verify directory name and filename (skip in grading/development environments)
if not in_allowed_env:
if not os.path.exists(EXPECTED_FILE):
notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
raise EnvironmentError(
f"Filename mismatch!\n"
f"Expected: {EXPECTED_FILE}\n"
f"Found notebooks: {notebooks}\n"
f"Please rename your notebook to '{EXPECTED_FILE}'."
)
print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
1. The Big Picture¶
Before we dive into individual concepts, let's see what you'll be able to understand by the end of this notebook. Here's a complete shipping calculator that uses all the concepts we'll learn today:
- Floor division (
//) - Comparisons (
>,<=,==) if-elif-elsechains- Logical operators (
and,or,not) round()for clean output
Don't worry if you don't understand it all yet! By the end of this notebook, every line will make sense.
def calculate_shipping(weight_lbs, length, width, height, is_express, is_member):
"""Calculate shipping cost with dimensional weight and discounts."""
# Calculate dimensional weight (volume / 139 for domestic shipping)
volume = length * width * height
dim_weight = volume // 139 # Floor division gives whole pounds
# Use the greater of actual weight or dimensional weight
if dim_weight > weight_lbs:
billable_weight = dim_weight
weight_type = "Dimensional"
else:
billable_weight = weight_lbs
weight_type = "Actual"
# Determine shipping tier based on billable weight
if billable_weight <= 1:
tier = "Light"
base_cost = 5.99
elif billable_weight <= 5:
tier = "Standard"
base_cost = 9.99
elif billable_weight <= 20:
tier = "Medium"
base_cost = 15.99
else:
tier = "Heavy"
base_cost = 24.99 + (billable_weight - 20) * 0.50
# Express shipping multiplier
if is_express:
base_cost = base_cost * 2.5
# Member discount (10% off, but only if order is over $10)
qualifies_for_discount = is_member and base_cost > 10
if qualifies_for_discount:
base_cost = base_cost * 0.9
# Check for oversized surcharge (any dimension over 48 inches)
is_oversized = length > 48 or width > 48 or height > 48
if is_oversized:
base_cost = base_cost + 15.00
# Round to avoid floating-point display issues
final_cost = round(base_cost, 2)
# Free shipping check
free_shipping = is_member and not is_express and billable_weight <= 5
return tier, weight_type, final_cost, is_oversized, free_shipping
# Example usage - try changing the values!
result = calculate_shipping(
weight_lbs=3, length=12, width=10, height=8, is_express=False, is_member=True
)
print(f"Tier: {result[0]}")
print(f"Weight Type: {result[1]}")
print(f"Cost: ${result[2]}")
print(f"Oversized: {result[3]}")
print(f"Free Shipping: {result[4]}")
Now let's learn each piece!
We'll build a grade calculator system through the exercises, applying each concept as we learn it.
2. Arithmetic Review¶
You already know +, -, *, and /. Let's learn three more operators that are incredibly useful.
2.1 Floor Division (//) and Modulo (%)¶
Floor division (//) divides and rounds DOWN to the nearest whole number.
Modulo (%) gives you the REMAINDER after division.
# Floor division: How many COMPLETE groups?
total_assignments = 23
group_size = 5
# What is the arithmetic division value?
simple_division = total_assignments / group_size
print(f"Simple division: {simple_division}\n")
complete_groups = total_assignments // group_size
print(f"{total_assignments} assignments in groups of {group_size}:")
print(f" Complete groups: {complete_groups}") # 4
# Modulo: How many LEFT OVER?
leftover = total_assignments % group_size
print(f" Leftover: {leftover}") # 3
# Common use: Check if a number is even or odd
student_id = 12345
# If student_id % 2 equals 0, it's even
remainder = student_id % 2
print(f"Student ID {student_id} divided by 2 has remainder: {remainder}")
print(f"Is it even? {remainder == 0}") # False (12345 is odd)
Question 1: Floor Division and Modulo (1 point)¶
A professor has total_points = 47 points to distribute across questions = 5 questions.
Calculate:
points_per_question- How many points each question gets (use floor division)extra_points- How many points are left over (use modulo)
# Given values (do not change)
total_points = 47
questions = 5
# ✏️ YOUR CODE HERE
points_per_question = ...
extra_points = ...
print(f"Each question gets {points_per_question} points")
print(f"Extra points remaining: {extra_points}")
grader.check("q1_floor_division_modulo")
2.2 Exponentiation (**)¶
The ** operator raises a number to a power. It can also calculate roots!
# Basic exponentiation
print(f"2 squared: {2**2}") # 4
print(f"2 cubed: {2**3}") # 8
print(f"10 squared: {10**2}") # 100
# Square root using ** 0.5
# Grade curve formula: take square root and multiply by 10
raw_score = 64
curved_score = raw_score**0.5 * 10
print(f"Raw score: {raw_score}")
print(f"Curved score: {curved_score}") # 80.0
Question 2: Exponentiation and Rounding (1 point)¶
Apply a grade curve to raw_score using this formula:
- Take the square root of the raw score (
** 0.5) - Multiply by 10
- Round to 1 decimal place using
round(value, 1)
Store the result in curved_score.
# Given value (do not change)
raw_score = 72
# ✏️ YOUR CODE HERE
# Calculate: square root of raw_score, multiply by 10, round to 1 decimal
curved_score = ...
print(f"Raw: {raw_score} -> Curved: {curved_score}")
grader.check("q2_exponentiation")
2.3 Floating-Point Precision¶
Computers store decimal numbers in binary, which can lead to tiny precision errors. This is not a bug - it's how computers work!
# The problem: this should be 0.3, right?
result = 0.1 + 0.1 + 0.1
print(f"0.1 + 0.1 + 0.1 = {result}")
# This comparison FAILS!
print(f"Is it equal to 0.3? {result == 0.3}") # False!
# Solution 1: round() for display and storage
grade_avg = 89.66666666666667
display_grade = round(grade_avg, 2)
print(f"Display grade: {display_grade}") # 89.67
# Solution 2: math.isclose() for comparisons
result = 0.1 + 0.1 + 0.1
# Instead of: result == 0.3 (which fails!)
# Use: math.isclose(result, 0.3)
print(f"Using ==: {result == 0.3}") # False
print(f"Using math.isclose(): {math.isclose(result, 0.3)}") # True!
Question 3: Floating-Point Comparison (1 point)¶
A student has three quiz scores with decimal values. Calculate their average and check if it equals the expected value.
Warning: Because of floating-point precision issues, using == to compare the average will fail! You must use math.isclose() instead.
- Calculate
quiz_averageas the sum of the three scores divided by 3 - Create
averages_match- a boolean that isTrueifquiz_averageis close toexpected_averageusingmath.isclose()
# Given values (do not change)
quiz1 = 87.5
quiz2 = 92.3
quiz3 = 78.7
expected_average = (
86.16666666666667 # The "true" average - but == comparison will fail!
)
# ✏️ YOUR CODE HERE
quiz_average = ...
averages_match = ...
print(f"Quiz average: {quiz_average}")
print(f"Expected: {expected_average}")
print(
f"Match using ==: {quiz_average == expected_average}"
) # False! Floating-point issue
print(f"Match using math.isclose(): {averages_match}")
grader.check("q3_floating_point")
# Creating boolean variables directly
is_enrolled = True
has_paid_tuition = False
print(f"Enrolled: {is_enrolled}")
print(f"Paid: {has_paid_tuition}")
print(f"Type: {type(is_enrolled)}") # <class 'bool'>
3.2 Relational Operators¶
Comparisons return boolean values:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 85 == 85 |
True |
!= |
Not equal to | 85 != 90 |
True |
< |
Less than | 85 < 90 |
True |
> |
Greater than | 85 > 90 |
False |
<= |
Less than or equal | 85 <= 85 |
True |
>= |
Greater than or equal | 85 >= 60 |
True |
Important: Use == for comparison, not = (which is assignment)!
score = 75
passing_threshold = 60
# Each comparison produces a boolean
is_passing = score >= passing_threshold
is_perfect = score == 100
needs_improvement = score < 70
is_not_zero = score != 0
print(f"Score: {score}")
print(f"Is passing (>= 60)? {is_passing}") # True
print(f"Is perfect (== 100)? {is_perfect}") # False
print(f"Needs improvement (< 70)? {needs_improvement}") # False
print(f"Is not zero (!= 0)? {is_not_zero}") # True
Question 4: Boolean Comparisons (1 point)¶
Given a student's exam_score, create three boolean variables:
is_passing-Trueif exam_score is 60 or aboveis_grade_a-Trueif exam_score is 90 or aboveneeds_retest-Trueif exam_score is below 70
# Given value (do not change)
exam_score = 82
# ✏️ YOUR CODE HERE
is_passing = ...
is_grade_a = ...
needs_retest = ...
print(f"Score: {exam_score}")
print(f"Is passing: {is_passing}")
print(f"Is A grade: {is_grade_a}")
print(f"Needs retest: {needs_retest}")
grader.check("q4_boolean_comparisons")
Question 5: Comparing Two Scores (1 point)¶
Compare two students' exam scores and create these boolean variables:
student1_higher-Trueif student 1's score is higher than student 2'sscores_equal-Trueif both scores are the sameboth_passing-Trueif BOTH scores are 60 or above (hint: useand)
# Given values (do not change)
student1_score = 88
student2_score = 75
# ✏️ YOUR CODE HERE
student1_higher = ...
scores_equal = ...
both_passing = ...
print(f"Student 1: {student1_score}, Student 2: {student2_score}")
print(f"Student 1 higher: {student1_higher}")
print(f"Scores equal: {scores_equal}")
print(f"Both passing: {both_passing}")
grader.check("q5_comparing_scores")
4. if-else Statements¶
Now we can make our code do different things based on conditions!
4.1 Basic if-else Structure¶
if condition:
# This code runs if condition is True
else:
# This code runs if condition is False
Key syntax:
- Colon (
:) after the condition and afterelse - Indentation (4 spaces) defines what's inside each block
- Only ONE block runs - never both!
score = 75
if score >= 60:
status = "PASS"
message = "Congratulations!"
else:
status = "FAIL"
message = "See instructor for retake options."
print(f"Score: {score}")
print(f"Status: {status}")
print(message)
# Try changing the score to see different output!
score = 55
if score >= 60:
status = "PASS"
else:
status = "FAIL"
print(f"Score {score}: {status}")
Question 6: Basic if-else (1 point)¶
Write an if-else statement that:
- Sets
resultto"Pass"iftest_scoreis 60 or above - Sets
resultto"Fail"otherwise
# Given value (do not change)
test_score = 65
# ✏️ YOUR CODE HERE
# Write an if-else statement that sets result to "Pass" if test_score >= 60, otherwise "Fail"
result = ...
print(f"Score {test_score}: {result}")
grader.check("q6_basic_if_else")
Question 7: if-else with Feedback (1 point)¶
Write an if-else statement that:
- Sets
feedbackto"Excellent work!"ifassignment_scoreis 90 or above - Sets
feedbackto"Keep practicing!"otherwise
# Given value (do not change)
assignment_score = 95
# ✏️ YOUR CODE HERE
...
feedback = ...
...
feedback = ...
print(f"Score {assignment_score}: {feedback}")
grader.check("q7_if_else_feedback")
5. if-elif-else Chains¶
What if you need more than two options? Use elif (short for "else if")!
5.1 Multiple Conditions¶
if condition1:
# runs if condition1 is True
elif condition2:
# runs if condition1 is False AND condition2 is True
elif condition3:
# runs if condition1 and condition2 are False AND condition3 is True
else:
# runs if ALL conditions are False
Important: Conditions are checked from top to bottom. The FIRST True condition wins!
# Temperature description based on degrees Fahrenheit
temperature = 72
if temperature >= 90:
description = "Hot"
elif temperature >= 75:
description = "Warm"
elif temperature >= 55:
description = "Cool"
elif temperature >= 32:
description = "Cold"
else:
description = "Freezing"
print(f"Temperature: {temperature}°F = {description}")
Order Matters!¶
Watch what happens if we check conditions in the wrong order:
# WRONG - Don't do this!
temperature = 95
if temperature >= 32: # 95 >= 32 is True!
description = "Cold" # So we get Cold, even though 95 is Hot!
elif temperature >= 55:
description = "Cool"
elif temperature >= 75:
description = "Warm"
elif temperature >= 90:
description = "Hot" # Never reached!
else:
description = "Freezing"
print(f"WRONG order: {temperature}°F = {description}")
# CORRECT - Check highest threshold first
temperature = 95
if temperature >= 90: # 95 >= 90 is True!
description = "Hot" # Correct!
elif temperature >= 75:
description = "Warm"
elif temperature >= 55:
description = "Cool"
elif temperature >= 32:
description = "Cold"
else:
description = "Freezing"
print(f"CORRECT order: {temperature}°F = {description}")
Question 8: Letter Grade Calculator (1 point)¶
Write an if-elif-else chain that assigns calculated_grade based on numeric_score:
| Score | Grade |
|---|---|
| 90+ | "A" |
| 80-89 | "B" |
| 70-79 | "C" |
| 60-69 | "D" |
| Below 60 | "F" |
# Given value (do not change)
numeric_score = 73
# ✏️ YOUR CODE HERE
# Write an if-elif-else chain that sets calculated_grade to "A", "B", "C", "D", or "F"
# A: 90+, B: 80-89, C: 70-79, D: 60-69, F: below 60
...
...
...
...
...
print(f"Score {numeric_score} = Grade {calculated_grade}")
grader.check("calculated_grade")
Question 9: Attendance Category (1 point)¶
Write an if-elif-else chain that assigns attendance_status based on class_attendance:
| Attendance | Status |
|---|---|
| 95% or above | "Excellent" |
| 80-94% | "Good" |
| Below 80% | "Needs Improvement" |
# Given value (do not change)
class_attendance = 87
# ✏️ YOUR CODE HERE
# Write an if-elif-else chain that sets attendance_status
# "Excellent" for 95%+, "Good" for 80-94%, "Needs Improvement" for below 80%
...
...
...
print(f"Attendance {class_attendance}%: {attendance_status}")
grader.check("q9_attendance_category")
# Honor roll requires BOTH high score AND high attendance
score = 92
attendance = 98
honor_roll = score >= 90 and attendance >= 95
print(f"Score: {score}, Attendance: {attendance}%")
print(f"Honor roll: {honor_roll}") # True (both conditions met)
# What if attendance drops?
score = 92
attendance = 80
honor_roll = score >= 90 and attendance >= 95
print(f"Score: {score}, Attendance: {attendance}%")
print(f"Honor roll: {honor_roll}") # False (attendance too low)
6.2 The or Operator¶
At least ONE condition must be True for the result to be True.
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
# Academic warning if EITHER score OR attendance is low
score = 55
attendance = 90
academic_warning = score < 60 or attendance < 70
print(f"Score: {score}, Attendance: {attendance}%")
print(f"Academic warning: {academic_warning}") # True (score is low)
# What if both are fine?
score = 75
attendance = 90
academic_warning = score < 60 or attendance < 70
print(f"Score: {score}, Attendance: {attendance}%")
print(f"Academic warning: {academic_warning}") # False (both OK)
demo_passing = True
demo_failing = not demo_passing
print(f"Is passing: {demo_passing}")
print(f"Is failing: {demo_failing}") # False
# Useful for readability
has_completed_prerequisites = False
if not has_completed_prerequisites:
print("Please complete prerequisites first.")
6.4 Combining Operators¶
You can combine and, or, and not in the same expression. Use parentheses to make it clear!
score = 88
attendance = 92
has_completed_hw = True
# Dean's list: high score AND high attendance AND completed homework
deans_list = (score >= 85 and attendance >= 90) and has_completed_hw
print(f"Dean's list: {deans_list}") # True
# Needs intervention: failing OR (low attendance AND missing homework)
needs_intervention = score < 60 or (attendance < 70 and not has_completed_hw)
print(f"Needs intervention: {needs_intervention}") # False
Question 10: Honor Roll and Academic Warning (1 point)¶
Using the given semester_score and semester_attendance, create two boolean variables:
makes_honor_roll-Trueif the student has BOTH an excellent score (90+) AND near-perfect attendance (95%+)has_academic_warning-Trueif the student is failing (below 60) OR has poor attendance (below 70%)
# Given values (do not change)
semester_score = 92
semester_attendance = 97
# ✏️ YOUR CODE HERE
makes_honor_roll = ...
has_academic_warning = ...
print(f"Score: {semester_score}, Attendance: {semester_attendance}%")
print(f"Honor roll: {makes_honor_roll}")
print(f"Academic warning: {has_academic_warning}")
grader.check("q10_logical_operators")
7. Putting It All Together¶
Now you understand all the pieces! Let's go back to our shipping calculator and see how it all fits together.
Look at the code at the top of this notebook again - every line should make sense now:
volume // 139- floor division for dimensional weightif dim_weight > weight_lbs:- comparison and if-elseif billable_weight <= 1:...elif...else- if-elif-else chainis_member and base_cost > 10- combining conditions withandlength > 48 or width > 48 or height > 48- combining withornot is_express- usingnotround(base_cost, 2)- handling floating-point
Question 11: Complete Grade Report - STRETCH GOAL (1 bonus point)¶
Build a complete grade calculator! Given three exam scores and an attendance percentage:
- Calculate
final_score: (exam average × 0.8) + (attendance × 0.2) - Determine
letter_gradeusing if-elif-else (A: 90+, B: 80+, C: 70+, D: 60+, F: below 60) - Set
honor_rolltoTrueif final_score >= 90 AND attendance_pct >= 95 - Set
academic_warningtoTrueif final_score < 60 OR attendance_pct < 70
# Given values (do not change)
exam1 = 88
exam2 = 92
exam3 = 85
attendance_pct = 96
# ✏️ YOUR CODE HERE
# Step 1: Calculate final score
exam_average = ...
final_score = ...
# Step 2: Determine letter grade
...
letter_grade = ...
...
letter_grade = ...
...
letter_grade = ...
...
letter_grade = ...
...
letter_grade = ...
# Step 3: Honor roll check
honor_roll = ...
# Step 4: Academic warning check
academic_warning = ...
# Display results
print(f"Exams: {exam1}, {exam2}, {exam3}")
print(f"Attendance: {attendance_pct}%")
print(f"Final Score: {round(final_score, 2)}")
print(f"Letter Grade: {letter_grade}")
print(f"Honor Roll: {honor_roll}")
print(f"Academic Warning: {academic_warning}")
grader.check("q11_integration")
Summary¶
Congratulations! You've learned how to make decisions in Python!
| Concept | Syntax | Example |
|---|---|---|
| Floor division | // |
23 // 5 → 4 |
| Modulo (remainder) | % |
23 % 5 → 3 |
| Exponent | ** |
2 ** 3 → 8 |
| Float comparison | math.isclose(a, b) |
math.isclose(0.1+0.2, 0.3) → True |
| Boolean values | True, False |
is_valid = True |
| Equal | == |
x == 5 |
| Not equal | != |
x != 5 |
| Less/greater | <, >, <=, >= |
x >= 60 |
| if-else | if cond: / else: |
See examples |
| if-elif-else | elif cond: |
See examples |
| Logical AND | and |
a and b |
| Logical OR | or |
a or b |
| Logical NOT | not |
not a |
Key Takeaways¶
- Comparisons produce booleans - Every
<,>,==, etc. gives youTrueorFalse - if-else lets code branch - Different code runs based on conditions
- Order matters in if-elif-else - Check the most specific condition first
andrequires both - Both sides must beTrueorrequires one - At least one side must beTrue- Use parentheses - Make complex conditions clear!
You have completed the Decision Structures and Boolean Logic notebook!
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()