Skip to main content

Lesson 10: Expressions and Operators

Review Python basics—variables, numbers, strings, booleans, and type conversion—then learn operators to build expressions that solve architectural problems.

Introduction

You've spent the last five lessons learning the building blocks: variables, numbers, strings, booleans, and type conversion.

You've already been writing expressions without realising it.

Every time you wrote floor_count * floor_height or room_name + " " + str(room_number), you were writing an expression, a combination of values, variables, and operators that produces a result.

This lesson ties everything together. We'll review what you've learned, introduce a few operators you haven't seen yet, and show you how to build complex expressions that solve real architectural problems.

Think of this as your checkpoint before moving forward.


Lesson Overview

This section contains a general overview of topics you will learn in this lesson.

  • Review all operators you've learned so far
  • Understand operator precedence (order of operations)
  • Learn compound assignment operators (+=, -=, *=, /=)
  • Use the walrus operator (:=) for inline assignment
  • Master chaining comparisons
  • Build complex architectural calculations
  • Recognise when expressions become too complex

What Is an Expression?

An expression is any valid combination of values, variables, and operators that produces a result.

Simple expressions:

5 + 3                    # Result: 8
floor_count              # Result: value of floor_count
"A" + "-" + "101"       # Result: "A-101"

Complex expressions:

ground_floor_height + (floor_count - 1) * typical_floor_height

Key point: Every expression evaluates to a single value.


Operators You've Already Learned

Let's review what you already know.

Arithmetic Operators

a + b    # Addition
a - b    # Subtraction
a * b    # Multiplication
a / b    # Division (always returns float)
a // b   # Floor division (returns integer)
a % b    # Modulo (remainder)
a ** b   # Exponentiation (a to the power of b)

You've used these for building height calculations, area computations, and budget math.

Comparison Operators

a > b     # Greater than
a < b     # Less than
a >= b    # Greater than or equal
a <= b    # Less than or equal
a == b    # Equal to
a != b    # Not equal to

You've used these for compliance checks and validation.

Logical Operators

a and b   # Both must be True
a or b    # At least one must be True
not a     # Reverses the boolean

You've used these for multi-condition checks.

String Operators

a + b     # Concatenation
a * n     # Repetition

You've used these for building sheet names and file paths.


Operator Precedence (The Rules)

When you write complex expressions, Python needs to know what order to evaluate them.

Full precedence order (highest to lowest):

  1. * (Exponentiation)
  2. +xxnot x (Unary plus, minus, not)
  3. ///% (Multiplication, division, floor division, modulo)
  4. +,  (Addition, subtraction)
  5. <<=>>===!= (Comparisons)
  6. and (Logical AND)
  7. or (Logical OR)

Example: Order Matters

# Without parentheses
result = 10 + 5 * 2
print(result)  # Output: 20 (not 30)
# Evaluates as: 10 + (5 * 2)

# With parentheses
result = (10 + 5) * 2
print(result)  # Output: 30

Architectural Example: Building Height

ground_floor_height = 4.5
typical_floor_height = 3.2
floor_count = 12

# Wrong (without parentheses)
total_height = ground_floor_height + floor_count * typical_floor_height
print(total_height)  # Output: 42.9
# This calculates: 4.5 + (12 * 3.2) = 4.5 + 38.4

# Correct (with parentheses)
typical_floors = floor_count - 1
total_height = ground_floor_height + typical_floors * typical_floor_height
print(total_height)  # Output: 39.7
# This calculates: 4.5 + (11 * 3.2) = 4.5 + 35.2

Best Practice: When in doubt, use parentheses. They make your intent clear and prevent bugs.


New Operators: Compound Assignment

You've been writing code like this:

floor_count = 8
floor_count = floor_count + 1
print(floor_count)  # Output: 9

There's a shorter way:

floor_count = 8
floor_count += 1
print(floor_count)  # Output: 9

+= is a compound assignment operator. It adds to the variable and reassigns in one step.

All Compound Assignment Operators

x += 5    # Same as: x = x + 5
x -= 3    # Same as: x = x - 3
x *= 2    # Same as: x = x * 2
x /= 4    # Same as: x = x / 4
x //= 2   # Same as: x = x // 2
x %= 3    # Same as: x = x % 3
x **= 2   # Same as: x = x ** 2

Architectural Example: Running Totals

# Calculating total area across multiple floors
total_area = 0

# Floor 1
total_area += 450.5

# Floor 2
total_area += 480.2

# Floor 3
total_area += 465.8

print(total_area)  # Output: 1396.5

This is especially useful when accumulating values in loops (which you'll learn in the next module).

String Concatenation with +=

sheet_name = "A-101"
sheet_name += " Ground Floor Plan"
print(sheet_name)  # Output: A-101 Ground Floor Plan

# Same as:
sheet_name = sheet_name + " Ground Floor Plan"

Chaining Comparisons

Python lets you chain comparison operators in a way that reads naturally.

Standard Way (Verbose)

room_area = 420

# Check if area is between 400 and 500
is_valid = room_area >= 400 and room_area <= 500
print(is_valid)  # Output: True

Chained Way (Cleaner)

room_area = 420

# Check if area is between 400 and 500
is_valid = 400 <= room_area <= 500
print(is_valid)  # Output: True

This reads like math notation: "400 is less than or equal to room_area, which is less than or equal to 500."

Architectural Example: Code Compliance Range

ceiling_height = 2.8

# Habitable rooms must be between 2.4m and 3.0m
is_compliant = 2.4 <= ceiling_height <= 3.0
print(is_compliant)  # Output: True

# Multiple rooms
rooms = [
    {"name": "Office 1", "height": 2.8},
    {"name": "Office 2", "height": 2.3},
    {"name": "Office 3", "height": 3.1}
]

for room in rooms:
    height = room["height"]
    is_valid = 2.4 <= height <= 3.0

    if is_valid:
        print(f"{room['name']}: PASS")
    else:
        print(f"{room['name']}: FAIL - height {height}m")

# Output:
# Office 1: PASS
# Office 2: FAIL - height 2.3m
# Office 3: FAIL - height 3.1m

The Walrus Operator (:=) — Assignment in Expressions

Note: This is a newer Python feature (3.8+). It's optional but useful.

Sometimes you want to assign a value and use it in the same expression.

Without Walrus Operator

building_height = 35.7
floor_height = 3.2

floor_count = building_height / floor_height

if floor_count > 10:
    print(f"Building has {floor_count} floors")

With Walrus Operator

building_height = 35.7
floor_height = 3.2

if (floor_count := building_height / floor_height) > 10:
    print(f"Building has {floor_count} floors")

The walrus operator := assigns the result to floor_count AND uses it in the comparison.

When to use it: When you need a value for both a check and later use.

When not to use it: When it makes code less readable. Clarity > brevity.


The in Operator (Membership)

Check if a value exists in a string or collection.

In Strings

sheet_name = "A-101 Ground Floor Plan"

if "Floor" in sheet_name:
    print("This is a floor plan")

if "Ceiling" not in sheet_name:
    print("This is not a ceiling plan")

Architectural Example: Filtering Sheets

sheet_names = [
    "A-101 Floor Plan",
    "A-102 Floor Plan",
    "A-201 Ceiling Plan",
    "S-101 Foundation Plan"
]

# Find all floor plans
floor_plans = []
for sheet in sheet_names:
    if "Floor" in sheet:
        floor_plans.append(sheet)

print(floor_plans)
# Output: ['A-101 Floor Plan', 'A-102 Floor Plan', 'S-101 Foundation Plan']

You'll use in extensively when working with lists (next module).


The is Operator (Identity)

is checks if two variables point to the exact same object in memory.

For most architectural work, you'll use == (equality) not is (identity).

# Checking for None (special value)
room_name = None

if room_name is None:
    print("Room has no name")

# Don't use 'is' for numbers or strings
floor_count = 12
if floor_count is 12:  # This works but is bad practice
    print("Twelve floors")

# Use == instead
if floor_count == 12:  # Correct
    print("Twelve floors")

Rule of thumb: Use is only for checking None. Use == for everything else.


Building Complex Expressions

Now let's combine everything into real architectural calculations.

Example 1: Floor Area Ratio with Validation

site_area = 2000.0
gross_floor_area = 8500.0
max_far = 5.0

# Calculate FAR and check if compliant
far = gross_floor_area / site_area
is_compliant = far <= max_far

print(f"FAR: {far}")
print(f"Max FAR: {max_far}")
print(f"Compliant: {is_compliant}")

# Output:
# FAR: 4.25
# Max FAR: 5.0
# Compliant: True

Example 2: Budget Breakdown with Percentages

total_budget = 5000000
design_percentage = 15
construction_percentage = 75
contingency_percentage = 10

# Calculate allocations
design_budget = total_budget * (design_percentage / 100)
construction_budget = total_budget * (construction_percentage / 100)
contingency_budget = total_budget * (contingency_percentage / 100)

# Verify totals
total_allocated = design_budget + construction_budget + contingency_budget

print(f"Design: ${design_budget:,.0f}")
print(f"Construction: ${construction_budget:,.0f}")
print(f"Contingency: ${contingency_budget:,.0f}")
print(f"Total: ${total_allocated:,.0f}")

# Output:
# Design: $750,000
# Construction: $3,750,000
# Contingency: $500,000
# Total: $5,000,000

Example 3: Multi-Condition Room Validation

# Room requirements
room_area = 420
ceiling_height = 2.8
has_windows = True
is_basement = False

# Minimum requirements
min_area = 400
min_height = 2.7

# Complex validation
area_ok = room_area >= min_area
height_ok = ceiling_height >= min_height
natural_light_ok = has_windows or not is_basement

is_habitable = area_ok and height_ok and natural_light_ok

print(f"Area OK: {area_ok}")
print(f"Height OK: {height_ok}")
print(f"Natural Light OK: {natural_light_ok}")
print(f"Habitable: {is_habitable}")

# Output:
# Area OK: True
# Height OK: True
# Natural Light OK: True
# Habitable: True

When Expressions Become Too Complex

Complex expressions are powerful, but they can become unreadable.

Too Complex (Hard to Read)

result = (site_area * 0.6 + parking_area * 0.4) / (total_floors - basement_floors + penthouse_floors * 1.5) if total_floors > 5 and has_parking else site_area / total_floors

Better (Broken Down)

if total_floors > 5 and has_parking:
    weighted_area = site_area * 0.6 + parking_area * 0.4
    adjusted_floors = total_floors - basement_floors + penthouse_floors * 1.5
    result = weighted_area / adjusted_floors
else:
    result = site_area / total_floors

Best Practice: If an expression spans more than one line or requires mental effort to parse, break it down into smaller steps with descriptive variable names.


The Pain vs The Python Fix

The Pain: Manually calculating building metrics. Every dimension change means recalculating everything by hand or in multiple spreadsheet cells.

The Python Fix: Write the expression once. Change one input, everything updates.

# Define once
ground_floor_height = 4.5
typical_floor_height = 3.2
floor_count = 12
floor_area = 450.0

# Calculate automatically
typical_floors = floor_count - 1
total_height = ground_floor_height + (typical_floors * typical_floor_height)
total_area = floor_count * floor_area
average_height = total_height / floor_count

print(f"Total height: {total_height}m")
print(f"Total area: {total_area}m²")
print(f"Average floor height: {average_height}m")

# Change floor count
floor_count = 18

# Recalculate
typical_floors = floor_count - 1
total_height = ground_floor_height + (typical_floors * typical_floor_height)
total_area = floor_count * floor_area
average_height = total_height / floor_count

print(f"\\nWith {floor_count} floors:")
print(f"Total height: {total_height}m")
print(f"Total area: {total_area}m²")
print(f"Average floor height: {average_height}m")

Assignment

  1. Create a new file called expressions_practice.py
  2. Complex building calculation:
    • Variables: ground_floor = 4.5, typical_floor = 3.2, penthouse = 5.0, floor_count = 15
    • 1 ground floor, 13 typical floors, 1 penthouse
    • Calculate total building height
    • Use proper operator precedence (parentheses where needed)
  3. Budget calculator with compound operators:
    • Start with: total_budget = 0
    • Add: design = 750000
    • Add: construction = 3500000
    • Add: contingency = 500000
    • Use += for each addition
    • Print final total
  4. Range validation with chained comparisons:
    • Variables: ceiling_height = 2.8, min_height = 2.4, max_height = 3.0
    • Check if height is within range using chained comparison
    • Test with values: 2.3, 2.8, 3.1
  5. FAR calculation with validation:
    • Variables: site_area = 2000, gross_floor_area = 8500, max_far = 5.0
    • Calculate FAR
    • Check if compliant (FAR <= max_far)
    • Print results clearly
  6. Sheet name filtering:
    • List: ["A-101 Floor Plan", "A-201 Ceiling Plan", "S-101 Floor Plan"]
    • Use in operator to find sheets containing "Floor"
    • Print matching sheets
  7. Multi-condition validation:
    • Room: area = 420, height = 2.6, windows = True, basement = False
    • Requirements: area >= 400, height >= 2.7, windows or not basement
    • Create boolean for each condition
    • Combine with and
    • Print which conditions pass/fail
  8. Experiment:
    • Write a complex expression on one line
    • Break it down into multiple lines with named variables
    • Compare readability

Knowledge Check

The following questions are an opportunity to reflect on key topics in this lesson.


Module 02 Complete!

You've learned:

  • Variables (naming and storing information)
  • Numbers (integers and floats)
  • Strings (text manipulation)
  • Booleans (True/False logic)
  • Type conversion (changing between types)
  • Expressions (combining it all together)

What's next: Module 03 covers control flow — making decisions with if statements and repeating work with loops. You now have all the building blocks you need.


Additional Resources

This section contains helpful links to related content. It isn't required, so consider it supplemental.

Updated on Mar 27, 2026