Based on Zed Shaw's "Learn Python the Hard Way," this is a review of Exercises 13 - 19 in that text. For non-computer-science students and learners. This PPT will not make sense without Zed's lessons. The PPT is intended to supplement and help explain these seven lessons. The PPT was updated on Jan. 17, 2014.
Learn Python Functions and File Handling with Exercises 13-19
1. Learn Python the Hard Way
Exercises 13 – 19
http://learnpythonthehardway.org/
2. from sys import argv
• You’ll see this kind of thing a lot in Python
scripts:
from ----- import ----• The first thing (sys) is a module that already
exists in Python. It contains many things.
• The second thing (argv) is a variable that is
defined in sys. By importing it, you can do
stuff that would not work otherwise.
3. Python is flexible …
• Once you have argv in your program (because
you started with from sys import argv), you
can use it like this:
script, x, y, z = argv
• It’s entirely up to you how many things you
put in that line before = argv
4. … but Python is fussy too
• If your program has four things in the line
before = argv
script, x, y, z = argv
• … then you absolutely must invoke your
program with three arguments, like this:
~$ python ex13.py Tom Dick Harry
5.
6. from sys import argv
• Zed’s “Study Drills” are really key for learning
how this works
• Think of why a program might need this
instead of raw_input()
• Note: The “arguments” for argv are loaded
into your program before the program is
running
8. > type something here
With Zed’s Exercise 14, again, his “Study Drills”
are really important.
If you’re skipping them, you’re probably not
getting it.
You’re going to start feeling very lost …
9. Exercise 15
Opening files
f = open("myfileonmycomputer.txt")
f is a variable name (it could be x, or file, or txt)
myfileonmycomputer.txt
is the name of a normal file on your computer
open() is a built-in function in Python.
Note: This only stores the file as a value (it does NOT
show you the contents of the file).
10. Exercise 15
Opening files (2)
f = open(filename)
In Ex. 15, Zed has that (above).
Where does filename come from?
Go back to the second line of his code:
script, filename = argv
filename came from the argument you typed
when you invoked your program:
~$ python ex15.py ex15_sample.txt
11. Exercise 15
Reading files
print f.read()
What does this do?
Make sure you understand this.
read() is a method in Python. It reads what
you tell it to read, and then returns a string that
contains what it read.
12. You can play with this stuff
on the command line
13. Why this is cool
You can send Python out to the Web and ask it
to read files out there.
Then you can search the contents of those files
and do stuff with the contents.
Python is powerful.
Code is powerful!
14. Exercise 16
Messing with the contents of files
f = open(filename, 'w')
What does the ‘w’ do? Did you look it up?
f.truncate()
What does this do? (Make sure you know!)
f.write(something)
What does this do?
17. Top: The original file, test.txt. Bottom: The same file, after truncating and writing.
18. What will Python allow?
What happens if you enter:
f.write(a, b, c)
Note: You should try this kind of thing.
Write a comment in your code about what you
find out after you try it.
19. Modes for open()
f = open(filename, 'w')
Modes 'r+', 'w+' and 'a+' open the file for
updating (note that 'w+' truncates the file).
'r+' read
'w+' write and erase all contents
'a+' append
If the mode is omitted, it defaults to 'r'.
http://docs.python.org/2/library/functions.html#open
20. Exercise 17
Checking if a file exists
from sys import argv
from os.path import exists
Review Exercise 13
• The first thing (os.path) is a module that is part of
Python. It contains many things.
• The second thing (exists) is a function that is
defined in os.path. You must import it if you
intend to use it.
21. Exercise 17
Using exists
print "Does the output file exist?
%r" % exists(to_file)
If that confuses you, try just this:
print exists(to_file)
Then run the program again, and give it a
filename that does not exist on your computer.
23. Exercise 17
Copying file contents
• I think Zed’s filenames are confusing in Ex. 17.
• If you change the variable names for the two
files to: oldfile and newfile, or to original and
destination, maybe it will help you.
script, oldfile, newfile = argv
24. Exercise 17
Copying, Step 1
f = open(oldfile)
indata = f.read()
is the same as
indata = open(oldfile).read()
(Python allows us to chain instructions together
in one line)
25. Exercise 17
Copying, Step 2
t = open(newfile, 'w')
t.write(indata)
Confusing, yes?
The real file represented by newfile will now be
represented by the variable name t.
The value of indata is put into t.
Whatever was in oldfile is now in newfile.
29. Yes, Exercise 17 is hard.
Even Zed says so! *
* In his “Common Student Questions” section
30. Exercise 18
Functions!
• Functions are as essential to programming as
variables
• Most programming languages use functions
• Basically, a function has a name and a list of
instructions
• When you call the function, those instructions
will run (they will be executed)
31.
32. Exercise 18
More about functions!
• Important: A function does not do anything,
ever, until it is called
• If you define a function, but you never call it,
it will never run
• Most programs contain several (or many)
different functions
33. Exercise 18
Accurate typing
• Here’s where your journalism editing skill
gives you an edge!
• Follow the style carefully …
def functionname(argument,
argument):
(don’t forget the colon!)
• Indents: In Python, the indents are superimportant! The convention is to use 4 spaces
—and NOT a tab.
34. Exercise 19
Variables inside and outside
• Python doesn’t throw an error if you use the
exact same variable name inside a function
AND outside a function
• This can be misleading
• Those would actually be two different
variables
• If you change the value of a variable inside a
function, the value of the other variable
(outside) will not change!
35.
36. Exercise 19
Variables inside and outside
Therefore, it is very smart to be careful about
the names you give to your variables.
Don’t mix and match.
Use different variable names inside the
functions.
37. Start with the code you see below.
Then, below it, write a function that takes mpg,
price_of_gas, and distance as arguments.
The function will calculate the cost of gas for the trip.
39. Learn Python the Hard Way
Exercises 13 – 19
(now we know something)
Notas del editor
SOURCE http://learnpythonthehardway.org/book/
All of this is just part of Python. Go with it. Relax.
You can pass in any number of arguments. For example: script, a, b, c, d, e, f, g = argv
BUT the number of arguments indicated in the program MUST BE matched by what you type when you invoke (run) the program.
CODE EXAMPLE. LPTHW Exercise 13 – this is a variation on Zed’s exercise.
Play with this code until you really understand it.
See http://en.wikipedia.org/wiki/Adventure_game | Download Mac OS version (seen here) - http://lobotomo.com/products/Adventure/index.html
LPTHW Exercise 15 – the first time we work with external files.
LPTHW Exercise 15 requires you to understand Exercises 13 and 14. If you’re still unclear about argv – you’ll have to go back. SLIDE 2 in this PPT explains.
f = open(something) does ONE thing. print f.read() does something else. For a list of all built-in functions, see http://docs.python.org/2/library/functions.html
CODE EXAMPLE. Exercise 15.
LPTHW Exercise 16 – open, truncate, write.
CODE EXAMPLE. Exercise 16. Truncate.
CODE EXAMPLE. Exercise 16. Write.
Top: The original file, test.txt. Bottom: The same file, after truncating and writing.