Python for Business: Foundations, Control Flow, and Reusable Logic

Python Environment and Execution Models

Python consists of two foundational components: the high-level programming language and the interpreter. The Python interpreter reads source code and executes it sequentially, line by line. Development is performed inside an Integrated Development Environment (IDE) or editor, which provides tools to write, execute, and debug code.

 Common IDEs and text editors include:

  • IDLE (Integrated Development and Learning Environment, bundled with Python installations)

  • Visual Studio Code (VS Code)

  • PyCharm

Setting up Python requires installing Python 3 and adding Python to the system PATH environment variable so the interpreter can be called from any terminal directory.

Python programs are executed using two primary workflow modes:

  • Interactive Shell (REPL / Read-Eval-Print Loop): Commands typed into the >>> prompt evaluate immediately upon pressing Enter. This mode is suitable for inspecting variables, running quick calculations, and testing small code snippets.

  • Script / Program Mode: Multi-line Python statements are saved in text files with a .py extension. Running a script causes the interpreter to process the entire file top-to-bottom. Scripting is required for building reusable, production-ready systems.

# Example execution pipeline in Python
x = 2
y = 3
print(x + y)  # Output: 5

Operators, Expressions, Data Types, and Syntax Rules

An expression combines values, variables, and operators, which Python evaluates to compute a single output value.

Python assigns every value to a specific data type. A value's type dictates what operations are valid and how Python processes those operations:

  • Integer (int): Whole numbers without decimal points, such as 25 or -10.

  • Floating-point (float): Real numbers containing decimal points, such as 25.75 or 25.0.

  • String (str): Sequence of text characters enclosed in single or double quotation marks, such as "25" or "Hello".

  • Boolean (bool): Truth values represented strictly as True or False.

The values 25 (int) and "25" (str) are fundamentally different in memory. Operations on numbers perform calculations, whereas operations on strings perform text manipulations.

Arithmetic Operators

Python provides standard arithmetic operators for numeric evaluation:

  • Addition (+): Sums two numeric values (e.g., 7 + 3 evaluates to 10).

  • Subtraction (-): Subtracts the right value from the left value (e.g., 7 - 3 evaluates to 4).

  • Multiplication (*): Multiplies two values (e.g., 7 * 3 evaluates to 21).

  • Division (/): Divides the left operand by the right operand, always returning a float (e.g., 7 / 3 evaluates to 2.3333333333333335).

  • Floor Division (//): Divides and truncates the decimal portion, returning the integer quotient (e.g., 7 // 3 evaluates to 2).

  • Modulus (%): Computes the integer remainder of division (e.g., 7 % 3 evaluates to 1).

  • Exponentiation (**): Raises the base operand to the power of the exponent operand (e.g., 2 ** 3 evaluates to 8).

String Operations

When applied to strings, operators execute text-specific behavior:

  • String Concatenation (+): Joins two string objects together end-to-end without adding spaces. For example, "5" + "5" evaluates to "55", and "Python" + " is fun" evaluates to "Python is fun".

  • String Repetition (*): Multiplies a string by an integer to repeat it. For example, "Hi! " * 3 evaluates to "Hi! Hi! Hi! ".

Operator Precedence

When evaluating complex mathematical expressions containing multiple operators, Python follows a strict precedence hierarchy:

  1. Parentheses (): Expressions inside parentheses execute first.

  2. Exponentiation **

  3. Multiplication *, Division /, Floor Division //, Modulus %

  4. Addition +, Subtraction -

Operators at the same precedence level evaluate from left to right. Using explicit parentheses is recommended to guarantee evaluation order and enhance code readability.

Evaluation examples:

  • 10+5×210 + 5 \times 2 evaluates to 20 because multiplication takes precedence over addition.

  • (10+5)×2(10 + 5) \times 2 evaluates to 30 because parenthesized logic executes first.

  • 2+3×42 + 3 \times 4 evaluates to 14.

  • 17/517 / 5 evaluates to 3.4.

  • 17//517 // 5 evaluates to 3.

  • 17%517 \% 5 evaluates to 2.

Python Syntax and Error Handling

Syntax refers to the structural rules governing valid Python code. If code violates these structural rules, the interpreter halts execution and raises a SyntaxError:

  • 5 + throws SyntaxError: invalid syntax (missing right-hand operand).

  • 42 5 * 2 throws SyntaxError: invalid syntax (missing operational operator between values).

  • print("Hello) throws SyntaxError: unterminated string literal (missing closing quote mark).

Variable Assignment, Naming Conventions, and I/O Operations

Variables store data in memory so values can be reused, updated, and combined throughout a program.

The single equals sign (=) acts as the assignment operator, binding a variable name on the left to the evaluated value on the right:

price = 25
quantity = 4
total = price * quantity  # total stores 100

Reassigning a variable updates its current reference in memory:

price = 30  # price updated from 25 to 30

The assignment operator (=) differs fundamentally from the structural equality comparison operator (==). Assignment stores data; comparison evaluates equality to return a Boolean value.

Variable Naming Rules

Variable names must strictly follow these structural criteria:

  • Must begin with a letter (a–z, A–Z) or an underscore (_).

  • Cannot start with a numerical digit (e.g., 2sales is illegal and triggers a syntax error).

  • Can only contain alphanumeric characters and underscores (a-z, A-Z, 0-9, _).

  • Spaces are illegal in variable names.

  • Python is case-sensitive (Total, total, and TOTAL represent three distinct variables).

  • Recommended convention: snake_case, where words are lowercase and separated by underscores (e.g., customer_name, sales_2026, total_amount).

Input / Process / Output (IPO) Model

Programs process business logic through an Input →\rightarrow Process →\rightarrow Output pipeline:

  • Input: input() prompts the user for input and receives it. Critical rule: input() always returns user input as a string (str), even if the user enters numeric digits.

  • Processing / Type Casting: Explicit type conversions must convert user strings before performing arithmetic:

    • float() converts string or integer representations to floating-point numbers.

    • int() converts valid string digits or float representations to whole numbers.

    • str() converts numeric types to string text.

    • len() calculates the total character count of a string or item length of a sequence (e.g., len("Purdue") returns 6).

  • Output: print() outputs calculated values, strings, or variables to standard output.

# Practical IPO Script Example
price = float(input("Enter price: "))
tax = price * 0.07
total = price + tax
print("Total:", total)

Conditional Logic and Decision-Making Structures

While arithmetic calculations output scalar values, comparisons evaluate conditions to return Boolean results (True or False).

Comparison Operators

Comparison operators assess relationships between two values:

  • == Equal to

  • != Not equal to

  • > Greater than

  • < Less than

  • >= Greater than or equal to

  • <= Less than or equal to

Example evaluation: If revenue = 12000 and cost = 9000, then revenue > cost evaluates to True.

Logical Operators (and, or, not)

Logical operators combine multiple Boolean expressions:

  • and: Evaluates to True only if both surrounding conditions evaluate to True.

  • or: Evaluates to True if at least one surrounding condition evaluates to True.

  • not: Inverts the truth value of a condition (not True becomes False; not False becomes True).

Truth Table Summary:

  • True and True →\rightarrow True; True and False →\rightarrow False

  • True or False →\rightarrow True; False or False →\rightarrow False

  • not True →\rightarrow False; not False →\rightarrow True

Example Evaluation: Given sales = 12000 and rating = 4.2:

  • sales >= 10000 and rating >= 4.5 evaluates to True and False, which resolves to False.

Practical Business Logic Expressions:

  • Free shipping qualification: order_total >= 50 and is_member

  • Transaction flag: amount > 5000 or international

  • Communication targeting: not unsubscribed

Structural Selection Constructs

Control flow determines the order in which statements are executed. Python supports three core patterns: Sequence (order of instructions), Selection (conditional decision branching), and Repetition (loops).

The if Statement

Executes an indented code block only when the operational condition evaluates to True. Code indentation (4 spaces) marks block scope.

order_total = 75
if order_total >= 50:
    print("Free shipping")
    print("Thank you!")
print("Checkout complete")

If order_total is 75, all three messages print. If order_total is 35, the indented block is skipped, and only "Checkout complete" prints.

The if-else Statement

Provides two mutually exclusive execution paths. Exactly one branch runs.

order_total = 35
if order_total >= 50:
    print("Free shipping")
else:
    print("Standard shipping")

If order_total is 50, the condition 50 >= 50 is True, printing "Free shipping".

The if-elif-else Construct

Evaluates multiple conditions sequentially from top to bottom. The first branch whose condition evaluates to True executes, and Python skips all subsequent operational branches. Order of rules is critical.

spending = 7200
if spending >= 10000:
    tier = "Gold"
elif spending >= 5000:
    tier = "Silver"
else:
    tier = "Standard"
print(tier)  # Prints: Silver

If the >= 5000 check were positioned above the >= 10000 check, a spending level of 12000 would incorrectly evaluate to "Silver", making the "Gold" branch unreachable.

Nested Decisions

An if decision block can reside inside another if decision block to handle multi-layered rules:

amount = 7000
international = True
if amount > 5000:
    print("Review transaction")
    if international:
        print("High priority")

This nested logic can also be expressed as a flattened condition: if amount > 5000 and international:.

Business Discount Matrix Logic

Rules:

  1. Gold customers →\rightarrow 15% discount (0.15)

  2. Silver customers with order_total >= 250 →\rightarrow 10% discount (0.10)

  3. Any customer tier with order_total >= 500 →\rightarrow 5% discount (0.05)

  4. All other scenarios →\rightarrow 0% discount (0.00)

Implementation:

customer_tier = "Silver"
order_total = 325

if customer_tier == "Gold":
    discount = 0.15
elif customer_tier == "Silver" and order_total >= 250:
    discount = 0.10
elif order_total >= 500:
    discount = 0.05
else:
    discount = 0.00

print(discount)  # Outputs: 0.1

Iteration and Sequence Processing with for Loops

A for loop iterates repeatedly over items in a collection or sequence, executing the indented block once per item.

temperatures = [72, 75, 81]
for temp in temperatures:
    print(temp)
  • temperatures: Target sequence/collection.

  • temp: Loop variable representing the active item during the current iteration.

  • print(temp): Repeated statement block.

Iteration Mechanics and Variable Tracing

Loop variable tracing for wait_times = [12, 18, 7, 25] running for wait in wait_times: print(wait):

Iteration

Loop Variable (wait)

Output

Sequence Index

Pass 1

12

12

Index 0

Pass 2

18

18

Index 1

Pass 3

7

7

Index 2

Pass 4

25

25

Index 3

What changes each pass? The loop variable. What stays the same? The repeated instructions inside the loop body.

Integrating Conditionals inside Loops

Loops control operational repetition over datasets, whereas conditional statements filter or evaluate each item:

transactions = [120, 2500, 80, 5200, 410, 3000]
for amount in transactions:
    if amount >= 2000:
        print("Review")

Tracing execution:

  • 120: No output

  • 2500: Prints "Review"

  • 80: No output

  • 5200: Prints "Review"

  • 410: No output

  • 3000: Prints "Review"

Industry Repetition Applications

Repetition is a common computational pattern across business analytics domains:

  1. Banking: Inspect every transaction for fraudulent activity.

  2. Healthcare: Review clinical patient readings for abnormalities.

  3. Logistics: Check delivery status across all active shipments.

  4. Manufacturing: Inspect telemetry readings across factory machines.

  5. Marketing: Analyze engagement responses across marketing campaigns.

  6. Human Resources: Compute payroll, taxes, and benefits for every employee.

  7. Cybersecurity: Examine login attempts and network logs for security threats.

  8. Hospitality: Process guest room reservations across property portfolios.

Application: Customer Churn Retention Review

A subscription business tracks activity scores to identify churn risk (activity_scores = [82, 45, 67, 30, 91, 55]). Scores under 50 signal risk:

activity_scores = [82, 45, 67, 30, 91, 55]
for score in activity_scores:
    if score < 50:
        print("At risk")

Output Evaluation:

  • Score 82 →\rightarrow Healthy

  • Score 45 →\rightarrow At risk (Prints "At risk")

  • Score 67 →\rightarrow Healthy

  • Score 30 →\rightarrow At risk (Prints "At risk")

  • Score 91 →\rightarrow Healthy

  • Score 55 →\rightarrow Healthy

Range-Based Iteration and Financial Forecasting

When a program needs to repeat an action a specific number of times without an existing collection, range() generates integer sequences on demand.

for i in range(5):
    print(i)  # Prints: 0, 1, 2, 3, 4

Critical rule: range() includes the start value but excludes the stop value.

Three Configuration Signatures of range()

  1. range(stop)

    • Defaults start to 0 and steps by 1 up to stop - 1.

    • list(range(5)) →\rightarrow [0, 1, 2, 3, 4]

    • Business Use: Iterating over days in a promotional campaign.

  2. range(start, stop)

    • Starts at start, incrementing by 1 up to stop - 1.

    • list(range(1, 6)) →\rightarrow [1, 2, 3, 4, 5]

    • Business Use: Monthly multi-period forecasting.

  3. range(start, stop, step)

    • Starts at start, incrementing by step up to stop - 1.

    • list(range(0, 11, 2)) →\rightarrow [0, 2, 4, 6, 8, 10]

    • Business Use: Bi-monthly or alternate reporting intervals.

Application: Five-Year Infrastructure Growth Model

A cloud provider with an initial computing capacity of 10,000 units anticipates 8% annual growth (capacity=capacity×1.08\text{capacity} = \text{capacity} \times 1.08):

capacity = 10000
for year in range(1, 6):
    capacity = capacity * 1.08
    print(year, round(capacity, 2))

Operational Projection Output:

  • Year 1: 10800.00

  • Year 2: 11664.00

  • Year 3: 12597.12

  • Year 4: 13604.89

  • Year 5: 14693.28

Accumulator and Counter Design Patterns

Two structural iteration patterns appear frequently when summarizing operational datasets: Accumulation (summing values) and Counting (tallying occurrences).

Pattern 1: Accumulating a Total

An accumulator stores a running total across iterations. The tracking variable must be initialized before the loop starts (typically to 0) and updated on each iteration pass.

distances = [18, 32, 21, 27]
total_distance = 0
for distance in distances:
    total_distance = total_distance + distance
print(total_distance)  # Outputs: 98

Step-by-step Trace:

  • Initial State: total_distance = 0

  • Pass 1: + 18 →\rightarrow total_distance = 18

  • Pass 2: + 32 →\rightarrow total_distance = 50

  • Pass 3: + 21 →\rightarrow total_distance = 71

  • Pass 4: + 27 →\rightarrow total_distance = 98

Business Applications: Aggregating total transaction revenue, tracking billable hours from timesheets, summing fleet delivery miles, and aggregating site traffic.

Pattern 2: Counting Specific Occurrences

A counter variable initializes before the loop (typically to 0) and increments by 1 only when an item satisfies a specific conditional criteria.

delays = [12, 41, 5, 63, 28]
late_count = 0
for delay in delays:
    if delay > 30:
        late_count = late_count + 1
print(late_count)  # Outputs: 2

Step-by-step Trace:

  • Delay 12: 12 > 30 is False →\rightarrow late_count remains 0

  • Delay 41: 41 > 30 is True →\rightarrow late_count becomes 1

  • Delay 5: 5 > 30 is False →\rightarrow late_count remains 1

  • Delay 63: 63 > 30 is True →\rightarrow late_count becomes 2

  • Delay 28: 28 > 30 is False →\rightarrow late_count remains 2

Combined Operational Summary: Call Center Wait Analytics

Summarizing operational metrics requires pairing accumulators and counters within a single loop:

wait_times = [12, 35, 8, 41, 22, 50]
total_wait = 0
long_waits = 0

for wait in wait_times:
    total_wait = total_wait + wait
    if wait > 30:
        long_waits = long_waits + 1

print("Total wait time:", total_wait)  # 168 minutes
print("Long waits:", long_waits)      # 3 customers
print("Average wait:", total_wait / len(wait_times))  # 28.0 minutes

Mathematical summary: Total Wait=12+35+8+41+22+50=168 minutes\text{Total Wait} = 12 + 35 + 8 + 41 + 22 + 50 = 168\,\text{minutes} Long Waits (wait>30)=3 customers (35, 41, 50)\text{Long Waits (wait} > 30\text{)} = 3\,\text{customers (35, 41, 50)} Average Wait=1686=28.0 minutes\text{Average Wait} = \frac{168}{6} = 28.0\,\text{minutes}

Event-Driven Iteration with while Loops

A while loop continuously executes its code block as long as its designated Boolean evaluation remains True.

Structure of a while loop:

  1. Initialize: Set a baseline tracking variable prior to the loop.

  2. Check: Python evaluates the Boolean condition.

  3. Execute: Run the indented code block if the condition evaluates to True.

  4. Update: Modify the loop variable inside the block to advance toward a False evaluation.

inventory = 5
while inventory > 0:
    print("Sell one item")
    inventory = inventory - 1

Operational Execution Trace: Bank Queue Management

customers_waiting = 3
while customers_waiting > 0:
    print("Serve customer")
    customers_waiting = customers_waiting - 1

Execution Step Trace:

  • Start: Initialize customers_waiting = 3

  • Iteration 1: Check 3 > 0 (True) →\rightarrow Print "Serve customer" →\rightarrow Update customers_waiting to 2

  • Iteration 2: Check 2 > 0 (True) →\rightarrow Print "Serve customer" →\rightarrow Update customers_waiting to 1

  • Iteration 3: Check 1 > 0 (True) →\rightarrow Print "Serve customer" →\rightarrow Update customers_waiting to 0

  • Loop Exit: Check 0 > 0 (False) →\rightarrow Terminate loop execution.

Trace for queue system (customers_waiting = 6):

  • Step 0 (Start): 6 customers remaining

  • Step 1: 5 remaining

  • Step 2: 4 remaining

  • Step 3: 3 remaining

  • Step 4: 2 remaining

  • Step 5: 1 remaining

  • Step 6 (End): 0 remaining →\rightarrow Prints "Queue cleared"

Construct Selection Guide: for vs while

Use for loops when iterating over a defined collection or a fixed range of values (for each item). Use while loops when repetition depends on a state-based stopping condition (until / as long as).

Business Choice Matrix:

  1. Banking: Retry identity verification until approved or maximum allowed attempts are exhausted →\rightarrow while loop

  2. Customer Service: Serve queued customers continuously as long as people remain in line →\rightarrow while loop

  3. Inventory: Process incoming customer orders while stock levels remain positive →\rightarrow while loop

  4. Hospitality: Search room records dynamically until an open room match is located →\rightarrow while loop

  5. IT Operations: Retry database link connections while remote server status remains offline →\rightarrow while loop

  6. Transaction Auditing: Review every customer order record from yesterday's batch file →\rightarrow for loop

  7. Demand Forecasting: Estimate inventory demand for each of the upcoming 12 months →\rightarrow range() loop

Preventing Infinite Loops

If the state update step is omitted inside a while loop, the continuation condition remains True permanently, hanging the application in an infinite loop:

# Broken Version (Infinite Loop!)
battery = 20
while battery < 30:
    print("Charging...")  # battery never updates, loop runs infinitely

# Corrected Version
battery = 20
while battery < 30:
    print("Charging...")
    battery = battery + 1

Loop Control Statements: break and continue

Loop control statements modify execution flow within for and while loops:

  • break: Terminates the loop entirely and transfers execution to statements after the loop block.

  • continue: Aborts the current pass, skips remaining statements in the loop body, and advances to the next iteration.

Business Applications

Search Optimization with break

In a hotel room availability search (availability = [0, 0, 2, 0]), stop scanning database records immediately upon identifying the first available room:

availability = [0, 0, 2, 0]
for rooms in availability:
    if rooms > 0:
        print("Room found")
        break

Trace:

  • Index 0 (0 rooms): Available? No.

  • Index 1 (0 rooms): Available? No.

  • Index 2 (2 rooms): Available? Yes! Prints "Room found", triggers break, and exits search instantly.

Data Cleaning with continue

When processing customer survey feedback (ratings = [5, -1, 4, 3]), ignore invalid negative responses (-1) while processing all valid data:

ratings = [5, -1, 4, 3]
for rating in ratings:
    if rating < 0:
        continue
    print(rating)

Output Trace:

  • Rating 5: Valid →\rightarrow Prints 5

  • Rating -1: Invalid →\rightarrow Triggers continue, skips print(), advances to next item

  • Rating 4: Valid →\rightarrow Prints 4

  • Rating 3: Valid →\rightarrow Prints 3

Modular Programming with Functions

Copying and pasting business rules across multiple system modules leads to code duplication, high maintenance costs, and rule inconsistency. Functions centralize business logic into modular, reusable blocks.

A function is a named, reusable block of Python statements constructed to perform a specific task.

# Defining a function
def daily_briefing():
    print("Check overnight orders")
    print("Review inventory alerts")
    print("Open service dashboard")

# Executing (calling) the function
daily_briefing()

Key terms:

  • def: Reserved keyword signaling function definition.

  • daily_briefing(): Function name followed by parameter parenthesis.

  • Indented body: The encapsulated instructions stored for later execution.

Parameters vs Arguments

Parameters make functions adaptable to varied input data:

  • Parameter: A placeholder variable name declared inside the function definition header.

  • Argument: The concrete data value passed into the function call.

def estimate_hours(distance, speed):
    hours = distance / speed
    print(hours)

# Calling with arguments
estimate_hours(120, 60)  # distance=120, speed=60 -> Prints: 2.0
estimate_hours(300, 50)  # distance=300, speed=50 -> Prints: 6.0

Returning Values vs Printing

The print() function displays textual characters to stdout but returns None. The return statement passes an evaluated value back to the program statement that invoked the function, allowing that result to be stored in a variable or used in subsequent calculations.

def calculate_dti(monthly_debt, monthly_income):
    ratio = monthly_debt / monthly_income
    return ratio

# Storing returned calculation in variable for downstream logic
dti = calculate_dti(1800, 6000)  # dti stores 0.30
if dti > 0.40:
    print("Review application")

Debt-to-Income (DTI)=Monthly DebtMonthly Income=18006000=0.30\text{Debt-to-Income (DTI)} = \frac{\text{Monthly Debt}}{\text{Monthly Income}} = \frac{1800}{6000} = 0.30

Function Composition

Complex applications are constructed by calling smaller, focused functions inside larger workflow functions:

def calculate_dti(debt, income):
    return debt / income

def review_application(debt, income):
    dti = calculate_dti(debt, income)
    if dti > 0.40:
        return "Review"
    else:
        return "Proceed"

status = review_application(2400, 5000)
# calculate_dti(2400, 5000) returns 0.48
# 0.48 > 0.40 evaluates to True
# review_application returns "Review"

Retail Inventory Reorder Status Module

def reorder_status(stock, reorder_point):
    if stock <= reorder_point:
        return "Reorder"
    else:
        return "Sufficient"

# Product 1: Headphones (stock=18, reorder_point=20)
print(reorder_status(18, 20))  # Outputs: 'Reorder'

# Product 2: Water Bottle (stock=42, reorder_point=20)
print(reorder_status(42, 20))  # Outputs: 'Sufficient'

Combining Functions and Loops for Scalable Business Logic

Combining functions and loops establishes a core software pattern: Functions define single rules, and loops apply those rules across datasets.

Airline Delay Classification System

Rule specification:

  • Delay ≥60\ge 60 minutes →\rightarrow "Severe"

  • Delay ≥15\ge 15 minutes →\rightarrow "Delayed"

  • Delay <15< 15 minutes →\rightarrow "On time"

def classify_delay(minutes):
    if minutes >= 60:
        return "Severe"
    elif minutes >= 15:
        return "Delayed"
    else:
        return "On time"

delays = [8, 35, 75, 12, 48]
for delay in delays:
    print(classify_delay(delay))

Execution Output:

  • 8 minutes →\rightarrow On time

  • 35 minutes →\rightarrow Delayed

  • 75 minutes →\rightarrow Severe

  • 12 minutes →\rightarrow On time

  • 48 minutes →\rightarrow Delayed

In-Class Challenges and Comprehensive Walkthroughs

Challenge 1: Expense Reimbursement Audit Engine

Scenario: Inspect employee expense claims (claims = [85, 240, 120, 460, 95, 310]). Flag claims exceeding $200 with "Manager approval". Do not modify the source data. Include claim indexing using range().

claims = [85, 240, 120, 460, 95, 310]

# Base implementation
for claim in claims:
    if claim > 200:
        print("Manager approval")

# Bonus implementation using range()
for index in range(len(claims)):
    if claims[index] > 200:
        print("Claim #" + str(index + 1) + " (" + str(claims[index]) + "): Manager approval")

Challenge 2: Airline Satisfaction Score Analyzer

Scenario: Analyze flight customer satisfaction survey entries (ratings = [5, 4, 2, 3, 1, 5, 4]). Count positive responses (ratings of 4 or 5), aggregate the total rating sum, and display respondent indexes for dissatisfied feedback (ratings under 4).

ratings = [5, 4, 2, 3, 1, 5, 4]
positive_count = 0
total_rating_score = 0

for rating in ratings:
    total_rating_score = total_rating_score + rating
    if rating >= 4:
        positive_count = positive_count + 1

print("Positive Ratings Count:", positive_count)      # 4
print("Total Rating Score:", total_rating_score)        # 24
print("Average Rating:", total_rating_score / len(ratings)) # 3.4285714285714286

# Identifying dissatisfied customers
for i in range(len(ratings)):
    if ratings[i] < 4:
        print("Follow up with Respondent #" + str(i + 1) + ", Rating:", ratings[i])

Outputs for low satisfaction tracking:

  • Respondent #3, Rating: 2

  • Respondent #4, Rating: 3

  • Respondent #5, Rating: 1

Challenge 3: Insurance Claim Triage System

Scenario: Triage claim amounts (claims = [850, 3200, 12500, 600, 7800]) according to financial severity thresholds:

  • Under $1,000 $\rightarrow$ 'Routine'

  • $1,000 to $9,999 $\rightarrow$ 'Review'

  • $10,000+ →\rightarrow 'Priority Review'

Tasks:

  1. Create classify_claim(amount) returning category strings.

  2. Iterate through claims using a for loop.

  3. Count total 'Priority Review' claims.

  4. Display the total priority count.

  5. Bonus: Include claim index tracking using range().

def classify_claim(amount):
    if amount >= 10000:
        return "Priority Review"
    elif amount >= 1000:
        return "Review"
    else:
        return "Routine"

claims = [850, 3200, 12500, 600, 7800]
priority_count = 0

for index in range(len(claims)):
    amount = claims[index]
    category = classify_claim(amount)
    print("Claim #" + str(index + 1) + " (\"" + str(amount) + "\"): " + category)
    if category == "Priority Review":
        priority_count = priority_count + 1

print("Total Priority Review Claims:", priority_count)

Execution Output:

  • Claim #1 ($850): Routine

  • Claim #2 ($3200): Review

  • Claim #3 ($12500): Priority Review

  • Claim #4 ($600): Routine

  • Claim #5 ($7800): Review

  • Total Priority Review Claims: 1