-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathp_foundations_for_loops.qmd
275 lines (179 loc) · 7.25 KB
/
p_foundations_for_loops.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
---
title: 'Intro to Loops in Python'
---
```{python}
# | echo: false
# temporary solution to avoid SSL certificate verification error
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
```
## Introduction
At the heart of programming is the concept of repeating a task multiple times. A `for` loop is one fundamental way to do that. Loops enable efficient repetition, saving time and effort.
Mastering this concept is essential for writing intelligent Python code.
Let's dive in and enhance your coding skills!/Applications/Python 3.12/Install Certificates.command
## Learning Objectives
By the end of this lesson, you will be able to:
- Use basic `for` loops in Python
- Use index variables to iterate through lists in a loop
- Format output using f-strings within loops
- Apply loops to generate multiple plots for data visualization
## Packages
In this lesson, we will use the following Python libraries:
```{python}
import pandas as pd
import plotly.express as px
from vega_datasets import data
```
## Intro to `for` Loops
Let's start with a simple example. Suppose we have a list of children's ages in years, and we want to convert these to months:
```{python}
ages = [7, 8, 9] # List of ages in years
```
We could try to directly multiply the list by 12:
```{python}
ages * 12
```
But this does not do what we want. It repeats the list 12 times.
Rather, we need to loop through each element in the list and multiply it by 12:
```{python}
for age in ages:
print(age * 12)
```
`for` and `in` are required keywords in the loop. The colon and the indentation on the second line are also required.
In this loop, `age` is a temporary variable that takes the value of each element in `ages` during each iteration. First, `age` is 7, then 8, then 9.
You can choose any name for this variable:
```{python}
for random_name in ages:
print(random_name * 12)
```
Note that we need the print statement since the loop does not automatically print the result:
```{python}
for age in ages:
age * 12
```
::: {.callout-tip title='Practice'}
### Hours to Minutes Basic Loop
Try converting hours to minutes using a `for` loop. Start with this list of hours:
```{python}
hours = [3, 4, 5] # List of hours
# Your code here
```
:::
## Printing with f-strings
We might want to print both the result and the original age. We could do this by concatenating strings with the `+` operator. But we need to convert the age to a string with `str()`.
```{python}
for age in ages:
print(str(age) + " years is " + str(age * 12) + " months" )
```
Alternatively, we can use something called an f-string. This is a string that allows us to embed variables directly.
```{python}
for age in ages:
print(f"{age} years is {age * 12} months")
```
Within the f-string, we use curly braces `{}` to embed the variables.
::: {.callout-tip title='Practice'}
### Practice: F-String
Again convert the list of hours below to minutes. Use f-strings to print both the original hours and the converted minutes.
```{python}
hours = [3, 4, 5] # List of hours
# Your code here
# Example output "3 hours is 180 minutes"
```
:::
## Are `for` Loops Useful in Python?
While `for` loops are useful, in many cases there are more efficient ways to perform operations over collections of data.
For example, our initial age conversion could be achieved using pandas Series:
```{python}
import pandas as pd
ages = pd.Series([7, 8, 9])
months = ages * 12
print(months)
```
But while libraries like pandas offer powerful ways to work with data, for loops are essential for tasks that can't be easily vectorized or when you need fine-grained control over the iteration process.
## Looping with an Index and Value
Sometimes, we want to access both the position (index) and the value of items in a list. The `enumerate()` function helps us do this easily.
Let's look at our `ages` list again:
```{python}
ages = [7, 8, 9] # List of ages in years
```
First, let's see what `enumerate()` actually does:
```{python}
for item in enumerate(ages):
print(item)
```
As you can see, `enumerate()` gives us pairs of (index, value).
We can unpack these pairs directly in the `for` loop:
```{python}
for i, age in enumerate(ages):
print(f"The person at index {i} is aged {age}")
```
Here, `i` is the index, and `age` is the value at that index.
Now, let's create a more detailed output using both the index and value:
```{python}
for i, age in enumerate(ages):
print(f"The person at index {i} is aged {age} years which is {age * 12} months")
```
This is particularly useful when you need both the position and the value in your loop.
::: {.callout-tip title='Practice'}
### Practice: Enumerate with F-strings
Use `enumerate()` and f-strings to print a sentence for each hour in the list:
```{python}
hours = [3, 4, 5] # List of hours
# Your code here
# Example output: "Hour 3 at index 0 is equal to 180 minutes"
```
:::
# Real Loops Application: Generating Multiple Plots
Now that you have a solid understanding of `for` loops, let's apply our knowledge to a more realistic looping task: generating multiple plots.
We'll use the `gapminder` dataset from Vega datasets to demonstrate this. Our aim is to create line plots for a few selected countries in the gapminder dataset.
First, let's load the data:
```{python}
# Load gapminder dataset
gapminder = data.gapminder()
gapminder.head()
```
Now let's create a line chart for a single country. We'll use the `query` method to filter the data for the country "Canada". We have not learned this method yet; it is a pandas function that allows us to filter the data based on a condition. We will learn more about it later in the course.
```{python}
# Filter data for China
china_data = gapminder.query("country == 'China'")
# Create line chart
fig = px.line(china_data, x="year", y="life_expect", title="Life Expectancy in China")
fig.show()
```
Now, let's create a loop to create line plots for a few selected countries.
```{python}
countries = ["India", "China", "United States", "Indonesia", "Pakistan"]
for country_name in countries:
country_data = gapminder.query("country == @country_name")
fig = px.line(
country_data,
x="year",
y="life_expect",
title=f"Life Expectancy in {country_name}",
)
fig.show()
```
This loop creates a separate line plot for each country in our list, showing how life expectancy has changed over time.
::: {.callout-tip title='Practice'}
### Practice: Population Over Time
Using the `gapminder` dataset, create a bar chart (with `px.bar`) of the population for the countries `United States`, `Canada`, `Mexico` and `Jamaica` over time.
```{python}
# Your code here
```
:::
::: {.callout-tip title='Practice'}
### Practice: Tips Histogram by Day
Using the `tips` dataset, create a histogram of the total bill for each day of the week.
```{python}
# Load tips dataset
tips = px.data.tips()
tips.head()
```
```{python}
# List of days
days = ["Thur", "Fri", "Sat", "Sun"]
# Your loop here
```
:::
# Wrap Up!
We've covered the very basics of `for` loops in Python, from simple syntax to practical data analysis applications. Loops are essential for efficient coding, allowing you to automate repetitive tasks. As we progress in the course, we will encounter many other applications of this key programming construct.