Skip to content

Commit 7352f3d

Browse files
committed
Update writing-functions.md
1 parent e25308e commit 7352f3d

1 file changed

Lines changed: 0 additions & 356 deletions

File tree

episodes/writing-functions.md

Lines changed: 0 additions & 356 deletions
Original file line numberDiff line numberDiff line change
@@ -203,362 +203,6 @@ def fahr_to_celsius(temp):
203203
```
204204

205205

206-
::::::::::::::::::::::::::::::::::::::: challenge
207-
208-
## Definition and Use
209-
210-
What does the following program print?
211-
212-
```python
213-
def report(pressure):
214-
print(f'pressure is {pressure}')
215-
216-
report(22.5)
217-
```
218-
219-
::::::::::::::: solution
220-
221-
## Solution
222-
223-
```output
224-
pressure is 22.5
225-
```
226-
227-
:::::::::::::::::::::::::
228-
229-
::::::::::::::::::::::::::::::::::::::::::::::::::
230-
231-
::::::::::::::::::::::::::::::::::::::: challenge
232-
233-
## Order of Operations
234-
235-
The example above:
236-
237-
```python
238-
result = print_date(1871, 3, 19)
239-
print(f'result of call is: {result}')
240-
```
241-
242-
printed:
243-
244-
```output
245-
1871/3/19
246-
result of call is: None
247-
```
248-
249-
Explain why the two lines of output appeared in the order they did.
250-
251-
::::::::::::::: solution
252-
253-
## Solution
254-
255-
Each line of Python code is executed in order, regardless of whether that line calls
256-
out to a function, which may call out to other functions, or a
257-
variable assignment. In this case, the second line call to `print` will not execute until
258-
the result of `print_date` is complete in the first line.
259-
260-
261-
262-
:::::::::::::::::::::::::
263-
264-
::::::::::::::::::::::::::::::::::::::::::::::::::
265-
266-
::::::::::::::::::::::::::::::::::::::: challenge
267-
268-
## Encapsulation
269-
270-
Fill in the blanks to create a function that takes a single filename as an argument,
271-
loads the data in the file named by the argument,
272-
and returns the minimum value in that data.
273-
274-
```python
275-
import pandas
276-
277-
def min_in_data(____):
278-
data = ____
279-
return ____
280-
```
281-
282-
::::::::::::::: solution
283-
284-
## Solution
285-
286-
```python
287-
import pandas
288-
289-
def min_in_data(filename):
290-
data = pandas.read_csv(filename)
291-
return data.min()
292-
```
293-
294-
:::::::::::::::::::::::::
295-
296-
::::::::::::::::::::::::::::::::::::::::::::::::::
297-
298-
::::::::::::::::::::::::::::::::::::::: challenge
299-
300-
## Find the First
301-
302-
Fill in the blanks to create a function that takes a list of numbers as an argument
303-
and returns the first negative value in the list.
304-
What does your function do if the list is empty?
305-
306-
```python
307-
def first_negative(values):
308-
for v in ____:
309-
if ____:
310-
return ____
311-
```
312-
313-
::::::::::::::: solution
314-
315-
## Solution
316-
317-
```python
318-
def first_negative(values):
319-
for v in values:
320-
if v < 0:
321-
return v
322-
```
323-
324-
:::::::::::::::::::::::::
325-
326-
::::::::::::::::::::::::::::::::::::::::::::::::::
327-
328-
::::::::::::::::::::::::::::::::::::::: challenge
329-
330-
## Calling by Name
331-
332-
What does this short program print?
333-
334-
```python
335-
def print_date(year, month, day):
336-
joined = f'{year}/{month}/{day}'
337-
print(joined)
338-
339-
print_date(day=1, month=2, year=2003)
340-
```
341-
342-
1. When have you seen a function call like this before?
343-
2. When and why is it useful to call functions this way?
344-
345-
::::::::::::::: solution
346-
347-
## Solution
348-
349-
The program prints:
350-
351-
```output
352-
2003/2/1
353-
```
354-
355-
It is useful to call a function with named arguments to ensure that the
356-
values of each argument are assigned to the intended argument in the
357-
function. This allows the order of arguments to be specified independently
358-
of how they are defined in the function itself.
359-
360-
361-
362-
:::::::::::::::::::::::::
363-
364-
::::::::::::::::::::::::::::::::::::::::::::::::::
365-
366-
::::::::::::::::::::::::::::::::::::::: challenge
367-
368-
## Encapsulate of If/Print Block
369-
370-
The code below will run on a label-printer for chicken eggs. A digital scale will report a chicken egg mass (in grams) to the computer and then the computer will print a label.
371-
372-
Please re-write the code so that the if-block is folded into a function.
373-
374-
```python
375-
import random
376-
for i in range(10):
377-
378-
# simulating the mass of a chicken egg
379-
# the (random) mass will be 70 +/- 20 grams
380-
mass=70+20.0*(2.0*random.random()-1.0)
381-
382-
print(mass)
383-
384-
#egg sizing machinery prints a label
385-
if(mass>=85):
386-
print("jumbo")
387-
elif(mass>=70):
388-
print("large")
389-
elif(mass<70 and mass>=55):
390-
print("medium")
391-
else:
392-
print("small")
393-
```
394-
395-
The simplified program follows. What function definition will make it functional?
396-
397-
```python
398-
# revised version
399-
import random
400-
for i in range(10):
401-
402-
# simulating the mass of a chicken egg
403-
# the (random) mass will be 70 +/- 20 grams
404-
mass=70+20.0*(2.0*random.random()-1.0)
405-
406-
print(mass,print_egg_label(mass))
407-
408-
```
409-
410-
1. Create a function definition for `print_egg_label()` that will work with the revised program above. Note, the function's return value will be significant. Sample output might be `71.23 large`.
411-
2. A dirty egg might have a mass of more than 90 grams, and a spoiled or broken egg will probably have a mass that's less than 50 grams. Modify your `print_egg_label()` function to account for these error conditions. Sample output could be `25 too light, probably spoiled`.
412-
413-
::::::::::::::: solution
414-
415-
## Solution
416-
417-
```python
418-
def print_egg_label(mass):
419-
if(mass>=90):
420-
print(mass, "dirty")
421-
elif(mass>=85):
422-
print(mass, "jumbo")
423-
elif(mass>=70):
424-
print(mass, "large")
425-
elif(mass<70 and mass>=55):
426-
print(mass, "medium")
427-
else:
428-
print(mass, "too light, probably spoiled")
429-
```
430-
431-
:::::::::::::::::::::::::
432-
433-
::::::::::::::::::::::::::::::::::::::::::::::::::
434-
435-
::::::::::::::::::::::::::::::::::::::: challenge
436-
437-
## Encapsulating Data Analysis
438-
439-
Assume that the following code has been executed:
440-
441-
```python
442-
import pandas
443-
444-
df = pandas.read_csv('gapminder_gdp_asia.csv', index_col=0)
445-
japan = df.ix['Japan']
446-
```
447-
448-
1. Complete the statements below to obtain the average GDP for Japan
449-
across the years reported for the 1980s.
450-
451-
```python
452-
year = 1983
453-
gdp_decade = 'gdpPercap_' + str(year // ____)
454-
avg = (japan.ix[gdp_decade + ___] + japan.ix[gdp_decade + ___]) / 2
455-
```
456-
457-
2. Abstract the code above into a single function.
458-
459-
```python
460-
def avg_gdp_in_decade(country, continent, year):
461-
df = pd.read_csv('gapminder_gdp_'+___+'.csv',delimiter=',',index_col=0)
462-
____
463-
____
464-
____
465-
return avg
466-
```
467-
468-
3. How would you generalize this function
469-
if you did not know beforehand which specific years occurred as columns in the data?
470-
For instance, what if we also had data from years ending in 1 and 9 for each decade?
471-
(Hint: use the columns to filter out the ones that correspond to the decade,
472-
instead of enumerating them in the code.)
473-
474-
::::::::::::::: solution
475-
476-
## Solution
477-
478-
1.
479-
```python
480-
year = 1983
481-
gdp_decade = 'gdpPercap_' + str(year // 10)
482-
avg = (japan.ix[gdp_decade + '2'] + japan.ix[gdp_decade + '7']) / 2
483-
```
484-
485-
2.
486-
```python
487-
def avg_gdp_in_decade(country, continent, year):
488-
df = pd.read_csv('gapminder_gdp_' + continent + '.csv', index_col=0)
489-
c = df.ix[country]
490-
gdp_decade = 'gdpPercap_' + str(year // 10)
491-
avg = (c.ix[gdp_decade + '2'] + c.ix[gdp_decade + '7'])/2
492-
return avg
493-
```
494-
495-
3. We need to loop over the reported years
496-
to obtain the average for the relevant ones in the data.
497-
498-
```python
499-
def avg_gdp_in_decade(country, continent, year):
500-
df = pd.read_csv('gapminder_gdp_' + continent + '.csv', index_col=0)
501-
c = df.ix[country]
502-
gdp_decade = 'gdpPercap_' + str(year // 10)
503-
total = 0.0
504-
num_years = 0
505-
for yr_header in c.index: # c's index contains reported years
506-
if yr_header.startswith(gdp_decade):
507-
total = total + c.ix[yr_header]
508-
num_years = num_years + 1
509-
return total/num_years
510-
```
511-
512-
:::::::::::::::::::::::::
513-
514-
::::::::::::::::::::::::::::::::::::::::::::::::::
515-
516-
::::::::::::::::::::::::::::::::::::::: challenge
517-
518-
## Local and Global Variable Use
519-
520-
Trace the values of all variables in this program as it is executed.
521-
(Use '---' as the value of variables before and after they exist.)
522-
523-
```python
524-
limit = 100
525-
526-
def clip(value):
527-
return min(max(0.0, value), limit)
528-
529-
value = -22.5
530-
print(clip(value))
531-
```
532-
533-
::::::::::::::: solution
534-
535-
## Solution
536-
537-
```python
538-
# limit = ---
539-
# value = ---
540-
541-
limit = 100
542-
543-
def clip(value):
544-
return min(max(0.0, value), limit)
545-
546-
# limit = 100
547-
# value = ---
548-
549-
value = -22.5 # value = -22.5, limit = 100
550-
551-
print(clip(value)) # result is 0.0
552-
553-
# value = -22.5
554-
# limit = 100
555-
```
556-
557-
:::::::::::::::::::::::::
558-
559-
::::::::::::::::::::::::::::::::::::::::::::::::::
560-
561-
562206
:::::::::::::::::::::::::::::::::::::::: keypoints
563207

564208
- Break programs down into functions to make them easier to understand.

0 commit comments

Comments
 (0)