Code
temperature = 10
if temperature > 25:
print("hot")
elif temperature > 5:
print("mild")
else:
print("cold")mild
Control Flows in Python
A conditional runs one block of code and skips the others, depending on which test is true. Python checks the tests in order and stops at the first one that passes.
mild
The elif and else branches are both optional. You can write an if on its own.
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
> < |
greater than, less than |
>= <= |
greater than or equal to, less than or equal to |
in |
is a member of |
stay in
In plain Python you combine tests with and, or and not. Inside a pandas filter you use &, | and ~ instead, and every condition needs its own parentheses. See the data selection cheatsheet.
Conditionals become most useful when you wrap them in a function and hand that function to .apply(), which is the Day 4 pattern.
The loop variable, site here, takes each value in turn. The name is yours to choose.
This is the form live-coding session 5d uses, for the cases where one grouped sentence is not enough. Each turn of the loop gives you the groupβs name and the rows belonging to it.
site a: 2 rows, mean 16.55 C
site b: 2 rows, mean 18.10 C
site c: 1 rows, mean 21.90 C
Reach for a loop when you need to do something to each group that .agg() cannot express, or when you want to build up a list of results and combine them afterwards with pd.concat().