Added exerise numbers. Edits
This commit is contained in:
@@ -1,12 +1,10 @@
|
||||
# 1.1 Python
|
||||
|
||||
In this part, we'll start with the absolute basics of Python.
|
||||
|
||||
### What is Python?
|
||||
|
||||
Python is an interpreted high level programming language. It is often classified as a
|
||||
["scripting language"](https://en.wikipedia.org/wiki/Scripting_language) and
|
||||
is considered to be similar to languages such as Perl, Tcl, or Ruby. The syntax
|
||||
is considered similar to languages such as Perl, Tcl, or Ruby. The syntax
|
||||
of Python is loosely inspired by elements of C programming.
|
||||
|
||||
Python was created by Guido van Rossum around 1990 who named it in honor of Monty Python.
|
||||
@@ -14,12 +12,12 @@ Python was created by Guido van Rossum around 1990 who named it in honor of Mont
|
||||
### Where to get Python?
|
||||
|
||||
[Python.org](https://www.python.org/) is where you obtain Python. For the purposes of this course, you
|
||||
only need a basic installation. We recommend installing Python 3.6 or newer. We will be using Python3 in
|
||||
our solutions and notes.
|
||||
only need a basic installation. I recommend installing Python 3.6 or newer. Python 3.6 is used in the notes
|
||||
and solutions.
|
||||
|
||||
### Why was Python created?
|
||||
|
||||
According to Guido:
|
||||
In the words of Python's creator:
|
||||
|
||||
> My original motivation for creating Python was the perceived need
|
||||
> for a higher level language in the Amoeba [Operating Systems]
|
||||
@@ -34,9 +32,9 @@ According to Guido:
|
||||
### Where is Python on my Machine?
|
||||
|
||||
Although there are many environments in which you might run Python,
|
||||
this course has you run Python programs from the terminal or command
|
||||
shell. From the terminal, you should be able to type a command such as
|
||||
this:
|
||||
Python is typically installed on your machine as a program that runs
|
||||
from the terminal or command shell. From the terminal, you should be
|
||||
able to type `python` like this:
|
||||
|
||||
```
|
||||
bash $ python
|
||||
@@ -51,15 +49,15 @@ hello world
|
||||
If you are new to using the shell or a terminal, you should probably
|
||||
stop, finish a short tutorial on that first, and then return here.
|
||||
|
||||
Just so you know, you will become a much better Python programmer if
|
||||
you are able to run, debug, and interact with Python at the terminal
|
||||
shell. This is Python's native environment. If you are able to use
|
||||
Python in the shell, you will be able to use virtually everywhere
|
||||
else.
|
||||
Although there are many non-shell environments where you can code
|
||||
Python, you will be a stronger Python programmer if you are able to
|
||||
run, debug, and interact with Python at the terminal. This is
|
||||
Python's native environment. If you are able to use Python here, you
|
||||
will be able to use it everywhere else.
|
||||
|
||||
## Exercises
|
||||
|
||||
### (a) Using Python as a Calculator
|
||||
### Exercise 1.1: Using Python as a Calculator
|
||||
|
||||
On your machine, start Python and use it as a calulator to solve the
|
||||
following problem.
|
||||
@@ -85,7 +83,7 @@ broker takes their 20% cut?
|
||||
>>>
|
||||
```
|
||||
|
||||
### (b) Getting help
|
||||
### Exercise 1.2: Getting help
|
||||
|
||||
Use the `help()` command to get help on the `abs()` function. Then use
|
||||
`help()` to get help on the `round()` function. Type `help()` just by
|
||||
@@ -101,18 +99,19 @@ Followup: Go to <http://docs.python.org> and find the documentation for
|
||||
the `abs()` function (hint: it’s found under the library reference
|
||||
related to built-in functions).
|
||||
|
||||
### (c) Cutting and Pasting
|
||||
### Exercise 1.3: Cutting and Pasting
|
||||
|
||||
As you've noticed, this course is structured as a series of traditional
|
||||
web pages where you are encouraged to try interactive code samples by typing them
|
||||
by hand. If you are learning Python for the first time, this is encouraged.
|
||||
You will get a better feel for the language by slowing down, typing things in,
|
||||
and thinking about what you are doing.
|
||||
This course is structured as a series of traditional web pages where
|
||||
you are encouraged to try interactive Python code samples **by typing
|
||||
them out by hand.** If you are learning Python for the first time,
|
||||
this "slow approach" is encouraged. You will get a better feel for
|
||||
the language by slowing down, typing things in, and thinking about
|
||||
what you are doing.
|
||||
|
||||
If you are inclined to use "cut and paste" in the editor, select code
|
||||
If you must "cut and paste" code samples, select code
|
||||
starting after the `>>>` prompt and going up to, but not any further
|
||||
than the first blank line or the next `>>>` prompt (whichever appears
|
||||
first). Select "copy" from the brower, go to the Python window, and
|
||||
first). Select "copy" from the browser, go to the Python window, and
|
||||
select "paste" to copy it into the Python shell. To get the code to
|
||||
run, you may have to hit "Return" once after you’ve pasted it in.
|
||||
|
||||
@@ -139,12 +138,14 @@ Warning: It is never possible to paste more than one Python command
|
||||
(statements that appear after `>>>`) to the basic Python shell at a
|
||||
time. You have to paste each command one at a time.
|
||||
|
||||
### (d) Where is My Bus?
|
||||
Now that you've done this, just remember that you will get more out of
|
||||
the class by typing in code slowly and thinking about it--not cut and pasting.
|
||||
|
||||
If you’ve made it this far, try something more advanced and type these
|
||||
statements to find out how long people waiting on the corner of Clark
|
||||
street and Balmoral in Chicago will have to wait for the next
|
||||
northbound CTA \#22 bus:
|
||||
### Exercise 1.4: Where is My Bus?
|
||||
|
||||
Try something more advanced and type these statements to find out how
|
||||
long people waiting on the corner of Clark street and Balmoral in
|
||||
Chicago will have to wait for the next northbound CTA \#22 bus:
|
||||
|
||||
```pycon
|
||||
>>> import urllib.request
|
||||
@@ -181,5 +182,8 @@ exercise work. For example:
|
||||
>>>
|
||||
```
|
||||
|
||||
If you can't make this work, don't worry about it. The rest of this course
|
||||
has nothing to do with parsing XML.
|
||||
|
||||
[Contents](../Contents) \| [Next (1.2 A First Program)](02_Hello_world)
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
# 1.2 A First Python Program
|
||||
# 1.2 A First Program
|
||||
|
||||
This section discusses the creation of your first program, running the interpreter,
|
||||
and some basic debugging.
|
||||
This section discusses the creation of your first program, running the
|
||||
interpreter, and some basic debugging.
|
||||
|
||||
### Running Python
|
||||
|
||||
Python programs run inside an interpreter.
|
||||
Python programs always run inside an interpreter.
|
||||
|
||||
The interpreter is a simple "console-based" application that normally starts from a command shell.
|
||||
The interpreter is a "console-based" application that normally runs
|
||||
from a command shell.
|
||||
|
||||
```bash
|
||||
python3
|
||||
@@ -18,15 +19,16 @@ Type "help", "copyright", "credits" or "license" for more information.
|
||||
```
|
||||
|
||||
Expert programmers usually have no problem using the interpreter in
|
||||
this way, but it's not so user-friendly for beginners. That said,
|
||||
you'll become a better Python programmer if you're able to use the
|
||||
interpreter from the shell earlier rather than later.
|
||||
this way, but it's not so user-friendly for beginners. You may be using
|
||||
an environment that provides a different interface to Python. That's fine,
|
||||
but learning how to run Python terminal is still a useful skill to know.
|
||||
|
||||
### Interactive Mode
|
||||
|
||||
When you start Python, you get an *interactive* mode where you can experiment.
|
||||
|
||||
If you start typing statements, they will run immediately. There is no edit/compile/run/debug cycle.
|
||||
If you start typing statements, they will run immediately. There is no
|
||||
edit/compile/run/debug cycle.
|
||||
|
||||
```python
|
||||
>>> print('hello world')
|
||||
@@ -44,12 +46,12 @@ hello world
|
||||
>>>
|
||||
```
|
||||
|
||||
This *read-eval* loop is very useful for debugging and exploration.
|
||||
This so-called *read-eval* loop is very useful for debugging and exploration.
|
||||
|
||||
Let's take a closer look at the elements:
|
||||
|
||||
- `>>>` is the interpreter prompt for starting a new statement.
|
||||
- `...` is the interpreter prompt for continuing a statements. Enter a blank like to finish typing and run the statements.
|
||||
- `...` is the interpreter prompt for continuing a statements. Enter a blank line to finish typing and run the statements.
|
||||
|
||||
The `...` prompt may or may not be shown depending on how you are using Python. For this course,
|
||||
it is shown as blanks to make it easier to cut/paste code samples.
|
||||
@@ -68,26 +70,6 @@ The underscore `_` holds the last result.
|
||||
|
||||
*This is only true in the interactive mode.* You never use `_` in a program.
|
||||
|
||||
|
||||
Type `help(command)` to get information about `command`. Type `help()` with no name for interactive help.
|
||||
|
||||
```code
|
||||
>>> help(range)
|
||||
Help on class range in module builtins:
|
||||
|
||||
class range(object)
|
||||
| range(stop) -> range object
|
||||
| range(start, stop[, step]) -> range object
|
||||
|
|
||||
| Return an object that produces a sequence of integers from start (inclusive)
|
||||
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
|
||||
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
|
||||
| These are exactly the valid indices for a list of 4 elements.
|
||||
| When step is given, it specifies the increment (or decrement).
|
||||
```
|
||||
|
||||
The official documentation is at [http://docs.python.org](http://docs.python.org).
|
||||
|
||||
### Creating programs
|
||||
|
||||
Programs are put in `.py` files.
|
||||
@@ -105,7 +87,7 @@ To execute a program, run it in the terminal with the `python` command.
|
||||
For example, in command-line Unix:
|
||||
|
||||
```bash
|
||||
bash % python3 hello.py
|
||||
bash % python hello.py
|
||||
hello world
|
||||
bash %
|
||||
```
|
||||
@@ -124,9 +106,9 @@ Note: On Windows, you may need to specify a full path to the Python interpreter
|
||||
|
||||
### A Sample Program
|
||||
|
||||
Let's begin this part by trying to solve the following problem:
|
||||
Let's solve the following problem:
|
||||
|
||||
> One morning, you go out and place a dollar bill on the sidewalk by the Sears tower.
|
||||
> One morning, you go out and place a dollar bill on the sidewalk by the Sears tower in Chicago.
|
||||
> Each day thereafter, you go out double the number of bills.
|
||||
> How long does it take for the stack of bills to exceed the height of the tower?
|
||||
|
||||
@@ -149,7 +131,7 @@ print('Number of bills', num_bills)
|
||||
print('Final height', num_bills * bill_thickness)
|
||||
```
|
||||
|
||||
When we run it, we have the solution.
|
||||
When you run it, you get the following output:
|
||||
|
||||
```bash
|
||||
bash % python3 sears.py 1 1 0.00011
|
||||
@@ -163,7 +145,7 @@ bash % python3 sears.py 1 1 0.00011
|
||||
22 2097152 230.68672 Number of days 23 Number of bills 4194304 Final height 461.37344
|
||||
```
|
||||
|
||||
Using this program as a guide, you can learn a few core concepts about Python.
|
||||
Using this program as a guide, you can learn a number of important core concepts about Python.
|
||||
|
||||
### Statements
|
||||
|
||||
@@ -175,7 +157,7 @@ b = a * 2
|
||||
print(b)
|
||||
```
|
||||
|
||||
Each statement is terminated by a newline. Statements are executed one after the other until you reach the end of the file.
|
||||
Each statement is terminated by a newline. Statements are executed one after the other until control reaches the end of the file.
|
||||
|
||||
### Comments
|
||||
|
||||
@@ -235,8 +217,7 @@ WHILE x < 0: # ERROR
|
||||
|
||||
### Looping
|
||||
|
||||
Looping is a way to execute a set of instructions any number of times.
|
||||
There are many ways to accomplish this in Python, one of them is the `while` statement:
|
||||
The `while` statement executes a loop.
|
||||
|
||||
```python
|
||||
while num_bills * bill_thickness < sears_height:
|
||||
@@ -252,7 +233,7 @@ The statements below the `while` will execute as long as the expression after th
|
||||
### Indentation
|
||||
|
||||
Indentation in Python is used to denote a set of statements that go together.
|
||||
From our previous example:
|
||||
Consider the previous example:
|
||||
|
||||
```python
|
||||
while num_bills * bill_thickness < sears_height:
|
||||
@@ -263,7 +244,8 @@ while num_bills * bill_thickness < sears_height:
|
||||
print('Number of days', days)
|
||||
```
|
||||
|
||||
The indentation means that the following statements go together under the `while`.
|
||||
Indentation groups the following statements together as the operations that
|
||||
execute repeatedly:
|
||||
|
||||
```python
|
||||
print(day, num_bills, num_bills * bill_thickness)
|
||||
@@ -271,8 +253,8 @@ The indentation means that the following statements go together under the `while
|
||||
num_bills = num_bills * 2
|
||||
```
|
||||
|
||||
Because the next statement is not indented, it means that it does not
|
||||
belong to the previous set. The empty line is just for
|
||||
Because the `print()` statement at the end is not indented, it means
|
||||
that it does not belong to the loop. The empty line is just for
|
||||
readability. It does not affect the execution.
|
||||
|
||||
### Indentation best practices
|
||||
@@ -281,7 +263,8 @@ readability. It does not affect the execution.
|
||||
* Use 4 spaces per level.
|
||||
* Use a Python-aware editor.
|
||||
|
||||
Indentation within the block must be consistent.
|
||||
Python's only requirement is that indentation within the same block
|
||||
be consistent. For example, this is an error:
|
||||
|
||||
```python
|
||||
while num_bills * bill_thickness < sears_height:
|
||||
@@ -290,7 +273,6 @@ while num_bills * bill_thickness < sears_height:
|
||||
num_bills = num_bills * 2
|
||||
```
|
||||
|
||||
|
||||
### Conditionals
|
||||
|
||||
The `if` statement is used to execute a conditional:
|
||||
@@ -306,7 +288,7 @@ else:
|
||||
|
||||
Depending on the values of `a` and `b`, the execution will jump to `print('Computer says no')` or `print('Computer says yes')`.
|
||||
|
||||
You can check for multiple conditions with the `elif`.
|
||||
You can check for multiple conditions by adding extra checks using `elif`.
|
||||
|
||||
```python
|
||||
if a > b:
|
||||
@@ -335,14 +317,14 @@ x = 100
|
||||
print(x) # Prints the text '100'
|
||||
```
|
||||
|
||||
If you pass more than one item to `print` they are separated by spaces.
|
||||
If you pass more than one value to `print` they are separated by spaces.
|
||||
|
||||
```python
|
||||
name = 'Jake'
|
||||
print('My name is', name) # Print the text 'My name is Jake'
|
||||
```
|
||||
|
||||
`print()` always creates a new line at the end.
|
||||
`print()` always puts a new line at the end.
|
||||
|
||||
```python
|
||||
print('Hello')
|
||||
@@ -356,14 +338,14 @@ Hello
|
||||
My name is Jake
|
||||
```
|
||||
|
||||
This can be avoided.
|
||||
The extra newline can be suppressed:
|
||||
|
||||
```python
|
||||
print('Hello', end=' ')
|
||||
print('My name is', 'Jake')
|
||||
```
|
||||
|
||||
The previous code will print:
|
||||
This code will now print:
|
||||
|
||||
```code
|
||||
Hello My name is Jake
|
||||
@@ -378,13 +360,13 @@ name = input('Enter your name:')
|
||||
print('Your name is', name)
|
||||
```
|
||||
|
||||
`input` prints a prompt to the user and returns the response.
|
||||
`input` prints a prompt to the user and returns their response.
|
||||
This is useful for small programs, learning exercises or simple debugging.
|
||||
It is not widely used for real programs.
|
||||
|
||||
### `pass` statement
|
||||
|
||||
Sometimes you need to specify an empty block. The keyword `pass` is used for it.
|
||||
Sometimes you need to specify an empty code block. The keyword `pass` is used for it.
|
||||
|
||||
```python
|
||||
if a > b:
|
||||
@@ -393,11 +375,11 @@ else:
|
||||
print('Computer says false')
|
||||
```
|
||||
|
||||
This is also called a "no-op" statement. It does nothing. It serves as a placeholder for statements. Possibly to be added later.
|
||||
This is also called a "no-op" statement. It does nothing. It serves as a placeholder for statements, possibly to be added later.
|
||||
|
||||
## Exercises
|
||||
|
||||
### (a) The Bouncing Ball
|
||||
### Exercise 1.5: The Bouncing Ball
|
||||
|
||||
A rubber ball is dropped from a height of 100 meters and each time it hits the ground, it bounces back up to 3/5 the height it fell.
|
||||
Write a program "bounce.py" that prints a table showing the height of the first 10 bounces.
|
||||
@@ -432,7 +414,7 @@ Your program should make a table that looks something like this:
|
||||
10 0.6047
|
||||
```
|
||||
|
||||
### (b) Debugging
|
||||
### Exercise 1.6: Debugging
|
||||
|
||||
The following code fragment contains code from the Sears tower problem. It also has a bug in it.
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# 1.3 Numbers
|
||||
|
||||
This section covers some basics of performing mathematical calculations in Python.
|
||||
|
||||
### Types of Numbers
|
||||
|
||||
Python has 4 types of numbers:
|
||||
@@ -11,7 +9,7 @@ Python has 4 types of numbers:
|
||||
* Floating point
|
||||
* Complex (imaginary numbers)
|
||||
|
||||
### Booleans
|
||||
### Booleans (bool)
|
||||
|
||||
Booleans have two values: `True`, `False`.
|
||||
|
||||
@@ -29,9 +27,9 @@ if d == 0:
|
||||
print('d is False')
|
||||
```
|
||||
|
||||
*Don't do that, it would be odd.*
|
||||
*Don't write code like that. It would be odd.*
|
||||
|
||||
### Integers
|
||||
### Integers (int)
|
||||
|
||||
Signed values of arbitrary size and base:
|
||||
|
||||
@@ -62,26 +60,6 @@ x ^ y Bit-wise XOR
|
||||
abs(x) Absolute value
|
||||
```
|
||||
|
||||
### Comparisons
|
||||
|
||||
The following comparison / relational operators work with numbers:
|
||||
|
||||
`<`, `>`, `<=` `>=`, `==`, `!=`
|
||||
|
||||
You can form more complex boolean expressions using
|
||||
|
||||
`and`, `or`, `not`
|
||||
|
||||
Here are a few examples:
|
||||
|
||||
```python
|
||||
if b >= a and b <= c:
|
||||
print('b is between a and c')
|
||||
|
||||
if not (b < a or b > c):
|
||||
print('b is still between a and c')
|
||||
```
|
||||
|
||||
### Floating point (float)
|
||||
|
||||
Use a decimal or exponential notation to specify a floating point value:
|
||||
@@ -136,6 +114,34 @@ d = math.tan(x)
|
||||
e = math.log(x)
|
||||
```
|
||||
|
||||
|
||||
### Comparisons
|
||||
|
||||
The following comparison / relational operators work with numbers:
|
||||
|
||||
```
|
||||
x < y Less than
|
||||
x <= y Less than or equal
|
||||
x > y Greater than
|
||||
x >= y Greater than or equal
|
||||
x == y Equal to
|
||||
x != y Not equal to
|
||||
```
|
||||
|
||||
You can form more complex boolean expressions using
|
||||
|
||||
`and`, `or`, `not`
|
||||
|
||||
Here are a few examples:
|
||||
|
||||
```python
|
||||
if b >= a and b <= c:
|
||||
print('b is between a and c')
|
||||
|
||||
if not (b < a or b > c):
|
||||
print('b is still between a and c')
|
||||
```
|
||||
|
||||
### Converting Numbers
|
||||
|
||||
The type name can be used to convert values:
|
||||
@@ -159,7 +165,7 @@ Try it out.
|
||||
|
||||
## Exercises
|
||||
|
||||
### (a) Dave's mortgage
|
||||
### Exercise 1.7: Dave's mortgage
|
||||
|
||||
Dave has decided to take out a 30-year fixed rate mortgage of $500,000 with Guido’s Mortgage, Stock Investment, and Bitcoin trading corporation.
|
||||
The interest rate is 5% and the monthly payment is $2684.11.
|
||||
@@ -183,7 +189,7 @@ print('Total paid', total_paid)
|
||||
|
||||
Enter this program and run it. You should get an answer of `966,279.6`.
|
||||
|
||||
### (b) Extra payments
|
||||
### Exercise 1.8: Extra payments
|
||||
|
||||
Suppose Dave pays an extra $1000/month for the first 12 months of the mortgage?
|
||||
|
||||
@@ -191,7 +197,7 @@ Modify the program to incorporate this extra payment and have it print the total
|
||||
|
||||
When you run the new program, it should report a total payment of `929,965.62` over 342 months.
|
||||
|
||||
### (c) Making an Extra Payment Calculator
|
||||
### Exercise 1.9: Making an Extra Payment Calculator
|
||||
|
||||
Modify the program so that extra payment information can be more generally handled.
|
||||
Make it so that the user can set these variables:
|
||||
@@ -206,7 +212,7 @@ Make the program look at these variables and calculate the total paid appropriat
|
||||
|
||||
How much will Dave pay if he pays an extra $1000/month for 4 years starting in year 5 of the mortgage?
|
||||
|
||||
### (d) Making a table
|
||||
### Exercise 1.10: Making a table
|
||||
|
||||
Modify the program to print out a table showing the month, total paid so far, and the remaining principal.
|
||||
The output should look something like this:
|
||||
@@ -224,8 +230,28 @@ Total paid 878389.99
|
||||
Months 309
|
||||
```
|
||||
|
||||
### (e) Bonus
|
||||
### Exercise 1.11: Bonus
|
||||
|
||||
While you’re at it, fix the program to correct the for overpayment that occurs in the last month.
|
||||
|
||||
### Exercise 1.12: A Mystery
|
||||
|
||||
`int()` and `float()` can be used to convert numbers. For example,
|
||||
|
||||
```pycon
|
||||
>>> int("123")
|
||||
123
|
||||
>>> float("1.23")
|
||||
1.23
|
||||
>>>
|
||||
```
|
||||
|
||||
With that in mind, can you explain this behavior?
|
||||
|
||||
```pycon
|
||||
>>> bool("False")
|
||||
True
|
||||
>>>
|
||||
```
|
||||
|
||||
[Contents](../Contents) \| [Previous (1.2 A First Program)](02_Hello_world) \| [Next (1.4 Strings)](04_Strings)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# 1.4 Strings
|
||||
|
||||
This section covers the basics of text manipulation.
|
||||
|
||||
### Representing Text
|
||||
|
||||
String are text literals written in programs with quotes.
|
||||
@@ -40,9 +38,8 @@ at the keyboard. Here are some common escape codes:
|
||||
|
||||
### String Representation
|
||||
|
||||
Each character represents a raw unicode code point.
|
||||
|
||||
<!-- TODO: Add Picture of following characters -->
|
||||
The characters in a string are Unicode and represent a so-called "code-point". You can
|
||||
specify an exact code-point using the following escape sequences:
|
||||
|
||||
```python
|
||||
a = '\xf1' # a = 'ñ'
|
||||
@@ -51,7 +48,12 @@ c = '\U0001D122' # c = '𝄢'
|
||||
d = '\N{FORALL}' # d = '∀'
|
||||
```
|
||||
|
||||
Strings work like an array for accessing its characters. You use an integer index, starting at 0.
|
||||
The [Unicode Character Database](https://unicode.org/charts) is a reference for all
|
||||
available character codes.
|
||||
|
||||
### String Indexing
|
||||
|
||||
Strings work like an array for accessing individual characters. You use an integer index, starting at 0.
|
||||
|
||||
```python
|
||||
a = 'Hello world'
|
||||
@@ -85,7 +87,7 @@ len(s) # 5
|
||||
# Membership test (`in`, `not in`)
|
||||
t = 'e' in s # True
|
||||
f = 'x' in s # False
|
||||
tt = 'hi' not in s # True
|
||||
g = 'hi' not in s # True
|
||||
|
||||
# Replication (s * n)
|
||||
rep = s * 5 # 'HelloHelloHelloHelloHello'
|
||||
@@ -95,14 +97,14 @@ rep = s * 5 # 'HelloHelloHelloHelloHello'
|
||||
|
||||
Strings have methods that perform various operations with the string data.
|
||||
|
||||
Stripping any leading / trailing white space.
|
||||
Example: stripping any leading / trailing white space.
|
||||
|
||||
```python
|
||||
s = ' Hello '
|
||||
t = s.strip() # 'Hello'
|
||||
```
|
||||
|
||||
Case conversion.
|
||||
Example: Case conversion.
|
||||
|
||||
```python
|
||||
s = 'Hello'
|
||||
@@ -110,7 +112,7 @@ l = s.lower() # 'hello'
|
||||
u = s.upper() # 'HELLO'
|
||||
```
|
||||
|
||||
Replacing text.
|
||||
Example: Replacing text.
|
||||
|
||||
```python
|
||||
s = 'Hello world'
|
||||
@@ -119,7 +121,8 @@ t = s.replace('Hello' , 'Hallo') # 'Hallo world'
|
||||
|
||||
**More string methods:**
|
||||
|
||||
Strings have a wide variety of other methods for testing and manipulating the text data:
|
||||
Strings have a wide variety of other methods for testing and manipulating the text data.
|
||||
This is small sample of methods:
|
||||
|
||||
```python
|
||||
s.endswith(suffix) # Check if string ends with suffix
|
||||
@@ -158,7 +161,7 @@ TypeError: 'str' object does not support item assignment
|
||||
|
||||
### String Conversions
|
||||
|
||||
Use `str()` to convert a value to a string.
|
||||
Use `str()` to convert any value to a string suitable for printing.
|
||||
|
||||
```python
|
||||
>>> x = 42
|
||||
@@ -169,13 +172,13 @@ Use `str()` to convert a value to a string.
|
||||
|
||||
### Byte Strings
|
||||
|
||||
A string of 8-bit bytes.
|
||||
A string of 8-bit bytes, commonly encountered with low-level I/O.
|
||||
|
||||
```python
|
||||
data = b'Hello World\r\n'
|
||||
```
|
||||
|
||||
By putting a little b before our string literal we specify that it is a byte string as opposed to a text string.
|
||||
By putting a little b before the first quotation, you specify that it is a byte string as opposed to a text string.
|
||||
|
||||
Most of the usual string operations work.
|
||||
|
||||
@@ -185,13 +188,13 @@ data[0:5] # b'Hello'
|
||||
data.replace(b'Hello', b'Cruel') # b'Cruel World\r\n'
|
||||
```
|
||||
|
||||
Indexing is a bit different because it returns byte values.
|
||||
Indexing is a bit different because it returns byte values as integers.
|
||||
|
||||
```python
|
||||
data[0] # 72 (ASCII code for 'H')
|
||||
```
|
||||
|
||||
Conversion to/from text.
|
||||
Conversion to/from text strings.
|
||||
|
||||
```python
|
||||
text = data.decode('utf-8') # bytes -> text
|
||||
@@ -200,7 +203,7 @@ data = text.encode('utf-8') # text -> bytes
|
||||
|
||||
### Raw Strings
|
||||
|
||||
Raw strings are strings with uninterpreted backslash. They are little by prefixing the initial quote with a lowercase "r".
|
||||
Raw strings are string literals with an uninterpreted backslash. They specified by prefixing the initial quote with a lowercase "r".
|
||||
|
||||
```python
|
||||
>>> rs = r'c:\newdata\test' # Raw (uninterpreted backslash)
|
||||
@@ -208,8 +211,9 @@ Raw strings are strings with uninterpreted backslash. They are little by prefix
|
||||
'c:\\newdata\\test'
|
||||
```
|
||||
|
||||
The string is the literal text, exactly as typed.
|
||||
This is useful in situations where the backslash has special significance. Example: filename, regular expressions, etc.
|
||||
The string is the literal text enclosed inside, exactly as typed.
|
||||
This is useful in situations where the backslash has special
|
||||
significance. Example: filename, regular expressions, etc.
|
||||
|
||||
### f-Strings
|
||||
|
||||
@@ -228,13 +232,13 @@ A string with formatted expression substitution.
|
||||
>>>
|
||||
```
|
||||
|
||||
**Note: This requires Python 3.6 or newer.**
|
||||
**Note: This requires Python 3.6 or newer.** The meaning of the format codes
|
||||
is covered later.
|
||||
|
||||
## Exercises
|
||||
|
||||
|
||||
In this exercise, we experiment with operations on Python's string type.
|
||||
You may want to do most of this exercise at the Python interactive prompt where you can easily see the results.
|
||||
In these exercises, you experiment with operations on Python's string type.
|
||||
You should do this at the Python interactive prompt where you can easily see the results.
|
||||
Important note:
|
||||
|
||||
> In exercises where you are supposed to interact with the interpreter,
|
||||
@@ -251,7 +255,7 @@ Start by defining a string containing a series of stock ticker symbols like this
|
||||
>>>
|
||||
```
|
||||
|
||||
### (a): Extracting individual characters and substrings
|
||||
### Exercise 1.13: Extracting individual characters and substrings
|
||||
|
||||
Strings are arrays of characters. Try extracting a few characters:
|
||||
|
||||
@@ -269,7 +273,7 @@ Strings are arrays of characters. Try extracting a few characters:
|
||||
>>>
|
||||
```
|
||||
|
||||
### (b) Strings as read-only objects
|
||||
### Exercise 1.14: Strings as read-only objects
|
||||
|
||||
In Python, strings are read-only.
|
||||
|
||||
@@ -283,7 +287,7 @@ TypeError: 'str' object does not support item assignment
|
||||
>>>
|
||||
```
|
||||
|
||||
### (c) String concatenation
|
||||
### Exercise 1.15: String concatenation
|
||||
|
||||
Although string data is read-only, you can always reassign a variable
|
||||
to a newly created string.
|
||||
@@ -298,7 +302,7 @@ the end of `symbols`:
|
||||
>>>
|
||||
```
|
||||
|
||||
Oops! That's not what we wanted. Fix it so that the `symbols` variable holds the value `'HPQ,AAPL,IBM,MSFT,YHOO,SCO,GOOG'`.
|
||||
Oops! That's not what you wanted. Fix it so that the `symbols` variable holds the value `'HPQ,AAPL,IBM,MSFT,YHOO,SCO,GOOG'`.
|
||||
|
||||
In these examples, it might look like the original string is being
|
||||
modified, in an apparent violation of strings being read only. Not
|
||||
@@ -307,15 +311,16 @@ time. When the variable name `symbols` is reassigned, it points to the
|
||||
newly created string. Afterwards, the old string is destroyed since
|
||||
it's not being used anymore.
|
||||
|
||||
### (d) Membership testing (substring testing)
|
||||
### Exercise 1.16: Membership testing (substring testing)
|
||||
|
||||
Experiment with the `in` operator to check for substrings. At the interactive prompt, try these operations:
|
||||
Experiment with the `in` operator to check for substrings. At the
|
||||
interactive prompt, try these operations:
|
||||
|
||||
```pycon
|
||||
>>> 'IBM' in symbols
|
||||
?
|
||||
>>> 'AA' in symbols
|
||||
?
|
||||
True
|
||||
>>> 'CAT' in symbols
|
||||
?
|
||||
>>>
|
||||
@@ -323,7 +328,7 @@ Experiment with the `in` operator to check for substrings. At the interactive p
|
||||
|
||||
*Why did the check for "AA" return `True`?*
|
||||
|
||||
### (e) String Methods
|
||||
### Exercise 1.17: String Methods
|
||||
|
||||
At the Python interactive prompt, try experimenting with some of the string methods.
|
||||
|
||||
@@ -359,7 +364,7 @@ Try some more operations:
|
||||
>>>
|
||||
```
|
||||
|
||||
### (f) f-strings
|
||||
### Exercise 1.18: f-strings
|
||||
|
||||
Sometimes you want to create a string and embed the values of
|
||||
variables into it.
|
||||
@@ -375,13 +380,15 @@ To do that, use an f-string. For example:
|
||||
>>>
|
||||
```
|
||||
|
||||
Modify the `mortgage.py` program from Exercise 1.3 to create its output using f-strings.
|
||||
Modify the `mortgage.py` program from [Exercise 1.10](03_Numbers) to create its output using f-strings.
|
||||
Try to make it so that output is nicely aligned.
|
||||
|
||||
### Commentary
|
||||
|
||||
As you start to experiment with the interpreter, you often want to know more about the operations supported by different objects.
|
||||
For example, how do you find out what operations are available on a string?
|
||||
As you start to experiment with the interpreter, you often want to
|
||||
know more about the operations supported by different objects. For
|
||||
example, how do you find out what operations are available on a
|
||||
string?
|
||||
|
||||
Depending on your Python environment, you might be able to see a list
|
||||
of available methods via tab-completion. For example, try typing
|
||||
@@ -399,7 +406,12 @@ builtin-in `dir()` function. For example:
|
||||
```python
|
||||
>>> s = 'hello'
|
||||
>>> dir(s)
|
||||
['__add__', '__class__', '__contains__', ..., 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
|
||||
['__add__', '__class__', '__contains__', ..., 'find', 'format',
|
||||
'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
|
||||
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
|
||||
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
|
||||
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
|
||||
'title', 'translate', 'upper', 'zfill']
|
||||
>>>
|
||||
```
|
||||
|
||||
@@ -417,9 +429,4 @@ upper(...)
|
||||
>>>
|
||||
```
|
||||
|
||||
IDEs and alternative interactive shells often give you more help here.
|
||||
For example, a popular alternative to Python's normal interactive mode
|
||||
is IPython (http://ipython.org). IPython provides some nice features
|
||||
such as tab-completion of method names, more integrated help and more.
|
||||
|
||||
[Contents](../Contents) \| [Previous (1.3 Numbers)](03_Numbers) \| [Next (1.5 Lists)](05_Lists)
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
# 1.5 Lists
|
||||
|
||||
This section introduces lists, one of Python's basic objects for storing collections of data.
|
||||
|
||||
### Creating a List
|
||||
|
||||
Use square brackets to create a list:
|
||||
Use square brackets to define a list:
|
||||
|
||||
```python
|
||||
names = [ 'Elwood', 'Jake', 'Curtis' ]
|
||||
@@ -55,7 +53,7 @@ Negative indices count from the end.
|
||||
names[-1] # 'Curtis'
|
||||
```
|
||||
|
||||
You can change on element in the list.
|
||||
You can change any item in the list.
|
||||
|
||||
```python
|
||||
names[1] = 'Joliet Jake'
|
||||
@@ -96,20 +94,20 @@ for name in names:
|
||||
|
||||
This is similar to a `foreach` statement from other programming languages.
|
||||
|
||||
To find something quickly, use `index()`.
|
||||
To find the position of something quickly, use `index()`.
|
||||
|
||||
```python
|
||||
names = ['Elwood','Jake','Curtis']
|
||||
names.index('Curtis') # 2
|
||||
```
|
||||
|
||||
If the element is present more than one, it will return the index of the first occurrence.
|
||||
If the element is present more than once, `index()` will return the index of the first occurrence.
|
||||
|
||||
If the element is not found, it will raise a `ValueError` exception.
|
||||
|
||||
### List Removal
|
||||
|
||||
You can remove either with the element value or the index number.
|
||||
You can remove items either by element value or by index:
|
||||
|
||||
```python
|
||||
# Using the value
|
||||
@@ -119,12 +117,12 @@ names.remove('Curtis')
|
||||
del names[1]
|
||||
```
|
||||
|
||||
Removing results in items moving down to fill the space vacated. There are no holes in the list.
|
||||
Removing an item does not create a hole. Other items will move down to fill the space vacated.
|
||||
If there are more than one occurrence of the element, `.remove()` will remove only the first occurrence.
|
||||
|
||||
### List Sorting
|
||||
|
||||
Lists can be sorted 'in-place'.
|
||||
Lists can be sorted "in-place".
|
||||
|
||||
```python
|
||||
s = [10, 1, 7, 3]
|
||||
@@ -152,11 +150,12 @@ s.sort() # ['bar', 'foo', 'spam']
|
||||
```
|
||||
|
||||
Specifically, lists don't represent vectors/matrices as in MATLAB, Octave, IDL, etc.
|
||||
However, there are some packages to help you with that (e.g. numpy).
|
||||
However, there are some packages to help you with that (e.g. [numpy](https://numpy.org)).
|
||||
|
||||
## Exercises
|
||||
|
||||
In this exercise, we experiment with Python's list datatype. In the last exercise, you worked with strings containing stock symbols.
|
||||
In this exercise, we experiment with Python's list datatype. In the last section,
|
||||
you worked with strings containing stock symbols.
|
||||
|
||||
```pycon
|
||||
>>> symbols = 'HPQ,AAPL,IBM,MSFT,YHOO,DOA,GOOG'
|
||||
@@ -168,7 +167,7 @@ Split it into a list of names using the `split()` operation of strings:
|
||||
>>> symlist = symbols.split(',')
|
||||
```
|
||||
|
||||
### (a) Extracting and reassigning list elements
|
||||
### Exercise 1.19: Extracting and reassigning list elements
|
||||
|
||||
Try a few lookups:
|
||||
|
||||
@@ -224,7 +223,7 @@ You can reassign a portion of a list to another list. For example:
|
||||
When you do this, the list on the left-hand-side (`symlist`) will be resized as appropriate to make the right-hand-side (`mysyms`) fit.
|
||||
For instance, in the above example, the last two items of `symlist` got replaced by the single item in the list `mysyms`.
|
||||
|
||||
### (b) Looping over list items
|
||||
### Exercise 1.20: Looping over list items
|
||||
|
||||
The `for` loop works by looping over data in a sequence such as a list.
|
||||
Check this out by typing the following loop and watching what happens:
|
||||
@@ -235,7 +234,7 @@ Check this out by typing the following loop and watching what happens:
|
||||
# Look at the output
|
||||
```
|
||||
|
||||
### (c) Membership tests
|
||||
### Exercise 1.21: Membership tests
|
||||
|
||||
Use the `in` or `not in` operator to check if `'AIG'`,`'AA'`, and `'CAT'` are in the list of symbols.
|
||||
|
||||
@@ -249,7 +248,7 @@ True
|
||||
>>>
|
||||
```
|
||||
|
||||
### (d) Appending, inserting, and deleting items
|
||||
### Exercise 1.22: Appending, inserting, and deleting items
|
||||
|
||||
Use the `append()` method to add the symbol `'RHT'` to end of `symlist`.
|
||||
|
||||
@@ -319,7 +318,7 @@ Remove the first occurrence of `'YHOO'`.
|
||||
Just so you know, there is no method to find or remove all occurrences of an item.
|
||||
However, we'll see an elegant way to do this in section 2.
|
||||
|
||||
### (e) Sorting
|
||||
### Exercise 1.23: Sorting
|
||||
|
||||
Want to sort a list? Use the `sort()` method. Try it out:
|
||||
|
||||
@@ -341,7 +340,7 @@ Want to sort in reverse? Try this:
|
||||
|
||||
Note: Sorting a list modifies its contents 'in-place'. That is, the elements of the list are shuffled around, but no new list is created as a result.
|
||||
|
||||
### (f) Putting it all back together
|
||||
### Exercise 1.24: Putting it all back together
|
||||
|
||||
Want to take a list of strings and join them together into one string?
|
||||
Use the `join()` method of strings like this (note: this looks funny at first).
|
||||
@@ -359,7 +358,7 @@ Use the `join()` method of strings like this (note: this looks funny at first).
|
||||
>>>
|
||||
```
|
||||
|
||||
### (g) Lists of anything
|
||||
### Exercise 1.25: Lists of anything
|
||||
|
||||
Lists can contain any kind of object, including other lists (e.g., nested lists).
|
||||
Try this out:
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# 1.6 File Management
|
||||
|
||||
This section discusses the basics of working with files.
|
||||
|
||||
### File Input and Output
|
||||
|
||||
Open a file.
|
||||
@@ -84,9 +82,10 @@ with open('outfile', 'wt') as f:
|
||||
This exercise depends on a file `Data/portfolio.csv`. The file contains a list of lines with information on a portfolio of stocks.
|
||||
Locate the file and look at its contents:
|
||||
|
||||
### (a) File Preliminaries
|
||||
### Exercise 1.26: File Preliminaries
|
||||
|
||||
*Note: Make sure you are running Python in a location where you can access the `portfolio.csv` file.
|
||||
It's normally located in `Data/portfolio.csv`.
|
||||
You can find out where Python thinks it's running by doing this:
|
||||
|
||||
```pycon
|
||||
@@ -115,9 +114,11 @@ name,shares,price
|
||||
>>>
|
||||
```
|
||||
|
||||
In the above example, it should be noted that Python has two modes of output.
|
||||
In the first mode where you type `data` at the prompt, Python shows you the raw string representation including quotes and escape codes.
|
||||
When you type `print(data)`, you get the actual formatted output of the string.
|
||||
In the above example, it should be noted that Python has two modes of
|
||||
output. In the first mode where you type `data` at the prompt, Python
|
||||
shows you the raw string representation including quotes and escape
|
||||
codes. When you type `print(data)`, you get the actual formatted
|
||||
output of the string.
|
||||
|
||||
Although reading a file all at once is simple, it is often not the
|
||||
most appropriate way to do it—especially if the file happens to be
|
||||
@@ -137,9 +138,12 @@ name,shares,price
|
||||
>>>
|
||||
```
|
||||
|
||||
When you use this code as shown, lines are read until the end of the file is reached at which point the loop stops.
|
||||
When you use this code as shown, lines are read until the end of the
|
||||
file is reached at which point the loop stops.
|
||||
|
||||
On certain occasions, you might want to manually read or skip a *single* line of text (e.g., perhaps you want to skip the first line of column headers).
|
||||
On certain occasions, you might want to manually read or skip a
|
||||
*single* line of text (e.g., perhaps you want to skip the first line
|
||||
of column headers).
|
||||
|
||||
```pycon
|
||||
>>> f = open('Data/portfolio.csv', 'rt')
|
||||
@@ -180,7 +184,7 @@ For example, try this:
|
||||
|
||||
*Note: In these examples, `f.close()` is being called explicitly because the `with` statement isn’t being used.*
|
||||
|
||||
### (b) Reading a data file
|
||||
### Exercise 1.27: Reading a data file
|
||||
|
||||
Now that you know how to read a file, let’s write a program to perform a simple calculation.
|
||||
|
||||
@@ -197,10 +201,12 @@ Your program should print output such as the following:
|
||||
Total cost 44671.15
|
||||
```
|
||||
|
||||
### (c) Other kinds of 'files'
|
||||
### Exercise 1.28: Other kinds of 'files'
|
||||
|
||||
What if you wanted to read a non-text file such as a gzip-compressed datafile?
|
||||
The builtin `open()` function won’t help you here, but Python has a library module `gzip` that can read gzip compressed files.
|
||||
What if you wanted to read a non-text file such as a gzip-compressed
|
||||
datafile? The builtin `open()` function won’t help you here, but
|
||||
Python has a library module `gzip` that can read gzip compressed
|
||||
files.
|
||||
|
||||
Try it:
|
||||
|
||||
|
||||
@@ -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