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...
Python is flexible …
• Once you have argv in your program (because
you started with from sys import argv), you
can use it ...
… but Python is fussy too
• If your program has four things in the line
before = argv
script, x, y, z = argv
• … then you ...
from sys import argv
• Zed’s “Study Drills” are really key for learning
how this works
• Think of why a program might need...
“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...
Exercise 15

Opening files
f = open("myfileonmycomputer.txt")
f is a variable name (it could be x, or file, or txt)
myfile...
Exercise 15

Opening files (2)
f = open(filename)
In Ex. 15, Zed has that (above).
Where does filename come from?
Go back ...
Exercise 15

Reading files
print f.read()
What does this do?
Make sure you understand this.
read() is a method in Python. ...
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 o...
Exercise 16

Messing with the contents of files
f = open(filename, 'w')
What does the ‘w’ do? Did you look it up?
f.trunca...
Truncate a file
Play on the command line!
Write to a file
Play 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 comme...
Modes for open()
f = open(filename, 'w')
Modes 'r+', 'w+' and 'a+' open the file for
updating (note that 'w+' truncates th...
Exercise 17

Checking if a file exists
from sys import argv
from os.path import exists
Review Exercise 13
• The first thin...
Exercise 17

Using exists
print "Does the output file exist?
%r" % exists(to_file)
If that confuses you, try just this:
pr...
You can even play with this
on the command line
Exercise 17

Copying file contents
• I think Zed’s filenames are confusing in Ex. 17.
• If you change the variable names f...
Exercise 17

Copying, Step 1
f = open(oldfile)
indata = f.read()
is the same as
indata = open(oldfile).read()
(Python allo...
Exercise 17

Copying, Step 2
t = open(newfile, 'w')
t.write(indata)
Confusing, yes?
The real file represented by newfile w...
This code accomplishes the same thing as Zed’s Ex. 17.
Exercise 17

len()

This is a good one to play with
on the command line
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
Exercise 18

Functions!
• Functions are as essential to programming as
variables
• Most programming languages use function...
Exercise 18

More about functions!
• Important: A function does not do anything,
ever, until it is called
• If you define ...
Exercise 18

Accurate typing
• Here’s where your journalism editing skill
gives you an edge!
• Follow the style carefully ...
Exercise 19

Variables inside and outside
• Python doesn’t throw an error if you use the
exact same variable name inside a...
Exercise 19

Variables inside and outside
Therefore, it is very smart to be careful about
the names you give to your varia...
Start with the code you see below.
Then, below it, write a function that takes mpg,
price_of_gas, and distance as argument...
You’ll learn much more
about functions
in the upcoming exercises!
Learn Python the Hard Way
Exercises 13 – 19
(now we know something)
Learning Python - Week 2
Learning Python - Week 2
Learning Python - Week 2
Upcoming SlideShare
Loading in...5
×

Learning Python - Week 2

3,578

Published on

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.

Published in: Education, Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,578
On Slideshare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
55
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • 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.
  • You’ll get an error … Figure out why!
  • SOURCE http://docs.python.org/2/library/functions.html#open
  • LPTHW Exercise 17 – first, the import statements …
  • LPTHW Exercise 17 – how “exists” works
  • CODE EXAMPLE - LPTHW Exercise 17
  • LPTHW Exercise 17 – second, understanding the variable names …
  • LPTHW Exercise 17 – third, copy the contents of oldfile into a new variable named indata …
  • LPTHW Exercise 17 – fourth, copy the value of the variable named indata … into newfile.
  • LPTHW Exercise 17 – a variation with the same result: contents of one file are totally copied into a different file.
  • CODE EXAMPLE - LPTHW Exercise 17 – len() – How big is it? (or, how long? Measured in characters, or bytes)
  • CODE EXAMPLE - LPTHW Exercise 17 – len() // Open the little Info window in Mac OS with Command-I (I for Info).
  • LPTHW Exercise 17
  • CODE EXAMPLE. LPTHW Exercise 18 – try to figure this out.
  • CODE EXAMPLE. LPTHW Exercise 19 – try to figure this out.
  • LPTHW Exercise 19 – a problem for you to solve
  • Mindy McAdams - CONTACT – http://mindymcadams.com/
  • Learning Python - Week 2

    1. 1. Learn Python the Hard Way Exercises 13 – 19 http://learnpythonthehardway.org/
    2. 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. 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. 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. 5. 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
    6. 6. “Adventure”: An early computer game
    7. 7. > 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 …
    8. 8. 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).
    9. 9. 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
    10. 10. 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.
    11. 11. You can play with this stuff on the command line
    12. 12. 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!
    13. 13. 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?
    14. 14. Truncate a file Play on the command line!
    15. 15. Write to a file Play on the command line!
    16. 16. Top: The original file, test.txt. Bottom: The same file, after truncating and writing.
    17. 17. 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.
    18. 18. 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
    19. 19. 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.
    20. 20. 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.
    21. 21. You can even play with this on the command line
    22. 22. 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
    23. 23. 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)
    24. 24. 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.
    25. 25. This code accomplishes the same thing as Zed’s Ex. 17.
    26. 26. Exercise 17 len() This is a good one to play with on the command line
    27. 27. Compare the real file size with the result from len()
    28. 28. Yes, Exercise 17 is hard. Even Zed says so! * * In his “Common Student Questions” section
    29. 29. 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)
    30. 30. 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
    31. 31. 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.
    32. 32. 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!
    33. 33. 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.
    34. 34. 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.
    35. 35. You’ll learn much more about functions in the upcoming exercises!
    36. 36. Learn Python the Hard Way Exercises 13 – 19 (now we know something)
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×