4416.6
BAA1118 - Foundations of Programming for Analytics & AI
True or Falseif, elif, elsefor loopswhile loopsbreak, continue and comprehensionsEverything so far has run top to bottom, once.
Real analysis needs two more things:
Together they are called control flow: you control the order in which lines run.
if and ends with a colonTrueIn most languages, indentation is decoration. In Python, it is the code.
Cell In[45], line 2 print("Premium") ^ IndentationError: expected an indented block after 'if' statement on line 1
The convention is 4 spaces. Colab and VS Code insert them for you when you press Enter after a colon.
Warning
Never mix tabs and spaces. It produces errors that are invisible on screen.
Standard customer
else has no condition. It catches everything the if did not.
Silver
Source: UBC Master of Data Science, Programming in Python for Data Science
Silver
The customer spent €1,250 and was labelled Silver, because > 100 was tested first and won.
Write cut-offs from the most restrictive to the least.
You can put any value after if, not only a comparison. Python decides whether it counts as True or False:
False: zero, empty or nothing (0, "", [], {}, None)True: everything else, such as 42 or "Dublin"No email on file
"" and None are both falsy, so if email: catches both.
Irish premium
Each level adds 4 spaces. Beyond two levels, the code is hard to read: combine with and instead.
Write code that turns a mark out of 100 into a grade:
| Mark | Grade |
|---|---|
| 70 and above | First |
| 40 to 69 | Pass |
| below 40 | Fail |
if / elif / elseA mark of 64 is a Pass| Mark | Grade | Branch |
|---|---|---|
| 70 and above | First | if |
| 40 to 69 | Pass | elif |
| below 40 | Fail | else |
elif needs no mark < 70: the if has already caught 70 and above>= matters: with >, a mark of exactly 70 would be a PassTwo ways to total a list without sum():
By hand: one line per element
Read the loop as English: “for each value in sales, add it to total”. The print() inside the loop shows each step.
item is a new variable you name, holding one element at a timecollection is a list, string, dictionary, or anything iterableifSource: UBC Master of Data Science, Programming in Python for Data Science
Now processing: Ireland
Now processing: France
Now processing: Spain
The loop variable survives after the loop, holding the last value:
For a fixed number of repetitions, range() generates the numbers.
range(5) gives 0, 1, 2, 3, 4: five numbers, starting at zero, stopping before 5. The same rule as slicing.
Three steps you will write for the rest of your life:
[12.3, 30.75, 10.46]
Start with an empty list, append() inside the loop. This is the second most common loop pattern.
A total starts at 0, so why does this list start at []? Try it with 0:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[61], line 2 1 prices_with_vat = 0 ----> 2 prices_with_vat.append(12.3) AttributeError: 'int' object has no attribute 'append'
append() only exists for lists0 is an int, and an int has no append(): that is what the error says0 for a total, [] for a listConditions and loops combine naturally:
name
city
spend
name: Damien
city: Dublin
spend: 1250.5
.items() gives both at once, and the two loop variables are unpacked exactly as with tuples.
258
Eight lines. In week 8, pandas does this in one: df.groupby("region")["units"].sum().
When you need the position as well as the value:
0 Ireland
1 France
2 Spain
When you need to walk two lists together:
Each task reuses one pattern from the previous slides:
monthly, without sum()target: each value plus 10, using append()zip() to print each month with its value: Jan: 130Total: 600
Mean: 150.0
A for loop runs a known number of times. A while loop runs until a condition stops being true.
15 2078.93
We did not know in advance that it would take 15 years. That is exactly when while is the right tool.
Important
Every while loop must contain a line that eventually makes the condition false. If Colab hangs, press the stop button, or Runtime -> Interrupt execution.
In practice, 95% of the loops you write in analytics are for loops.
Found a big spender: 1200
90
760
180
continue is how you skip missing values without crashing.
Until: while
24 years at 3%
24 years at 3%, 12 at 6%: the “rule of 72” (72 ÷ the rate) predicts both.
continue skips each None and carries on. break stops the loop at the first None, so only 12.5 is printed.
Building a list with a loop:
[12.3, 30.75, 10.455]
The same thing, in one line:
Read it backwards: “for each price in prices, store price times 1.23”.
And a condition on the value stored:
['small', 'big', 'small', 'big', 'small']
Tip
If a comprehension no longer fits comfortably on one line, write it as a normal loop. Clever is not a goal.
0 12.300
1 30.750
2 10.455
dtype: float64
No loop. The operation applies to the whole column at once, and it is roughly 100 times faster on real data.
temps_f converting each to Fahrenheit: f = c * 9/5 + 32"warm" if above 15, "cold" otherwisefor loop, and check the two give the same result[54.5, 59.0, 49.64, 70.34, 65.66, 39.56]
[21.3, 18.7]
['cold', 'cold', 'cold', 'warm', 'warm', 'cold']
True
if / elif / else, tested in order, first match winsfor item in collection: and the accumulator patternrange(), enumerate(), zip()while for “until”, with the infinite loop riskbreak and continue
Thanks for your attention and don’t hesitate to ask if you have any questions! @damien_dupre @damien-dupre https://damien-dupre.github.io damien.dupre@dcu.ie