Date post: | 06-May-2015 |
Category: |
Education |
Upload: | mindy-mcadams |
View: | 3,282 times |
Download: | 3 times |
Learn Python the Hard Way
Exercises 13 – 19
http://learnpythonthehardway.org/
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.
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
… 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
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
“Adventure”: An early computer game
> 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 …
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).
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 = argvfilename came from the argument you typed when you invoked your program:~$ python ex15.py ex15_sample.txt
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.
Exercise 15
You can play with this stuff on the command line
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!
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?
Exercise 16
Truncate a filePlay on the command line!
Write to a filePlay on the command line!
Top: The original file, test.txt. Bottom: The same file, after truncating and writing.
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.
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
Checking if a file exists
from sys import argvfrom 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.
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.
Exercise 17
You can even play with thison the command line
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
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)
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.
Exercise 17
This code accomplishes the same thing as Zed’s Ex. 17.
This is a good one to play withon the command line
len()Exercise 17
Compare the real file size with the result from len()
Yes, Exercise 17 is hard.Even Zed says so! *
* In his “Common Student Questions” section
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)
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
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 super- important! The convention is to use 4 spaces —and NOT a tab.
Exercise 18
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!
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.
Exercise 19
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.
You’ll learn much more about functions
in the upcoming exercises!
Learn Python the Hard Way
Exercises 13 – 19
(now we know something)