Python foundations · Sessions 1 & 2 · review

Four chapters, one churn problem

In Session 1 we covered variables and conditionals; Session 2 opens with functions and loops. This page keeps the four decks in one place, says what you should be able to do after each, and shows every idea on the customer-churn problem the whole course keeps coming back to. Then Lab 0 checks that it stuck.

The class notebook is the Session 2 meeting cell for cell — conditionals, try / except, a function, loops, then a first look at pandas on the Titanic passenger list. Outputs are cleared; run it to get them back.

Lab 0 · Python Foundations Check

Thirteen self-checking exercises · due Mon Oct 5, 11:59 PM

Each exercise has a task, a cell for your code, and a check cell that prints ✓ or tells you exactly what is off. Three exercises per chapter, plus one that puts all four together. Budget 60–90 minutes. Upload the finished notebook to Canvas; it counts toward Participation & in-class labs on completion.

  • Variables: what a customer has paid, text that should be a number, a churn-rate sentence
  • Conditionals: risk tiers, the retention-offer rule, a try / except safety net
  • Functions: expected profit of an offer, risk_tier(), clean_price()
  • Loops: count churners, the largest charge, a queue with a sentinel — then all of it at once
Chapter 2 · Session 1 · Mon Sep 14

Variables, expressions & statements

What we covered

  • Constants and the three types you will meet every day: int, float, str
  • Reserved words and the rules for variable names
  • Assignment statements: the right side is computed first, then stored in the name on the left
  • Numeric operators and precedence — and why 7 / 2 and 7 // 2 differ
  • Converting text to numbers with int() and float(); reading input

You should now be able to

  • Predict what an expression evaluates to before you run it
  • Turn a string like "72.5" into a number you can do arithmetic with
  • Put a computed number into a sentence with an f-string

On the churn problem

monthly = 72.5
months = 14
total = monthly * months            # 1015.0 — the right side first, then the name
churners, customers = 1869, 7043
rate = churners / customers         # 0.2654...
print(f'Churn rate: {rate:.1%}')    # Churn rate: 26.5%

Every column in a pandas table is a variable with a type. Session 2 spends twenty minutes on a column that should be a float and arrives as text.

Slides by Charles Severance, Python for Everybody, used under its Creative Commons license.

Chapter 3 · Session 1 · Mon Sep 14

Conditional execution

What we covered

  • Comparison operators: <, <=, ==, >=, >, != — and why == is not =
  • One-way decisions with if, and indentation as the block marker
  • Nested decisions, then the cleaner multi-way if / elif / else
  • Combining conditions with and, or, not
  • try / except as a safety net around code that might fail

You should now be able to

  • Sort a probability into high / medium / low risk with if / elif / else
  • Write a business rule as one boolean expression
  • Convert messy input without crashing, using try / except

On the churn problem

p, tenure, contract = 0.18, 9, 'Month-to-month'
if p >= 0.5:
    tier = 'high'
elif p >= 0.2:
    tier = 'medium'
else:
    tier = 'low'
send_offer = p >= 0.10 and tenure < 24 and contract == 'Month-to-month'   # True

A threshold is an if statement. Session 5 is an entire evening about where to put it.

Slides by Charles Severance, Python for Everybody, used under its Creative Commons license.

Chapter 4 · Session 2 review · Mon Sep 21

Functions

What we covered

  • Built-in functions you already use (print, int, float, len) versus functions you define
  • def, the function name, and the indented body
  • Parameters and arguments; return values versus functions that only print
  • Default values for parameters, and calling with keywords
  • Why functions: name a piece of logic once, reuse it everywhere, test it in isolation

You should now be able to

  • Turn a repeated if / elif / else into one function you call three times
  • Write a function with sensible defaults and call it with keyword arguments
  • Explain the difference between printing a result and returning it

On the churn problem

def expected_profit(p, offer=50, save=450):
    """Expected profit of a retention offer to a customer with churn probability p."""
    return p * save - offer

expected_profit(0.5)               # 175.0
expected_profit(0.5, offer=200)    # 25.0

scikit-learn is functions all the way down: fit(), predict(), score(). Reading their signatures is this chapter.

Slides by Charles Severance, Python for Everybody, used under its Creative Commons license.

Chapter 5 · Session 2 review · Mon Sep 21

Loops & iteration

What we covered

  • while loops and the iteration variable that must change — or you have an infinite loop
  • break to leave a loop early, continue to skip to the next turn
  • Definite loops with for over a list, a string, or range()
  • The loop idioms: counting, summing, finding the largest (start from None), searching with a flag

You should now be able to

  • Count how many customers churned with a counter and a for loop
  • Find the largest charge and its position with the None-start pattern
  • Process a queue until a sentinel value with while and break

On the churn problem

charges = [70.7, 20.05, 99.65, 45.3, 104.8, 89.1]
largest = None
for i in range(len(charges)):
    if largest is None or charges[i] > largest:
        largest, largest_index = charges[i], i
# largest == 104.8, largest_index == 4

pandas is a loop you do not have to write. Knowing what the loop would have done is how you know what df.groupby() did.

Slides by Charles Severance, Python for Everybody, used under its Creative Commons license.

Where this goes next

Chapters 6–10 (strings, files, lists, dictionaries, tuples) and pandas are Levels 2–4 of the Python Track, with the same slides, the same in-browser lessons, and Prof. Arslan's ISOM 730 notebooks. Session 2's notebook assumes Level 4; if Lab 0 felt easy, go there. If it did not, do Lessons 0 and 1 of Python, Guided first — they grade you as you go.