• Complain

Zed A. Shaw - Learn Python The Hard Way

Here you can read online Zed A. Shaw - Learn Python The Hard Way full text of the book (entire story) in english for free. Download pdf and epub, get meaning, cover and reviews about this ebook. year: 2011, genre: Computer. Description of the work, (preface) as well as reviews are available. Best literature library LitArk.com created for fans of good reading and offers a wide selection of genres:

Romance novel Science fiction Adventure Detective Science History Home and family Prose Art Politics Computer Non-fiction Religion Business Children Humor

Choose a favorite category and find really read worthwhile books. Enjoy immersion in the world of imagination, feel the emotions of the characters or learn something new for yourself, make an fascinating discovery.

No cover
  • Book:
    Learn Python The Hard Way
  • Author:
  • Genre:
  • Year:
    2011
  • Rating:
    4 / 5
  • Favourites:
    Add to favourites
  • Your mark:
    • 80
    • 1
    • 2
    • 3
    • 4
    • 5

Learn Python The Hard Way: summary, description and annotation

We offer to read an annotation, description, summary or preface (depends on what the author of the book "Learn Python The Hard Way" wrote himself). If you haven't found the necessary information about the book — write in the comments, we will try to find it.

Learn Python The Hard Way — read online for free the complete book (whole text) full work

Below is the text of the book, divided by pages. System saving the place of the last page read, allows you to conveniently read the book "Learn Python The Hard Way" online for free, without having to search again every time where you left off. Put a bookmark, and you can go to the page where you finished reading at any time.

Light

Font size:

Reset

Interval:

Bookmark:

Make
Exercise 17: More Files

Now let's do a few more things with files. We're going to actually write aPython script to copy one file to another. It'll be very short but will giveyou some ideas about other things you can do with files.

1 2 3 4 5 6 7 8 9101112131415161718192021222324
from sys import argv from os.path import exists script , from_file , to_file = argv print "Copying from %s to %s " % ( from_file , to_file ) # we could do these two on one line too, how? input = open ( from_file ) indata = input . read () print "The input file is %d bytes long" % len ( indata ) print "Does the output file exist? %r " % exists ( to_file ) print "Ready, hit RETURN to continue, CTRL-C to abort." raw_input () output = open ( to_file , 'w' ) output . write ( indata ) print "Alright, all done." output . close () input . close ()

You should immediately notice that we import another handy commandnamed exists . This returns True if a file exists, based on itsname in a string as an argument. It returns False if not. We'll be usingthis function in the second half of this book to do lots of things, butright now you should see how you can import it.

Using import is a way to get tons of free code other better (well, usually)programmers have written so you do not have to write it.

What You Should See

Just like your other scripts, run this one with two arguments, the file to copyfrom and the file to copy it to. If we use your test.txt file from beforewe get this:

$ python ex17.py test.txt copied.txt Copying from test.txt to copied.txt The input file is 81 bytes long Does the output file exist? False Ready, hit RETURN to continue, CTRL-C to abort. Alright, all done. $ cat copied.txt To all the people out there. I say I don't like my hair. I need to shave it off. $

It should work with any file. Try a bunch more and see what happens. Justbe careful you do not blast an important file.

Warning

Did you see that trick I did with cat ? It only works on Linux or OSX,on Windows use type to do the same thing.

Extra Credit
  1. Go read up on Python's import statement, and start python to tryit out. Try importing some things and see if you can get it right. It'salright if you do not.
  2. This script is really annoying. There's no need to ask you beforedoing the copy, and it prints too much out to the screen. Try to make itmore friendly to use by removing features.
  3. See how short you can make the script. I could make this 1 line long.
  4. Notice at the end of the WYSS I used something called cat? It's an oldcommand that "con*cat*enates" files together, but mostly it's just aneasy way to print a file to the screen. Type man cat to read about it.
  5. Windows people, find the alternative to cat that Linux/OSXpeople have. Do not worry about man since there is nothing like that.
  6. Find out why you had to do output.close() in the code.
Copyright 2010, Zed A. Shaw. Last updated on Jun 24, 2011.
Exercise 41: Gothons From Planet Percal #25

Did you figure out the secret of the function in the dict from thelast exercise? Can you explain it to yourself? I'll explain itand you can compare your explanation with mine. Here are the lines ofcode we are talking about:

cities [ '_find' ] = find_city city_found = cities [ '_find' ]( cities , state )

Remember that functions can be variables too. The def find_city just makesanother variable name in your current module that you can use anywhere. Inthis code first we are putting the function find_city into the dict cities as '_find' . This is the same as all the others where we set states to somecities, but in this case it's actually the function.

Alright, so once we know that find_city is in the dict at _find , that meanswe can do work with it. The 2nd line of code (used later in the previousexercise) can be broken down like this:

  1. Python sees city_found = and knows we want to make a new variable.
  2. It then reads cities and finds that variable, it's a dict.
  3. Then there's ['_find'] which will index into the cities dict and pullout whatever is at _find .
  4. What is at ['_find'] is our function find_city so Python then knowsit's got a function, and when it hits ( it does the function call.
  5. The parameters cities, state are passed to this function find_city , andit runs because it's called.
  6. find_city then tries to look up states inside cities , and returnswhat it finds or a message saying it didn't find anything.
  7. Python takes what find_city returned, and finally that is what is assignedto city_found all the way at the beginning.

Here's a trick. Sometimes these things read better in Englishif you read the code backwards. This is how I would doit for that same line (remember backwards):

  1. state and city are...
  2. passed as parameters to...
  3. a function at...
  4. '_find' inside...
  5. the dict cities ...
  6. and finally assigned to city_found .

Here's another way to read it, this time "inside-out".

  1. Find the center item of the expression, in this case ['_find'] .
  2. Go counter-clock-wise and you have a dict cities , so this finds the element _find in cities.
  3. That gives us a function. Keep going counter-clock-wise and you get to the parameters.
  4. The parameters are passed to the function, and that returns a result. Go counter-clock-wise again.
  5. Finally, we are at the city_found = assignment, and we have our end result.

After decades of programming I don't even think about these three ways to readcode. I just glance at it and know what it means. I can even glance at a wholescreen of code, and all the bugs and errors jump out at me. That took an incrediblylong time and quite a bit more study than is sane. To get that way, I learned thesethree ways of reading most any programming language:

  1. Front to back.
  2. Back to front.
  3. Counter-clock-wise.

Try them out when you have a difficult statement to figure out.

Now type in your next exercise, then go over it.This one is gonna be fun.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
from sys import exit from random import randint def death (): quips = [ "You died. You kinda suck at this." , "Nice job, you died ...jackass." , "Such a luser." , "I have a small puppy that's better at this." ] print quips [ randint ( , len ( quips ) - )] exit ( ) def central_corridor (): print "The Gothons of Planet Percal #25 have invaded your ship and destroyed" print "your entire crew. You are the last surviving member and your last" print "mission is to get the neutron destruct bomb from the Weapons Armory," print "put it in the bridge, and blow the ship up after getting into an " print "escape pod." print " \n " print "You're running down the central corridor to the Weapons Armory when" print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume" print "flowing around his hate filled body. He's blocking the door to the" print "Armory and about to pull a weapon to blast you." action = raw_input ( "> " ) if action == "shoot!" : print "Quick on the draw you yank out your blaster and fire it at the Gothon." print "His clown costume is flowing and moving around his body, which throws" print "off your aim. Your laser hits his costume but misses him entirely. This" print "completely ruins his brand new costume his mother bought him, which" print "makes him fly into an insane rage and blast you repeatedly in the face until" print "you are dead. Then he eats you." return 'death' elif action == "dodge!" : print "Like a world class boxer you dodge, weave, slip and slide right" print "as the Gothon's blaster cranks a laser past your head." print "In the middle of your artful dodge your foot slips and you" print "bang your head on the metal wall and pass out." print "You wake up shortly after only to die as the Gothon stomps on" print "your head and eats you." return 'death' elif action == "tell a joke" : print "Lucky for you they made you learn Gothon insults in the academy." print "You tell the one Gothon joke you know:" print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr." print "The Gothon stops, tries not to laugh, then busts out laughing and can't move." print "While he's laughing you run up and shoot him square in the head" print "putting him down, then jump through the Weapon Armory door." return 'laser_weapon_armory' else : print "DOES NOT COMPUTE!" return 'central_corridor' def laser_weapon_armory (): print "You do a dive roll into the Weapon Armory, crouch and scan the room" print "for more Gothons that might be hiding. It's dead quiet, too quiet." print "You stand up and run to the far side of the room and find the" print "neutron bomb in its container. There's a keypad lock on the box" print "and you need the code to get the bomb out. If you get the code" print "wrong 10 times then the lock closes forever and you can't" print "get the bomb. The code is 3 digits." code = " %d%d%d " % ( randint ( , ), randint ( , ), randint ( , )) guess = raw_input ( "[keypad]> " ) guesses = while guess != code and guesses < : print "BZZZZEDDD!" guesses += guess = raw_input ( "[keypad]> " ) if guess == code : print "The container clicks open and the seal breaks, letting gas out." print "You grab the neutron bomb and run as fast as you can to the" print "bridge where you must place it in the right spot." return 'the_bridge' else : print "The lock buzzes one last time and then you hear a sickening" print "melting sound as the mechanism is fused together." print "You decide to sit there, and finally the Gothons blow up the" print "ship from their ship and you die." return 'death' def the_bridge (): print "You burst onto the Bridge with the netron destruct bomb" print "under your arm and surprise 5 Gothons who are trying to" print "take control of the ship. Each of them has an even uglier" print "clown costume than the last. They haven't pulled their" print "weapons out yet, as they see the active bomb under your" print "arm and don't want to set it off." action = raw_input ( "> " ) if action == "throw the bomb" : print "In a panic you throw the bomb at the group of Gothons" print "and make a leap for the door. Right as you drop it a" print "Gothon shoots you right in the back killing you." print "As you die you see another Gothon frantically try to disarm" print "the bomb. You die knowing they will probably blow up when" print "it goes off." return 'death' elif action == "slowly place the bomb" : print "You point your blaster at the bomb under your arm" print "and the Gothons put their hands up and start to sweat." print "You inch backward to the door, open it, and then carefully" print "place the bomb on the floor, pointing your blaster at it." print "You then jump back through the door, punch the close button" print "and blast the lock so the Gothons can't get out." print "Now that the bomb is placed you run to the escape pod to" print "get off this tin can." return 'escape_pod' else : print "DOES NOT COMPUTE!" return "the_bridge" def escape_pod (): print "You rush through the ship desperately trying to make it to" print "the escape pod before the whole ship explodes. It seems like" print "hardly any Gothons are on the ship, so your run is clear of" print "interference. You get to the chamber with the escape pods, and" print "now need to pick one to take. Some of them could be damaged" print "but you don't have time to look. There's 5 pods, which one" print "do you take?" good_pod = randint ( , ) guess = raw_input ( "[pod #]> " ) if int ( guess ) != good_pod : print "You jump into pod %s and hit the eject button." % guess print "The pod escapes out into the void of space, then" print "implodes as the hull ruptures, crushing your body" print "into jam jelly." return 'death' else : print "You jump into pod %s and hit the eject button." % guess print "The pod easily slides out into space heading to" print "the planet below. As it flies to the planet, you look" print "back and see your ship implode then explode like a" print "bright star, taking out the Gothon ship at the same" print "time. You won!" exit ( ) ROOMS = { 'death' : death , 'central_corridor' : central_corridor , 'laser_weapon_armory' : laser_weapon_armory , 'the_bridge' : the_bridge , 'escape_pod' : escape_pod } def runner ( map , start ): next = start while True : room = map [ next ] print " \n --------" next = room () runner ( ROOMS , 'central_corridor' )
Next page
Light

Font size:

Reset

Interval:

Bookmark:

Make

Similar books «Learn Python The Hard Way»

Look at similar books to Learn Python The Hard Way. We have selected literature similar in name and meaning in the hope of providing readers with more options to find new, interesting, not yet read works.


Reviews about «Learn Python The Hard Way»

Discussion, reviews of the book Learn Python The Hard Way and just readers' own opinions. Leave your comments, write what you think about the work, its meaning or the main characters. Specify what exactly you liked and what you didn't like, and why you think so.