Added exerise numbers. Edits
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# 1.7 Introduction to Functions
|
||||
# 1.7 Functions
|
||||
|
||||
As your programs start to get larger, you'll want to get organized. This section
|
||||
introduces functions. Error handling with exceptions is also introduced.
|
||||
@@ -41,14 +41,15 @@ x = math.sqrt(10)
|
||||
|
||||
# `urllib.request` module
|
||||
import urllib.request
|
||||
u = urllib.request.urlopen('http://www.python.org/') data = u.read()
|
||||
u = urllib.request.urlopen('http://www.python.org/')
|
||||
data = u.read()
|
||||
```
|
||||
|
||||
We will cover libraries and modules in more detail later.
|
||||
|
||||
### Errors and exceptions
|
||||
|
||||
Errors are reported as exceptions. An exception causes the program to stop.
|
||||
Functions report errors as exceptions. An exception causes the program to stop.
|
||||
|
||||
Try this in your python REPL.
|
||||
|
||||
@@ -60,13 +61,14 @@ ValueError: invalid literal for int() with base 10: 'N/A'
|
||||
>>>
|
||||
```
|
||||
|
||||
For debugging purposes, the message describes what happened, where the error occurred and the traceback.
|
||||
For debugging purposes, the message describes what happened, where the error occurred,
|
||||
and a traceback showing the other function calls that led to the failure.
|
||||
|
||||
### Catching and Handling Exceptions
|
||||
|
||||
Exceptions can be caught and handled.
|
||||
|
||||
To catch, use `try - except` statement.
|
||||
To catch, use the `try - except` statement.
|
||||
|
||||
```python
|
||||
for line in f:
|
||||
@@ -88,7 +90,7 @@ To raise an exception, use the `raise` statement.
|
||||
raise RuntimeError('What a kerfuffle')
|
||||
```
|
||||
|
||||
This will cause the program to abord with an exception traceback. Unless caught by a `try-except` block.
|
||||
This will cause the program to abort with an exception traceback. Unless caught by a `try-except` block.
|
||||
|
||||
```bash
|
||||
% python3 foo.py
|
||||
@@ -100,7 +102,7 @@ RuntimeError: What a kerfuffle
|
||||
|
||||
## Exercises
|
||||
|
||||
### (a) Defining a function
|
||||
### Exercise 1.29: Defining a function
|
||||
|
||||
You can define a simple function using the `def` statement. For example,
|
||||
|
||||
@@ -119,12 +121,15 @@ Hello Paula
|
||||
If the first statement of a function is a string, it serves as documentation.
|
||||
Try typing a command such as `help(greeting)` to see it displayed.
|
||||
|
||||
### (b) Turning a script into a function
|
||||
### Exercise 1.30: Turning a script into a function
|
||||
|
||||
Take the code you wrote for the `pcost.py` program in the last exercise and turn it into a function `portfolio_cost(filename)`.
|
||||
The function takes a filename as input, reads the portfolio data in that file, and returns the total cost of the portfolio.
|
||||
Take the code you wrote for the `pcost.py` program in [Exercise 1.27](06_Files)
|
||||
and turn it into a function `portfolio_cost(filename)`. The
|
||||
function takes a filename as input, reads the portfolio data in that
|
||||
file, and returns the total cost of the portfolio as a float.
|
||||
|
||||
To use your function, change your program so that it looks something like this:
|
||||
To use your function, change your program so that it looks something
|
||||
like this:
|
||||
|
||||
```python
|
||||
def portfolio_cost(filename):
|
||||
@@ -137,7 +142,8 @@ print('Total cost:', cost)
|
||||
```
|
||||
|
||||
When you run your program, you should see the same output as before.
|
||||
After you’ve run your program, you can also call your function interactively by typing this:
|
||||
After you’ve run your program, you can also call your function
|
||||
interactively by typing this:
|
||||
|
||||
```bash
|
||||
bash $ python3 -i pcost.py
|
||||
@@ -151,7 +157,8 @@ This will allow you to call your function from the interactive mode.
|
||||
>>>
|
||||
```
|
||||
|
||||
Being able to experiment with your code interactively is useful for testing and debugging.
|
||||
Being able to experiment with your code interactively is useful for
|
||||
testing and debugging.
|
||||
|
||||
What happens if you try your function on a file with some missing fields?
|
||||
|
||||
@@ -170,14 +177,15 @@ you can either sanitize the original input file by eliminating bad
|
||||
lines or you can modify your code to handle the bad lines in some
|
||||
manner.
|
||||
|
||||
Modify the `pcost.py` program to catch the exception, print a warning message,
|
||||
and continue processing the rest of the file.
|
||||
Modify the `pcost.py` program to catch the exception, print a warning
|
||||
message, and continue processing the rest of the file.
|
||||
|
||||
### (c) Using a library function
|
||||
### Exercise 1.31: Using a library function
|
||||
|
||||
Python comes with a large standard library of useful functions.
|
||||
One library that might be useful here is the `csv` module. You should use it whenever you have to work with CSV data files.
|
||||
Here is an example of how it works:
|
||||
Python comes with a large standard library of useful functions. One
|
||||
library that might be useful here is the `csv` module. You should use
|
||||
it whenever you have to work with CSV data files. Here is an example
|
||||
of how it works:
|
||||
|
||||
```pycon
|
||||
>>> import csv
|
||||
@@ -200,12 +208,15 @@ Here is an example of how it works:
|
||||
>>>
|
||||
```
|
||||
|
||||
One nice thing about the `csv` module is that it deals with a variety of low-level details such as quoting and proper comma splitting.
|
||||
In the above output, you’ll notice that it has stripped the double-quotes away from the names in the first column.
|
||||
One nice thing about the `csv` module is that it deals with a variety
|
||||
of low-level details such as quoting and proper comma splitting. In
|
||||
the above output, you’ll notice that it has stripped the double-quotes
|
||||
away from the names in the first column.
|
||||
|
||||
Modify your `pcost.py` program so that it uses the `csv` module for parsing and try running earlier examples.
|
||||
Modify your `pcost.py` program so that it uses the `csv` module for
|
||||
parsing and try running earlier examples.
|
||||
|
||||
### (d) Reading from the command line
|
||||
### Exercise 1.32: Reading from the command line
|
||||
|
||||
In the `pcost.py` program, the name of the input file has been hardwired into the code:
|
||||
|
||||
@@ -221,9 +232,11 @@ cost = portfolio_cost('Data/portfolio.csv')
|
||||
print('Total cost:', cost)
|
||||
```
|
||||
|
||||
That’s fine for learning and testing, but in a real program you probably wouldn’t do that.
|
||||
That’s fine for learning and testing, but in a real program you
|
||||
probably wouldn’t do that.
|
||||
|
||||
Instead, you might pass the name of the file in as an argument to a script. Try changing the bottom part of the program as follows:
|
||||
Instead, you might pass the name of the file in as an argument to a
|
||||
script. Try changing the bottom part of the program as follows:
|
||||
|
||||
```python
|
||||
# pcost.py
|
||||
|
||||
Reference in New Issue
Block a user