Exercises — Chapter 3: Python Basics

Starred exercises (*) have worked solutions in Appendix B.


Tier 1: Recall

1.1 What are the five core Python data types? Give a business example of each.

1.2 What does the type() function return? Give an example.

1.3 ★ Write a Python expression that converts the string "47500" to an integer, then multiplies it by 1.15.

1.4 What is the difference between / and // in Python? Give an example showing where the results differ.

1.5 What does % (modulo) compute? Write an expression to find how many items are left over after packing 247 items into boxes of 16.

1.6 Write an f-string that displays a revenue variable of 1_234_567.89 as $1,234,567.89.

1.7 What does and return when both operands are True? When one is False?

1.8 What is None, and how does it differ from 0 and "" (empty string)?


Tier 2: Apply

2.1 ★ Create variables for a consulting project: - Client name: "Pacific Ridge Partners" - Hours billed: 18.5 - Hourly rate: 195.00 - Expense reimbursement: 340.00

Calculate and print: - Hourly fees subtotal - Total invoice amount (fees + expenses) - Whether this is a 10+ hour engagement (True/False) - The invoice formatted as: "Invoice for Pacific Ridge Partners: $X,XXX.XX"

2.2 Acme Corp's Q1 data: - Q1 revenue: $2,187,400 - Q1 COGS: $1,356,188 - Q1 operating expenses: $425,000

Calculate and print: gross profit, gross margin %, operating profit, operating margin %.

2.3 ★ A product has: - List price: $89.99 - Bulk discount rate: 15% - Sales tax rate: 8.25%

Write a script that computes: discounted price, tax amount, and final price (after discount and tax). Print each, formatted with 2 decimal places.

2.4 Write expressions (not full scripts) that produce the following: - True if a variable score is between 70 and 90 (inclusive), using a chained comparison - The number of complete weeks in 87 days - The number of leftover days after removing complete weeks from 87 days - A string saying "Q" followed by a quarter number variable q (e.g., "Q3")

2.5 Clean the following strings using string methods:

raw_name = "  JOHN   SMITH  "    # Should become "John Smith"
raw_code = "prod-abc-123"        # Should become "PROD-ABC-123"
raw_price = "$1,234.56"          # Should become "1234.56" (ready for float conversion)

Tier 3: Analyze

3.1 ★ Explain what happens when you run the following and why:

a = 10
b = 3
print(a / b)
print(a // b)
print(a % b)
print(a ** b)

3.2 What is the output of each of the following? Explain the reasoning:

print("5" + "10")
print(5 + 10)
print(int("5") + int("10"))
print(str(5) + str(10))
print(5 * "ha")

3.3 The float imprecision problem (Section 3.2) means that 0.1 + 0.2 != 0.3. What practical impact does this have in a financial reporting context? Give a specific scenario where this could cause a problem, and describe how the Decimal module solves it.

3.4 ★ A colleague writes this code to calculate a discount:

price = 120.00
discount_pct = 15
final_price = price - price * discount_pct / 100
print(f"Final price: ${final_price}")

Is this correct? What does it output? Is the output well-formatted? Rewrite it to be both correct (if needed) and well-formatted with 2 decimal places.

3.5 Explain Python's short-circuit evaluation with and and or. Give a business example where short-circuit evaluation matters (either for correctness or performance).


Tier 4: Synthesize

4.1 Design and write a "Profitability Health Check" script for a company with the following inputs:

revenue = 500_000
cogs = 310_000
operating_expenses = 125_000
interest_expense = 8_500
tax_rate = 0.21

The script should calculate and display: - Gross profit and gross margin % - EBITDA (approximate: operating profit before interest and tax) - Net income (after interest and taxes) - Net margin % - A health status: "Healthy" if net margin > 10%, "Caution" if 5–10%, "Critical" if < 5%

4.2 Build a "Unit Economics Calculator" that takes:

customer_acquisition_cost = 450      # CAC
average_order_value = 85             # AOV
purchase_frequency = 4.2             # Times per year
gross_margin_rate = 0.42             # 42%
average_customer_lifespan_years = 3  # How long they stay
discount_rate = 0.10                 # For NPV calculation

Calculate and display: - Annual customer gross profit - Simple Customer Lifetime Value (CLV) = annual GP × lifespan - CAC:CLV ratio (below 3x is concerning) - Payback period in months (CAC / monthly gross profit)

4.3 Write a "Shipping Calculator" for Acme Corp: - Orders under $50: flat $8.99 shipping - Orders $50–$149.99: flat $4.99 shipping - Orders $150+: free shipping - Express shipping: always +$12.00 on top of standard - Overnight: always +$25.00 on top of standard

Take inputs: order_amount, is_express, is_overnight. Calculate and print the total shipping cost. (Use boolean logic from Section 3.7.)


Tier 5: Challenge

5.1 (Research) Python's Decimal module handles exact decimal arithmetic. Research: - How to create Decimal values - What ROUND_HALF_UP is and why it matters for accounting - How to set precision - The trade-off: Decimal vs. float in terms of performance and precision

Write a function-free script (using only Chapter 3 concepts) that calculates a simple invoice total using Decimal arithmetic instead of floats.

5.2 (Open-Ended) The chapter discusses naming conventions for variables. In business Python code, there's a tension between: - Short, terse names that are quick to type (common in data science) - Long, explicit names that are self-documenting (common in production code)

Write both a "terse" and a "verbose" version of the Acme monthly summary calculation from Section 3.10. Then make the case: which style is better for your team (analysts who write Python occasionally vs. engineers who write Python professionally)?