Learn python the hard way pdf download free






















Finally the purpose of this setup is so you can do three things very reliably while you work on the exercises: 1. Run the exercises you wrote. Fix them when they are broken. Anything else will only confuse you, so stick to the plan. If you haven't done that then do not go on. You will not have a good time. This is the only time I'll start an exercise with a warning that you should not skip or get ahead of yourself.

Type the following text into a single file named ex1. This is important as python works best with files ending in. Notice I did not type the line numbers on the left Those are printed in the book so I can talk about specific lines by saying, "See line Notice I have the print at the beginning of the line and how it looks exactly the same as what I have above.

Exactly means exactly, not kind of sort of the same. Every single character has to match for it to work. But, the colors are all different. Color doesn't matter, only the characters you type. Then in Terminal run the file by typing: python ex1.

If not, you have done something wrong. No, the computer is not wrong. Even I make many of these mistakes. Let's look at this line-by-line. Here we ran our command in the terminal to run the ex1. Python then tells us that the file ex1. It then prints this line for us. Notice the missing " double-quote character? Finally, it prints out a "SyntaxError" and tells us something about what might be the error. Usually these are very cryptic, but if you copy that text into a search engine, you will find someone else who's had that error and you can probably figure out how to fix it.

Study Drills You will also have Study Drills. The Study Drills contains things you should try to do. If you can't, skip it and come back later. For this exercise, try these things: 1. Make your script print another line. Make your script print only one of the lines. Put a ' ' octothorpe character at the beginning of a line.

What did it do? Try to find out what this character does. From now on, I won't explain how each exercise works unless an exercise is different. Note An 'octothorpe' is also called a 'pound', 'hash', 'mesh', or any number of names.

Pick the one that makes you chill out. You may run into some of these, so I've collected them into answers for you. Save your file first as a. Then you'll have color when you type. I get SyntaxError: invalid syntax when I run ex1. You are probably trying to run python, then trying to type python again. Close your terminal, start it again, and right away type only python ex1.

I still can't get python in my PowerShell. You need to be in the same directory as the file you created. Make sure you use the cd command to go there first.

How do I get my country's language characters into my file? You most likely took the code in my file above literally, and thought that print "Hello World! Your file has to be exactly like mine, and in the code above and all of the screenshots, I have print "Hello World!

Make sure your code is like mine and it should work. They are used to tell you what something does in English, and they also are used to disable parts of your program if you need to remove them temporarily.

Here's how you use comments in Python: A comment, this is so you can read your program later. Anything after the is ignored by python. It is important for you to understand that everything does not have to be literal. Your screen and program may visually look different, but what's important is the text you type into the file you're writing in your text editor.

In fact, I could work with any text editor and the results would be the same. This will run. Again, I'm not going to show you screenshots of all the terminals possible.

Study Drills 1. Find out if you were right about what the character does and make sure you know what it's called octothorpe or pound character. Take your ex2. Start at the last line, and check each word in reverse against what you should have typed.

Did you find more mistakes? Fix them. Read what you typed above out loud, including saying each character by its name. Common Student Questions Are you sure is called the pound character? I call it the octothorpe and that is the only name that no country uses and that works in every country. Every country thinks their way to call this one character is both the most important way to do it, and also the only way it's done.

To me this is simply arrogance and really, y'all should just chill out and focus on more important things like learning to code. Python still ignores that as code, but it's used as a kind of "hack" or workaround for problems with setting and detecting the format of a file.

You also find a similar kind of comment for editor settings. Why does the in print "Hi there. The in that code is inside a string, so it will be put into the string until the ending " character is hit. These pound characters are just considered characters and aren't considered comments.

How do I comment out multiple lines? Put a in front of each one. I can't figure out how to type a character on my country's keyboard? Some countries use the Alt key and combinations of those to print characters foreign to their language. You'll have to look online in a search engine to see how to type it. Why do I have to read code backwards?

It's a trick to make your brain not attach meaning to each part of the code, and doing that makes you process each piece exactly. This catches errors and is a handy error checking technique.

Do not worry, programmers lie frequently about being math geniuses when they really aren't. If they were math geniuses, they would be doing math, not writing ads and social network games to steal people's money. This exercise has lots of math symbols. Let's name them right away so you know what they are called. As you type this one in, say the names. When saying them feels boring you can stop saying them.

After you type in the code for this exercise, go back and figure out what each of these does and complete the table. How about some more. Is it greater? True Is it greater or equal? True Is it less or equal? False Study Drills 1. Above each line, use the to write a comment to yourself explaining what the line does. Remember in Exercise 0 when you started python? Start python this way again and using the above characters and what you know, use python as a calculator.

Find something you need to calculate and write a new. Notice the math seems "wrong"? There are no fractions, only whole numbers. Find out why by researching what a "floating point" number is. Rewrite ex3. Mostly that's just how the designers chose to use that symbol. Another way to say it is, "X divided by Y with J remaining. What is the order of operations? That's the order Python follows as well. It's not really rounding down, it's just dropping the fractional part after the decimal.

Try doing 7. The next step is to learn about variables. In programming a variable is nothing more than a name for something so you can use the name rather than the something as you code. Programmers use these variable names to make their code read more like English, and because they have lousy memories. If they didn't use good names for things in their software, they'd get lost when they tried to read their code again.

If you get stuck with this exercise, remember the tricks you have been taught so far of finding differences and focusing on details: 1. Write a comment above each line explaining to yourself what it does in English.

Read your. Find out how to type it if you do not already know. We use this character a lot to put an imaginary space between words in variable names. There are only 30 drivers available. There will be 70 empty cars today. We can transport We have 90 to carpool today.

We need to put about 3 in each car. Study Drills When I wrote this program the first time I had a mistake, and python told me about it like this: Traceback most recent call last : File "ex4.

Make sure you use line numbers and explain why. Here's more extra credit: 1. I used 4. What happens if it's just 4? Remember that 4. Find out what that means. Write comments above each of the variable assignments. Try running python as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j. You can, but it's bad form. You should add space around operators like this so that it's easier to read.

How can I print without spaces between words in print? You will do more of this soon. What do you mean by "read the file backwards"? Very simple. Imagine you have a file with 16 lines of code in it. Start at line 16, and compare it to my file at line Then do it again for 15, and so on until you've read the whole file backwards. Why did you use 4. See the extra credit. This time we'll use something called a "format string". Every time you put " double-quotes around a piece of text you have been making a string.

A string is how you make something that your program might give to a human. You print them, save them to files, send them to web servers, all sorts of things. Strings are really handy, so in this exercise you will learn how to make strings that have variables embedded in them.

You embed variables inside a string by using specialized format sequences and then putting the variables at the end with a special syntax that tells Python, "Hey, this is a format string, put these variables in there. He's 74 inches tall. He's pounds heavy. Actually that's not too heavy. He's got Blue eyes and Brown hair. His teeth are usually White depending on the coffee. If I add 35, 74, and I get Try more format characters. It's like saying "print this no matter what".

Search online for all of the Python format characters. Try to write some variables that convert the inches and pounds to centimeters and kilos. Do not just type in the measurements. Work out the math in Python.

No, the 1 is not a valid variable name. They need to start with a character, so a1 would work, but 1 will not. You'll learn more about this as you continue, but they are "formatters". I don't get it, what is a "formatter"? The problem with teaching you programming is that to understand many of my descriptions you need to know how to do programming already. The way I solve this is I make you do something, and then I explain it later.

When you run into these kinds of questions, write them down and see if I explain it later. How can I round a floating point number? You can use the round function like this: round 1.

I get this error TypeError: 'str' object is not callable. Why does this not make sense to me? Try making the numbers in this script your measurements. It's weird, but talking about yourself will make it seem more "real". In this exercise we create a bunch of variables with complex strings so you can see what they are for. First an explanation of strings. A string is usually a bit of text you want to display to someone, or "export" out of the program you are writing.

Python knows you want something to be a string when you put either " double-quotes or ' single-quotes around the text. You saw this many times with your use of print when you put the text you want to go to the string inside " or ' after the print.

Then Python prints it. Strings may contain the format characters you have discovered so far. The only catch is that if you want multiple formats in your string to print multiple variables, you need to put them inside parenthesis separated by , commas.

It's as if you were telling me to buy you a list of items from the store and you said, "I want milk, eggs, bread, and soup. We will now type in a whole bunch of strings, variables, formats, and print them. You will also practice using short abbreviated variable names.

Programmers love saving themselves time at your expense by using annoying cryptic variable names, so let's get you started being able to read and write them early on. Those who know binary and those who don't.

I said: 'There are 10 types of people. I also said: 'Those who know binary and those who don't. Isn't that joke so funny?! False This is the left side of Go through this program and write a comment above each line explaining it. Find all the places where a string is put inside a string.

There are four places. Are you sure there's only four places? How do you know? Maybe I like lying. Yes, and you'll learn more about these boolean values in exercise Why do you put ' single-quotes around some strings and not others?

Mostly it's because of style, but I'll use a single-quote inside a string that has double-quotes. Look at line 10 to see how I'm doing that. I get the error TypeError: not all arguments converted during string formatting. You need to make sure that line of code is exactly the same. Go back and figure out what you did wrong.

I won't be explaining much since it is just more of the same. The purpose is to build up your chops. See you in a few exercises, and do not skip! Do not paste! Its fleece was white as snow. And everywhere that Mary went. Cheese Burger Study Drills For these next few exercises, you will have the exact same extra credit. Go back through and write a comment on what each line does. Read each one backwards or out loud to find your errors.

From now on, when you make mistakes write down on a piece of paper what kind of mistake you made. When you go to the next exercise, look at the last mistakes you made and try not to make them in this new one. Remember that everyone makes mistakes. Programmers are like magicians who like everyone to think they are perfect and never wrong, but it's all an act. They make mistakes all the time. Common Student Questions How does the "end" statement work? These are not really an "end statement", but actually the names of variables that just happen to have the word "end" in them.

Why are you using the variable named 'snow'? That's actually not a variable, it is just a string with the word snow in it. A variable wouldn't have the single-quotes around it. Is it normal to write an English comment for every line of code like you say to do in Study Drills 1? No, normally you write comments only to explain difficult to understand code, or why you did something.

Why or your motivation is usually much more important, and then you try to write the code so that it explains how something is being done on its own. However, sometimes you just have to write such nasty code to solve a problem that it does need a comment on every line.

In this case though it's strictly for you to get better at translating from code to English. Can I use single-quotes or double-quotes to make a string or do they do different things? In Python either way to make a string is acceptable although typically you'll use single-quotes for any short strings like 'a' or 'snow'. Couldn't you just not use the comma , and turn the last two lines into one single-line print? Yes, you could very easily, but then it'd be longer than 80 characters which in Python is bad style.

Do your checks of your work, write down your mistakes, try not to make them on the next exercise. Notice that the last line of output uses both single and double quotes for individual pieces.

Why do you think that is? Why do I have to put quotes around "one" but not around True or False? That's because Python recognizes True and False as keywords representing the concept of true and false. You'll learn more about how these work in Exercise Python is going to print the strings in the most efficient way it can, not replicate exactly the way you wrote them.

Why doesn't this work in Python 3? Don't use Python 3. Use Python 2. No, you should learn to use the command line. It is essential to learning programming and is a good place to start if you want to learn about programming. IDLE will fail for you when you get further in the book.

With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. It's the "raw" format for debugging. I get an error when I put spaces between the three double-quotes? You have to type them like """ and not " " ", meaning with no spaces between each one. Is it bad that my errors are always spelling mistakes? Most programming errors in the beginning and even later are simple spelling mistakes, typos, or getting simple things out of order. In Exercise 9 I threw you some new stuff, just to keep you on your toes.

I showed you two ways to make a string that goes across multiple lines. What these two characters do is put a new line character into the string at that point. These two characters will print just one back-slash. We'll try a few of these sequences so you can see what I mean. Another important escape sequence is to escape a single-quote ' or double-quote ".

Imagine you have a string that uses double-quotes and you want to put a double-quote in for the output. If you do this "I "understand" joe. You need a way to tell Python that the " inside the string isn't a real double-quote.

To solve this problem you escape double-quotes and single-quotes so Python knows to include in the string. We'll also play with these. What You Should See Look for the tab characters that you made. In this exercise the spacing is important to get right. I'm split on a line. You may not use many of these, but memorize their format and what they do anyway.

Also try them out in some strings to see if you can make them work. Escape What it does. Memorize all the escape sequences by putting them on flash cards. Use ''' triple-single-quote instead.

Can you see why you might use that instead of """? Combine escape sequences and format strings to create a more complex format. Common Student Questions I still haven't completely figured out the last exercise, should I continue?

Yes, keep going and instead of stopping take notes listing things you don't understand for each exercise. Periodically go through your notes and see if you can figure these things out after you've completed more exercises. Sometimes though you may need to go back a few exercises and go through them again. Think about why you would need this. They are different characters that do very different things. I don't get Study Drills 3. What do you mean by "combine" escapes and formats? One of the things I try to get you to understand is that each of these exercises can be combined to solve problems.

Take what you know about format sequences and write some new code that uses those and the escapes from this exercise. What's better, ''' or """? It's entirely based on style. I have got you doing a lot of printing so that you get used to typing simple things, but those simple things are fairly boring. What we want to do now is get data into your programs. This is a little tricky because you have learn to do two things that may not make sense right away, but trust me and do it anyway.

It will make sense in a few exercises. Most of what software does is the following: 1. Take some kind of input from a person. Change it. Print out something to show how it changed. So far you have only been printing, but you haven't been able to get any input from a person, or change it.

You may not even know what "input" means, so rather than talk about it, let's have you do some and see if you get it. Next exercise we'll do more to explain it. This is so that print doesn't end the line with a newline and go to the next line. Can you find other ways to use it? Try some of the samples you find. Write another "form" like this to ask some other questions. See how the single-quote needs to be escaped because otherwise it would end the string?

You don't put your height in there, you type it directly into your terminal. First thing is, go back and make the code exactly like mine. Next, run the script, and when it pauses, type your height in at your keyboard. That's all there is to it. Why do you have a newline on line 8 instead of putting it on one line? That's so that the line is less than 80 characters long, which is a style that Python programmers like. You could put it on one line if you like.

The input function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it. When my strings print out there's a u in front of them, as in u'35'. That's how Python tells you that the string is unicode. This is how you ask someone a question and get their answer. Read what it says. Get out of pydoc by typing q to quit. Go look online for what the pydoc command does.

Use pydoc to also read about open, file, os, and sys. It's alright if you do not understand those, just read through and take notes about interesting things. You aren't running pydoc from the command line, you're probably running it from inside python. Exit out of python first. Why does my pydoc not pause like yours does?

Sometimes if the help document is short enough to fit on one screen then pydoc will just print it. When I run pydoc I get more is not recognized as an internal. Some versions of Windows do not have that command, which means pydoc is broken for you.

You can skip this extra credit and just search online for Python documentation when you need it. I will not answer this question again so you must memorize this fact. This is the 1 thing people ask repeatedly, and asking the same question over and over means you aren't taking the time to memorize what you should.

Stop now, and finally memorize this fact. Why can't I do print "How old are you? You'd think that'd work, but Python doesn't recognize that as valid.

The only answer I can really give is, you just can't. You know how you type python ex Well the ex What we'll do now is write a script that also accepts arguments. This is how you add features to your script from the Python feature set. Rather than give you all the features at once, Python asks you to say what you plan to use.

This keeps your programs small, but it also acts as documentation for other programmers who read your code later. The argv is the "argument variable", a very standard name in programming, that you will find used in many other languages.

This variable holds the arguments you pass to your Python script when you run it. In the exercises you will get to play with this more and see what happens. Line 3 "unpacks" argv so that, rather than holding all the arguments, it gets assigned to four variables you can work with: script, first, second, and third.

This may look strange, but "unpack" is probably the best word to describe what it does. It just says, "Take whatever is in argv, unpack it, and assign it to all of these variables on the left in order.

Hold Up! Features Have Another Name I call them "features" here these little things you import to make your Python program do more but nobody else calls them features. I just used that name because I needed to trick you into learning what they are without jargon.

From now on we will be calling these "features" that we import modules. I'll say things like, "You want to import the sys module.

Notice when I run it I give it first 2nd, which caused it to give an error about "need more than 3 values to unpack" telling you that you didn't give it enough parameters.

Try giving fewer than three arguments to your script. See that error you get? See if you can explain it. Write a script that has fewer arguments and one that has more.

Make sure you give the unpacked variables good names. Remember that modules give you features. Remember this because we'll need it later. Remember that an important skill is paying attention to details. If you look at the What You Should See section you see that I run the script with parameters on the command line. You should replicate how I ran it exactly. The different has to do with where the user is required to give input. If they give your script inputs on the command line, then you use argv.

Are the command line arguments strings? Yes, they come in as strings, even if you typed numbers on the command line. How do you use the command line? Don't over think it.

From that start playing with more ways to use both in the same script. Because that's backwards to how it should work.

Do it the way I do it and it'll work. You will need this for the next exercise where we learn to read and write files. This is similar to a game like Zork or Adventure. Not sure where that is. Now if we want to make the prompt something else, we just change it in this one spot and rerun the script. Very handy. What You Should See When you run this, remember that you have to give the script your name for the argv arguments. I'd like to ask you a few questions.

Do you like me zed? You live in 'San Francisco'. And you have a 'Tandy ' computer. Find out what Zork and Adventure were. Try to find a copy and play it.

Change the prompt variable to something else entirely. Add another argument and use it in your script. Again, you have to run it right on the command line, not inside python. If you type python, and then try to type python ex Close your window and then just type python ex I don't understand what you mean by changing the prompt? Change that to have a different value. You know this, it's just a string and you've done 13 exerises making them, so take the time to figure it out.

I get the error ValueError: need more than 1 value to unpack. You need to do the same thing here and focus on how I type the command in, and why I have a command line argument. Can I use double-quotes for the prompt variable? You totally can. Go ahead and try that.

You have a Tandy computer? I did when I was little. I get NameError: name 'prompt' is not defined when I run it. You either spelled the name of the prompt variable wrong or forgot that line.

Go back and compare each line of code to mine, and start at the bottom of the script and work your way to the top. Don't use IDLE. You may have to play with this exercise the most to understand what's going on, so do it carefully and remember your checks.

Working with files is an easy way to erase your work if you are not careful. This exercise involves writing two files. One is your usual ex This second file isn't a script but a plain text file we'll be reading in our script. Here are the contents of that file: This is stuff I typed into a file. It is really cool stuff.

Lots and lots of fun to have in here. What we want to do is "open" that file in our script and print it out. That's bad because we want it to load other files later. Next we have line 5 where we use a new command open. Right now, run pydoc open and read the instructions.

You just opened a file. Line 7 we print a little line, but on line 8 we have something very new and exciting. We call a function on txt. What you got back from open is a file, and it's also got commands you can give it.

You give a file a command by using the. The difference is that when you say txt. Do your read command with no parameters! Study Drills This is a big jump so be sure you do this extra credit as best you can before moving on. Above each line write out in English what that line does. If you are not sure ask someone for help or search online. Try searching for "python open". I used the name "commands" here, but they are also called "functions" and "methods". Search around online to see what other people do to define these.

Do not worry if they confuse you. It's normal for a programmer to confuse you with their vast extensive knowledge. Think of why one way of getting the filename would be better than another.

See all the other ones you can use? Try some of the other commands. Startup python again and use open from the prompt. Notice how you can open files and run read on them right there? It's important to close files when you are done with them. You can think of it like an old tape drive that you saw on mainframe computers in the 50s, or even like a DVD play from today. You can move around inside them, and then "read" them, but the file is not the contents. Now you are in python as we've done a few other times.

Once you have that you can just type in code and python will run it in little pieces. Play with that. What does from sys import argv mean? For now just understand that sys is a package, and this phrase just says to get the argv feature from that package. You'll learn more about these later.

No, that's not how you do it. Make the code exactly like mine, then run it from the command line the exact same way I do. You don't put the names of files in, you let Python put the name in. Why is there no error when we open the file twice?

Python will not restrict you from opening a file more than once and in fact sometimes this is necessary. Here's the list of commands I want you to remember: close -- Closes the file. For now these are the important commands you need to know. Some of them take parameters, but we do not really care about that.

You only need to remember that write takes a parameter of a string you want to write to the file. So go slow, do your checks, and make it run. One trick is to get bits of it running at a time. Get lines running, then 5 more, then a few more, etc. Opening the file Truncating the file. Now I'm going to ask you for three lines. And finally, we close it. Now, open up the file you made in my case test. Neat right? If you feel you do not understand this, go back through and use the comment trick to get it squared away in your mind.

One simple English comment above each line will help you understand, or at least let you know what you need to research more. Write a script similar to the last exercise that uses read and argv to read the file you just created. There's too much repetition in this file.

Use strings, formats, and escapes to print out line1, line2, and line3 with just one target. Find out why we had to pass a 'w' as an extra parameter to open. Hint: open tries to be safe by making you explicitly say you want to write a file. If you open the file with 'w' mode, then do you really need the target. Go read the docs for Python's open function and see if that's true.

Common Student Questions Is the truncate necessary with the 'w' parameter? See Study Drills 5. What does 'w' mean? It's really just a string with a character in it for the kind of mode for the file. There's also 'r' for "read", 'a' for append, and modifiers on these. What are the modifiers to the file modes we can use?

This will open the file in both read and write mode, and depending on the character use position the file in different ways. Does just doing open filename open it in 'r' read mode?

Yes, that's the default for the open function. We're going to actually write a Python script to copy one file to another. It'll be very short but will give you some ideas about other things you can do with files. This returns True if a file exists, based on its name in a string as an argument. It returns False if not.

We'll be using this function in the second half of this book to do lots of things, but right 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 copy from and the file to copy it to. I'm going to use a simple test file named test.

Alright, all done. It should work with any file. Try a bunch more and see what happens. Just be careful you do not blast an important file. Warning Did you see that trick I did with cat? Go read up on Python's import statement, and start python to try it out. Try importing some things and see if you can get it right. It's alright if you do not.

This script is really annoying. There's no need to ask you before doing the copy, and it prints too much out to the screen. Try to make it more friendly to use by removing features. See how short you can make the script. I could make this 1 line long. Type man cat to read about it. Please bear in mind that we do not own copyrights to these books. We highly encourage our visitors to purchase original books from respected publishers.

If someone with copyrights wants us to remove this content, please contact us immediately. All books on the learntocodetogether. If you feel that we have violated your copyrights, then please contact us immediately click here. Tags: learn python learn python the hard way 3rd edition learn to code together python. Buy Me a Coffee. All Rights Reserved. Theme by. He kept updating it from time to time and eventually Addison-Wesley turned it into a book by the same name and they have now brought it out in its third edition.

The website is made up of lots of short exercises that help beginner programmers learn the various nuances of Python but in bite-sized chunks. A DVD with more than 5 hours of the tutorial is bundled with the book so that readers also have access to video material. Two things to note before you begin are that the book is on Python 2 and you are warned against installing Python 3.

Shaw explicitly tells you not to use IDE or an alternative Python editor. The book is split into 52 exercises or chapters if you will.



0コメント

  • 1000 / 1000