In [ ]:
# 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() and math.isclose()
  • Create and use boolean values (True/False)
  • Write if, if-else, and if-elif-else statements
  • Combine conditions using and, or, and not

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.

In [ ]:
# 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-else chains
  • 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.

In [ ]:
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.

In [ ]:
# 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
In [ ]:
# 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:

  1. points_per_question - How many points each question gets (use floor division)
  2. extra_points - How many points are left over (use modulo)
In [ ]:
# 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}")
In [ ]:
grader.check("q1_floor_division_modulo")

2.2 Exponentiation (**)

The ** operator raises a number to a power. It can also calculate roots!

In [ ]:
# Basic exponentiation
print(f"2 squared: {2**2}")  # 4
print(f"2 cubed: {2**3}")  # 8
print(f"10 squared: {10**2}")  # 100
In [ ]:
# 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.

In [ ]:
# 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}")
In [ ]:
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!

In [ ]:
# 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!
In [ ]:
# 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
In [ ]:
# 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.

  1. Calculate quiz_average as the sum of the three scores divided by 3
  2. Create averages_match - a boolean that is True if quiz_average is close to expected_average using math.isclose()
In [ ]:
# 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}")
In [ ]:
grader.check("q3_floating_point")

3. Booleans and Relational Operators

3.1 Boolean Values

A boolean is a value that is either True or False. That's it - only two possible values!

Booleans are the foundation of decision-making in code.

In [ ]:
# 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)!

In [ ]:
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:

  1. is_passing - True if exam_score is 60 or above
  2. is_grade_a - True if exam_score is 90 or above
  3. needs_retest - True if exam_score is below 70
In [ ]:
# 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}")
In [ ]:
grader.check("q4_boolean_comparisons")

Question 5: Comparing Two Scores (1 point)

Compare two students' exam scores and create these boolean variables:

  1. student1_higher - True if student 1's score is higher than student 2's
  2. scores_equal - True if both scores are the same
  3. both_passing - True if BOTH scores are 60 or above (hint: use and)
In [ ]:
# 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}")
In [ ]:
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 after else
  • Indentation (4 spaces) defines what's inside each block
  • Only ONE block runs - never both!
In [ ]:
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)
In [ ]:
# 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 result to "Pass" if test_score is 60 or above
  • Sets result to "Fail" otherwise
In [ ]:
# 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}")
In [ ]:
grader.check("q6_basic_if_else")

Question 7: if-else with Feedback (1 point)

Write an if-else statement that:

  • Sets feedback to "Excellent work!" if assignment_score is 90 or above
  • Sets feedback to "Keep practicing!" otherwise
In [ ]:
# Given value (do not change)
assignment_score = 95

# ✏️ YOUR CODE HERE
...
    feedback = ...
...
    feedback = ...

print(f"Score {assignment_score}: {feedback}")
In [ ]:
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!

In [ ]:
# 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:

In [ ]:
# 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}")
In [ ]:
# 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"
In [ ]:
# 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}")
In [ ]:
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"
In [ ]:
# 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}")
In [ ]:
grader.check("q9_attendance_category")

6. Logical Operators: and, or, not

Sometimes you need to combine multiple conditions. That's where logical operators come in!

6.1 The and Operator

Both conditions must be True for the result to be True.

A B A and B
True True True
True False False
False True False
False False False
In [ ]:
# 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)
In [ ]:
# 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
In [ ]:
# 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)
In [ ]:
# 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)

6.3 The not Operator

Flips True to False and False to True.

A not A
True False
False True
In [ ]:
demo_passing = True
demo_failing = not demo_passing

print(f"Is passing: {demo_passing}")
print(f"Is failing: {demo_failing}")  # False
In [ ]:
# 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!

In [ ]:
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:

  1. makes_honor_roll - True if the student has BOTH an excellent score (90+) AND near-perfect attendance (95%+)
  2. has_academic_warning - True if the student is failing (below 60) OR has poor attendance (below 70%)
In [ ]:
# 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}")
In [ ]:
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 weight
  • if dim_weight > weight_lbs: - comparison and if-else
  • if billable_weight <= 1: ... elif ... else - if-elif-else chain
  • is_member and base_cost > 10 - combining conditions with and
  • length > 48 or width > 48 or height > 48 - combining with or
  • not is_express - using not
  • round(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:

  1. Calculate final_score: (exam average × 0.8) + (attendance × 0.2)
  2. Determine letter_grade using if-elif-else (A: 90+, B: 80+, C: 70+, D: 60+, F: below 60)
  3. Set honor_roll to True if final_score >= 90 AND attendance_pct >= 95
  4. Set academic_warning to True if final_score < 60 OR attendance_pct < 70
In [ ]:
# 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}")
In [ ]:
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

  1. Comparisons produce booleans - Every <, >, ==, etc. gives you True or False
  2. if-else lets code branch - Different code runs based on conditions
  3. Order matters in if-elif-else - Check the most specific condition first
  4. and requires both - Both sides must be True
  5. or requires one - At least one side must be True
  6. 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.

In [ ]:
grader.check_all()