Skip to content

Commit e1f22e1

Browse files
committed
update readme
1 parent 357997c commit e1f22e1

File tree

1 file changed

+38
-261
lines changed

1 file changed

+38
-261
lines changed

README.md

Lines changed: 38 additions & 261 deletions
Original file line numberDiff line numberDiff line change
@@ -1,322 +1,99 @@
11

2-
# For loops
2+
# Functions lab
33

4-
### Learning Objectives
4+
As we know, we can use functions to give a name to sequences of our code, to make it more expressive. We can also use functions to allow us to reuse code. In this lab we will get practice in using functions for these purposes.
55

6-
* Understand the components of a point in a graph, an $x$ value, and a $y$ value
7-
* Understand how to plot a point on a graph, from a point's $x$ and $y$ value
8-
* Get a sense of how to use a graphing library, like Plotly, to answer questions about our data
6+
### Objectives
97

10-
### Picking up where we last left off
8+
* Practice declaring and returning values from function
9+
* Practice accessing variables outside of a function's scope, from inside of a function
1110

12-
In the last lesson, we plotted some of our travel data.
11+
### Writing our first functions
1312

14-
15-
```python
16-
import pandas
17-
file_name = './cities.xlsx'
18-
travel_df = pandas.read_excel(file_name)
19-
cities = travel_df.to_dict('records')
20-
```
21-
22-
23-
```python
24-
import plotly
25-
26-
plotly.offline.init_notebook_mode(connected=True)
27-
28-
x_values = [cities[0]['City'], cities[1]['City'], cities[2]['City']]
29-
y_values = [cities[0]['Population'], cities[1]['Population'], cities[2]['Population']]
30-
31-
trace_first_three_pops = {'x': x_values, 'y': y_values, 'type': 'bar'}
32-
# plotly.offline.iplot([trace_first_three_pops])
33-
```
34-
35-
36-
<script>requirejs.config({paths: { 'plotly': ['https://cdn.plot.ly/plotly-latest.min']},});if(!window.Plotly) {{require(['plotly'],function(plotly) {window.Plotly=plotly;});}}</script>
37-
38-
39-
Let's take another look at our `x_values` variable.
40-
41-
42-
```python
43-
x_values = [cities[0]['City'], cities[1]['City'], cities[2]['City']]
44-
```
45-
46-
As you can see, we go one by one through the `cities` list, and for each element of the cities list, we retrieve the `City` attribute. This procedure of going one by one, and doing the same thing can be automated with the `for` loop.
47-
48-
### Learning Objectives
49-
50-
### Introduction to the For Loop
51-
52-
A `for` loop in Python, is good at going through elements of a list one by one. Let's take an initial array.
53-
54-
55-
```python
56-
zero_to_three = [0, 1, 2, 3]
57-
```
58-
59-
Now to print the elements of a list, we currently do the following:
60-
61-
62-
```python
63-
print(zero_to_three[0])
64-
print(zero_to_three[1])
65-
print(zero_to_three[2])
66-
```
67-
68-
0
69-
1
70-
2
71-
72-
73-
So we increase the index by one each time, starting at the number zero and ending at the number 2. A `for` loop is great at going through these elements in the list. For example:
74-
75-
76-
```python
77-
for i in [0, 1, 2]:
78-
print(i + 5)
79-
```
80-
81-
5
82-
6
83-
7
84-
85-
86-
So note that above, our expression prints three times: once for each element in our list. The first time it starts with the number 0, for that is the first element in the array, and then it goes forward to the second element, and then the third. So we can use the `for` loop to operate on the numbers zero through two, and the `i` represents a successive element in our list each time.
87-
88-
Pay careful attention to the syntax. Essentially, Python needs to know when the body of the loop begins and when it ends. So we mark the beginning of the loop's body with a colon, `:`, and then indent each successive line of the loop. (If you press enter after the colon, the indent will come automatically). To end the body of the loop, we simply unindent.
89-
90-
91-
```python
92-
for i in [0, 1, 2]:
93-
print(i + 5)
94-
print(10)
95-
```
96-
97-
5
98-
6
99-
7
100-
10
101-
102-
103-
Just like any other variable, we can call the `i` whatever we like.
104-
105-
106-
```python
107-
for number in [0, 1, 2]:
108-
print(number + 5)
109-
```
110-
111-
5
112-
6
113-
7
114-
115-
116-
We just have to make sure that whatever word we use after `for` is referenced in our loop later on.
117-
118-
119-
```python
120-
for number in [0, 1, 2]:
121-
print(what + 5)
122-
```
123-
124-
125-
---------------------------------------------------------------------------
126-
127-
NameError Traceback (most recent call last)
128-
129-
<ipython-input-23-ba9129ae8cfe> in <module>()
130-
1 for number in [0, 1, 2]:
131-
----> 2 print(what + 5)
132-
133-
134-
NameError: name 'what' is not defined
135-
136-
137-
### Using list elements as indices
138-
139-
In the above section we iterated through a list of successive numbers. Now remember that to access elements of any lists, we use a number to do so.
13+
Imagine we work in a diner. We have a list of `orders` which we assign below. Write a function called `number_of_orders` that returns the current number of orders.
14014

14115

14216
```python
143-
countries = ['Croatia', 'USA', 'Argentina']
17+
orders = ['turkey sandwich', 'eggs']
18+
def number_of_orders():
19+
pass
14420
```
14521

14622

14723
```python
148-
countries[0]
24+
number_of_orders() # 2
14925
```
15026

151-
152-
153-
154-
'Croatia'
155-
156-
27+
Now write another function called `next_up` that returns the first order (the order with the lowest index), in the `orders` list.
15728

15829

15930
```python
160-
countries[2]
31+
def next_up():
32+
pass
16133
```
16234

16335

164-
165-
166-
'Argentina'
167-
168-
169-
170-
So to iterate through the elements of `countries`, we can do the following:
171-
172-
17336
```python
174-
for i in [0, 1, 2]:
175-
print(countries[i])
176-
```
177-
178-
Croatia
179-
USA
180-
Argentina
181-
37+
orders = ['turkey sandwich', 'eggs']
38+
next_up() # 'turkey sandwich'
18239

183-
So notice what happened there. Just like previously, our loop variable, `i`, is a different element of the list each time. Because these elements are also the increasing indices for our list of `countries`, we can use them to access and then operate on the elements of the `countries`.
184-
185-
186-
```python
187-
for i in [0, 1, 2]:
188-
print(i)
189-
print(countries[i])
40+
orders = ['beet salad', 'fennel']
41+
next_up() # 'beet salad'
19042
```
19143

192-
0
193-
Croatia
194-
1
195-
USA
196-
2
197-
Argentina
198-
199-
200-
Of course, this only works if the elements of the list match up with the size of our list. So it would be nice to perform some calculation to ensure that this is the case. Let's do it.
201-
202-
We can use the `len` function to calculate the size of our list.
44+
Ok, now write a function called `healthy_order` that returns the string `'spinach salad'`.
20345

20446

20547
```python
206-
len(countries)
48+
def healthy_order():
49+
pass
20750
```
20851

20952

210-
211-
212-
3
213-
214-
215-
216-
Then we can turn this length into a successive list of elements with the following:
217-
218-
First, create a range object:
219-
220-
22153
```python
222-
range(0, len(countries))
54+
healthy_order() # 'spinach salad'
22355
```
22456

225-
226-
227-
228-
range(0, 3)
229-
230-
231-
232-
And then convert this into a list:
57+
Now let's declare an array called `orders`. Change the function `healthy_order` so that it continues to return the string `'spinach salad'`, but also adds the string `'spinach salad'` to the end of the list of orders.
23358

23459

23560
```python
236-
list(range(0, len(countries)))
61+
orders = ['turkey sandwich', 'eggs']
62+
healthy_order()
63+
orders[-1] # 'spinach salad'
23764
```
23865

23966

24067

24168

242-
[0, 1, 2]
69+
'eggs'
24370

24471

24572

246-
Note that the range object is marking the starting and ending point, and excluding the end. So this works perfectly:
73+
Now let's write another function iterates through the list of `orders` and capitalizes the first letter of each word in the order. It should return a list of capitalized orders.
24774

24875

24976
```python
250-
for i in list(range(0, len(countries))):
251-
print(countries[i])
77+
orders = ['spinach salad', 'turkey sandwich']
78+
def capitalize_orders():
79+
pass
25280
```
25381

254-
Croatia
255-
USA
256-
Argentina
257-
258-
259-
And as we add or subtract countries, we will still be iterating through our list elements.
260-
26182

26283
```python
263-
countries = ['Croatia', 'USA', 'Argentina']
264-
countries.append('Mexico')
265-
for i in list(range(0, len(countries))):
266-
print(countries[i])
84+
capitalize_orders() # ['Spinach Salad', 'Turkey Sandwich']
26785
```
26886

269-
Croatia
270-
USA
271-
Argentina
272-
Mexico
273-
274-
275-
### Iterating through different datatypes
276-
277-
So far our loop variable has always been an element of a list that is a number. However, our block variable can represent any data type. For example, let's have the block variable represent each of the countries directly:
87+
Now if someone adds, an upcapitalized order, we can simply call our function again to return a list of capitalized orders.
27888

27989

28090
```python
281-
countries = ['Croatia', 'USA', 'Argentina']
282-
for i in countries:
283-
print(i)
91+
orders = ['spinach salad', 'turkey sandwich']
92+
capitalize_orders() # ['Spinach Salad', 'Turkey Sandwich']
93+
orders.append('eggs')
94+
capitalize_orders() # ['Spinach Salad', 'Turkey Sandwich', 'Eggs']
28495
```
28596

286-
Croatia
287-
USA
288-
Argentina
289-
290-
291-
So now `i` points to each element of the `countries` list. We previously used `i` as `i` was equal to an index of a list. However, here our block variable will equal an individual country. Might as well be expressive:
292-
293-
294-
```python
295-
for country in countries:
296-
print(country)
297-
```
298-
299-
Croatia
300-
USA
301-
Argentina
302-
303-
304-
This is a standard pattern. The variable name pointing to a list is plural, and to refer to a singular element as a loop variable, use the singular version. So if we were printing out a list of friends name, we would write it as the following:
305-
306-
307-
```python
308-
friends = ['Bob', 'Sally', 'Fred']
309-
for friend in friends:
310-
print(friend)
311-
```
312-
313-
Bob
314-
Sally
315-
Fred
316-
317-
318-
And there we are printing out a list of friends.
319-
32097
### Summary
32198

322-
In this section, we saw how we can use loops to iterate through various elements. This is a very powerful
99+
Great job. Through this lab you were able to get practice both writing and returning values from functions. You also practiced accessing variables not local to the function, but in the global scope.

0 commit comments

Comments
 (0)