Learn more python 3 the hard way pdf download
Line 7 prints a little message, but on line 8 we have something very new and exciting. We call a function on txt named read. What you get back from open is a file, and it also has commands you can give it. You give a file a command by using the. The difference is that txt.
Do your read command with no parameters! I said pay attention! You have been running scripts with just the name of the script, but now that you are using argv you have to add arguments.
Look at the very first line of the example below and you will see I do python ex If you do not type that you will get an error so pay attention! It is really cool stuff. Lots and lots of fun to have in here. Study Drills This is a big jump, so be sure you do this Study Drill 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. Get rid of the lines where you use input and run the script again.
Use only input and try the script that way. Why is one way of getting the filename better than another? Notice how you can open files and run read on them from within python3. First thing, from the command line just type python3. Now you are in python3. Then you can type in code and Python will run it in little pieces.
Play with that. To get out of it type quit and hit Enter. Why is there no error when we open the file twice? Python will not restrict you from opening a file more than once, and sometimes this is necessary. 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.
Make the code exactly like mine, then run it from the command line the exact same way I do. You can assign the result to a variable. Watch out if you care about the file. In the early days of computers data was stored on each of these kinds of media, so many of the file operations still resemble a storage system that is linear. 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. What You Should See There are actually two things you will see. Opening the file Truncating the file. Now I'm going to ask you for three lines.
Now, open up the file you made in my case test. Neat, right? If 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. 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.
Common Student Questions Is the truncate necessary with the 'w' parameter? See Study Drills 5. What does 'w' mean? What modifiers to the file modes can I 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? This returns True if a file exists, based on its name in a string as an argument.
It returns False if not. 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. 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. Did you see the trick I did with echo to make a file and cat to show the file?
This script is really annoying. Try to make the script more friendly to use by removing features. See how short you can make the script. I could make this one line long. Type man cat to read about it. Try importing some things and see if you can get it right. Make sure you know what a string is. No way you can make this one line!
That ; depends ; on ; how ; you ; define ; one ; line ; of ; code. Is it normal to feel like this exercise was really hard? Yes, it is totally normal. Everyone is different, so just keep going and keep reviewing exer- cises that you had trouble with until it clicks.
Be patient. What does the len function do? It gets the length of the string that you pass to it then returns that as a number. Play with it. When I try to make this script shorter I get an error when I close the files at the end. It should already be closed by Python once that one line runs.
I get a Syntax:EOL while scanning string literal error. You forgot to end a string properly with a quote. Go look at that line again. I am about to introduce you to the function! Dum dum dah! Every programmer will go on and on about functions and all the different ideas about how they work and what they do, but I will give you the simplest explanation you can use right now. Functions do three things: 1. They name pieces of code the way variables name strings and numbers.
They take arguments the way your scripts take argv. On the same line as def we give the function a name. This has to go inside parentheses to work. Then we end this line with a : colon and start indenting. Our first indented line is one that unpacks the arguments, the same as with your scripts. To demonstrate how it works we print these arguments out, just like we would in a script.
In Python we can skip the whole unpacking arguments and just use the names we want right inside. This is very important. What You Should See If you run ex Right away you can see how a function works. This means you can make your own commands and use them in your scripts too.
Study Drills Create a function checklist for later exercises. Write these checks on an index card and keep it by you while you complete the rest of these exercises or until you feel you do not need the index card anymore: 1.
Did you start your function definition with def? Did you put an open parenthesis right after the function name? Did you put your arguments after the parenthesis separated by commas? Did you make each argument unique meaning no duplicated names? Did you put a close parenthesis and a colon : after the arguments?
Did you indent all lines of code you want in the function four spaces? No more, no less. Did you put the character after the name to run it? Did you put the values you want into the parenthesis separated by commas? Did you end the function call with a character?
Use these two checklists on the remaining lessons until you do not need them anymore. The same as variable names. That tells Python to take all the arguments to the function and then put them in args as a list. This feels really boring and monotonous.
To make it less boring, take everything I tell you to type in, and then break it on purpose. Just keep doing these exercises and going through your checklist from the last exercise and you will eventually get it. The variables in your function are not connected to the variables in your script. We can give it straight numbers. We can give it variables.
We can give it math. We can even combine math and variables. You have 30 boxes of crackers! Man that's enough for a party! Get a blanket. OR, we can use variables from our script: You have 10 cheeses!
You have 50 boxes of crackers! We can even do math inside too: You have 30 cheeses! You have 11 boxes of crackers! And we can combine the two, variables and math: You have cheeses! You have boxes of crackers! Go back through the script and type a comment above each line explaining in English what it does. Start at the bottom and read each line backward, saying all the important characters.
Write at least one more function of your own design, and run it 10 different ways. See how creative you can get with functions, vari- ables, and input from a user.
Is there a way to analyze what this function is doing so I can understand it better? There are many dif- ferent ways, but try putting an English comment above each line describing what the line does. Another trick is to read the code out loud.
What if I want to ask the user for the numbers of cheese and crackers? You need to use int to con- vert what you get from input. No, those variables are separate and live outside the function.
When the function exits these tempo- rary variables go away and everything keeps working. Keep going in the book, and this should become clearer. But sometimes necessity means you have to use the same name, or you might do it on accident. Just avoid it whenever you can. Is there a limit to the number of arguments a function can have? The practical limit though is about five arguments before the function becomes annoying to use. Can you call a function within a function? Write English comments for each line to understand what that line does.
Find each place a function is used, and check its def to make sure that you are giving it the right arguments. Research online what the seek function for file does.
Try pydoc file, and see if you can figure it out from there. Then try pydoc file. A file in Python is kind of like an old tape drive on a mainframe or maybe a DVD player. Each time you do f. This will be explained more as you go on. First, the seek function is dealing in bytes, not lines. The code seek 0 moves the file to the 0 byte first byte in the file. We are manually incrementing it.
How does readline know where each line is? The file f is responsible for maintaining the current position in the file after each readline call, so that it will keep reading each line. Why are there empty lines between the lines in the file? There will be one thing to pay close attention to, but first type this in: ex What this does is the following: 1.
Our function is called with two arguments: a and b. Python adds the two numbers. To help there is extra credit to solve a puzzle and learn something cool. At the end of the script is a puzzle. It looks really weird, but if you run the script, you can see the results.
What you should do is try to figure out the normal formula that would recreate this same set of operations. Once you have the formula worked out for the puzzle, get in there and see what happens when you modify the parts of the functions.
Try to change it on purpose to make another value. Do the inverse. Write a simple formula and use the functions in the same way to calculate it. This exercise might really whack your brain out, but take it slow and easy and treat it like a little game.
Remember int input? Convert that to use the functions. In fact, this exercise is like one giant Study Drills. Make sure your list of symbols is complete. Next to each word or symbol, write its name and what it does. If you do not know what a word or symbol does, then read about it again and try using it in some code.
This may get boring, but push through and really nail it down. Once you have memorized the list and what they do, then step it up by writing out tables of symbols, their names, and what they do from memory. It helps you focus on a goal and know the purpose of all your efforts. In this exercise you are learning the names of symbols so that you can read source code more easily. Just take it slow and do not hurt your brain. Giving your brain a rest will help you learn faster with less frustration.
How modern computers store human languages for display and processing and how Python 3 calls this strings. How to handle errors in your string and byte handling. For now your job is to get a taste of the future and learn the four topics in the preceding list.
This exercise is hard! I recommend you take this exercise painfully slow. Take a paragraph at a time if you must. Just chip away at it for as long as it takes. The languages. There may be quite a few things that are new, so scan the file a few times.
Just give it a try. Switches, Conventions, and Encodings Before I can get into what this code means, you need to learn some basics about how data is stored in a computer. Modern computers are incredibly complex, but at their core they are like a huge array of light switches.
Computers use electricity to flip switches on or off. These switches can represent 1 for on, or 0 for off. One represents energy, electricity, on, power, substance. Zero represents off, done, gone, power down, the lack of energy. Computers take these 1s and 0s and use them to encode larger numbers. At the small end a computer will use 8 of these 1s and 0s to encode numbers There were even huge wars in the early history of computers on nothing more than the order of these bits because they were simply conventions we all had to agree on.
There are futher conventions for encoding large numbers using 16, 32, 64, and even more bits if you get into really big math. Once you have bytes you can start to store and display text by deciding on another convention for how a number maps to a letter. In the early days of computing there were many conventions that mapped 8 or 7 bits or less or more onto lists of characters kept inside a computer. This standard maps a number to a letter. Most of the early text in computers was nothing more than sequences of bytes, stored in memory, that a computer used to display text to a person.
Again, this is just a sequence of conventions that turned switches on and off. Re- member that a byte can hold numbers , or Different countries created their own en- coding conventions for their languages, and that mostly worked, but many encodings could only handle one language. That meant if you want to put the title of an American English book in the middle of a Thai sentence you were kind of in trouble.
To solve this problem a group of people created Unicode. You can use 32 bits to encode a Unicode character, and that is more characters than we could possibly find. Right now we use the extra space for important things like poop and smile emojis.
That means we have one more convention that is nothing more than a compression encoding, making it possible for most common characters to use 8 bits and then escape out into 16 or 32 bits as needed. You can also use other conventions encodings , but utf-8 is the current standard. On the left is the numbers for each byte of the utf-8 shown in hexadecimal , and the right has the character output as actual utf Disecting the Code We have an understanding of strings and byte sequences.
In Python a string is a UTF-8 encoded se- quence of characters for displaying or working with text. This is all based on conventions for how Python wants to work with text. Raw bytes have no convention to them. Again, Python knows its internal convention, but it has no idea what convention you need. In that case, you must use. This will be called at the end of this script to get things going.
You have done this before so nothing new here. Just readline as before when dealing with text files. You will learn about this in the second half of the book, so consider this a teaser of interesting things to come.
This is an if-statement, and it lets you make decisions in your Python code. The readline function will return an empty string when it reaches the end of the file and if line simply tests for this empty string. As long as readline gives us something, this will be true, and the code under indented in, lines will run. When this is false, Python will skip lines This simplifies my code and makes it easier for me to understand it.
If I want to learn what this function does, I can jump to it and study. I am calling main again inside main. All the information you need is there. This looks like I am calling the function inside itself, which seems like it should be illegal to do. Ask yourself, why should that be illegal? That would make it loop. I pass to encode the encoding I want and how to handle errors.
Remember that this then jumps to where the main function is defined on line 5, and on line 10 main is called again, causing this to keep looping. The if line: on line 8 will prevent our loop from going forever. Encodings Deep Dive We can now use our little script to explore other encodings.
Breaking It Rough ideas include the following: 1. Find strings of text encoded in other encodings and place them in the ex Extra challenging: Rewrite this using the b'' bytes instead of the UTF-8 strings, effectively revers- ing the script. If you can do that, then you can also break these bytes by removing some to see what happens. How much do you need to remove to cause Python to break? Use what you learned from 4 to see if you can mangle the files.
What errors do you get? This exercise is longer and all about building up stamina. The next exercise will be similar. Do them, get them exactly right, and do your checks. We can also do that this way: We'd have Make sure to do your checks: read it backward, read it out loud, and put comments above con- fusing parts.
Break the file on purpose, then run it to see what kinds of errors you get. Make sure you can fix it. Remember that inside the function the variable is temporary. When you return it then it can be assigned to a variable for later. What do you mean by reading the code backward? Start at the last line. Compare that line in your file to the same line in mine.
Do this until you get to the first line of the file. Who wrote that poem? I did. Not all of my poems suck. This exercise should be straightforward for you to type in, break down, and understand.
However, this exercise is a little different. Instead you will import it into Python and run the functions yourself. Once you have found all of the errors you can and fixed them, you will then want to follow the What You Should See section to complete the exercise. You run python3. Using this I want you to type each of these lines of Python code into python3.
Take the remaining lines of the What You Should See output and figure out what they are doing. Make sure you understand how you are running your functions in the ex25 module.
Try doing this: help ex25 and also help ex Notice how you get help for your module and how the help is those odd """ strings you put after each function in ex25? Typing ex Start a new session and see how all your functions are right there. Try breaking your file and see what it looks like in python when you use it. You will have to quit python with quit to be able to reload it. Common Student Questions I get None printed out for some of the functions.
You probably have a function that is missing the re- turn at the end. Go backward through the file and confirm that every line is right. I get -bash: import: command not found when I type import ex That means you first run Python. I get ImportError: No module named ex Python knows the file ends in. I get SyntaxError: invalid syntax when I run this. That means you have something like a missing or " or similar syntax error on that line or above it.
How can the words. This is similar to how files and many other things worked when you were working with them. When should I print instead of return in a function? The return from a function gives the line of code that called the function a result. You can think of a function as taking input through its arguments and returning output through return.
The print is completely unrelated to this and only deals with printing output to the terminal. You are almost done with the first half of the book. The second half is where things get interesting. You will learn logic and be able to do useful things like make decisions.
Before you continue, I have a quiz for you. Programmers will very frequently claim that their code is perfect. These programmers are stupid people who care little for others. I have poorly copied Exercises 24 and 25 into a file and removed random characters and added flaws.
Most of the errors are things Python will tell you, while some of them are math errors you should find. Others are formatting errors or spelling mistakes in the strings. All of these errors are very common mistakes all programmers make. Even experienced ones. Your job in this exercise is to correct this file. Use all of your skills to make this file better.
Analyze it first, maybe printing it out to edit it like you would a school term paper. Fix each flaw and keep running it and fixing it until the script runs perfectly. Try not to get help. If you get stuck take a break and come back to it later. Even if this takes days to do, bust through it and make it right. This is the only time you are allowed to copy-paste. Common Student Questions Do I have to import ex You can do either.
This file has the functions from ex25 though, so first go with removing references to it. You most certainly may. The computer is there to help, so use it as much as possible. Up to this point you have done everything you possibly can reading and writing files, to the Terminal, and have learned quite a lot of the math capabilities of Python.
From now on, you will be learning logic. Learning logic has to come after you do some memorization. I want you to do this exercise for an entire week. Do not falter. Even if you are bored out of your mind, keep doing it. This exercise has a set of logic tables you must memorize to make it easier for you to do the later exercises. It will be downright boring and tedious, but this teaches you a very important skill you will need as a programmer. You will need to be able to memorize important concepts in your life.
Most of these concepts will be exciting once you get them. You will struggle with them, like wrestling a squid, then one day you will understand it. All that work memorizing the basics pays off big later. Do not try to sit down for two hours straight and memorize these tables.
Your brain will only retain whatever you studied in the first 15 or 30 minutes anyway. Instead, create a bunch of index cards with each column on the left True or False on the front, and the column on the right on the back.
Once you can do that, start writing out your own truth tables each night into a notebook. Do not just copy them. Try to do them from memory. When you get stuck, glance quickly at the ones I have here to refresh your memory. Doing this will train your brain to remember the whole table.
Do not spend more than one week on this, because you will be applying it as you go. The terms and, or, not actually work the way you expect them to, just like in English.
The Truth Tables We will now use these characters to make the truth tables you need to memorize. NOT True? Remember though, there is no failing in this book, just trying as hard as you can each day, and then a little bit more. If you memorize these first, it not only builds your memorization skills, but it also makes these operations natural. After that, the concept of Boolean algebra is easy. But do whatever works for you. Boolean logic is used everywhere in programming. It is a fundamental part of computation, and knowing them very well is akin to knowing your scales in music.
In this exercise you will take the logic exercises you memorized and start trying them out in Python. Take each of these logic problems and write what you think the answer will be. In each case it will be either True or False. Once you have the answers written down, you will start Python in your terminal and type each logic problem in to confirm your answers. True and True 2. False and True 3. False and 0! Whenever you see these Boolean logic statements, you can solve them easily by this simple process: 1.
Find each not and invert it. When you are done you should have True or False. I will demonstrate with a variation on 3! Solve each equality test: 3! Find each not and invert it: not True is False: True and False 4.
The more complicated ones may seem very hard at first. You should be able to take a good first stab at solving them, but do not get discouraged. There are a lot of operators in Python similar to!
Write out the names of each of these equality operators. For example, I call! Play with Python by typing out new Boolean operators, and before you press Enter try to shout out what it is. Do not think about it. Shout the first thing that comes to mind. Write it down, then press Enter, and keep track of how many you get right and wrong. Throw away the piece of paper from 3 so you do not accidentally try to use it later. Common Student Questions Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True?
Python and many languages like to return one of the operands to their Boolean expressions rather than just True or False. This means that if you did False and 1 you get the first operand False , but if you do True and 1 you get the second 1. Play with this a bit. Is there any difference between! Other than that there should be no difference. Any and expression that has a False is immediately False, so you can stop there.
Any or expression that has a True is immediately True, so you can stop there. But make sure that you can process the whole expression because later it becomes helpful. The world is doomed! The world is saved! The world is dry! People are greater than or equal to dogs. People are less than or equal to dogs.
People are dogs. Study Drills In this Study Drill, try to guess what you think the if-statement is and what it does. Try to answer these questions in your own words before moving on to the next exercise: 1. What do you think the if does to the code under it? Why does the code under the if need to be indented four spaces? Can you put other boolean expressions from Exercise 27 in the if-statement? Try it.
What happens if you change the initial values for people, cats, and dogs? You did the Study Drills right? This is exactly the same thing you did when you made functions in the first half of the book. Python expects you to indent something after you end a line with a : colon.
Yes you can, and they can be as complex as you like, although really complex things generally are bad style. Because you are comparing numbers, if you change the numbers, different if-statements will evaluate to True and the blocks of code under them will run. Go back and put different numbers in and see if you can figure out in your head which blocks of code will run. This is important for when you do the next exercise where you write all the parts of if-statements that you can use.
Type this one in and make it work too. Maybe we could take the trucks. Alright, let's just take the trucks. Try to guess what elif and else are doing. Change the numbers of cars, people, and trucks, and then trace through each if-statement to see what will be printed. Above each line write an English description of what the line does. Python starts at the top and runs the first block that is True, so it will run only the first one. Your scripts ran starting at the top and went to the bottom where they ended.
Now that you have if, else, and elif you can start to make scripts that decide things. In the last script you wrote out a simple set of tests asking some questions. In this script you will ask the user questions and make decisions based on their answers. Write this script, and then play with it quite a lot to figure it out. Take the cake. Scream at the bear. Good job! Yellow jacket clothespins. Understanding revolvers yelling melodies. Make sure you understand this concept of if-statements inside if-statements.
In fact, do the Study Drills to really nail it. What You Should See Here is me playing this little adventure game. I do not do so well. Do you go through door 1 or door 2? What do you do? Make new parts of the game and change what decisions people can make. Expand the game out as much as you can before it gets ridiculous. Write a completely new game.
This is your computer; do what you want. Common Student Questions Can you replace elif with a sequence of if-else combinations? It also means that Python will check every if-else com- bination, rather than just the first false ones like it would with if-elif-else. Try to make some of these to figure out the differences. How do I tell whether a number is between a range of numbers?
What if I wanted more options in the if-elif-else blocks? Add more elif blocks for each possible choice. If you have been keep- ing up, you should realize that now you can combine all the other things you have learned with if- statements and boolean expressions to make your programs do smart things. However, programs also need to do repetitive things very quickly.
We are going to use a for-loop in this exercise to build and print various lists. When you do the exercise, you will start to figure out what they are. You have to figure it out. Before you can use a for-loop, you need a way to store the results of loops somewhere.
The best way to do this is with lists. Lists are exactly what their name says: a container of things that are organized in order from first to last. Then you put each item you want in the list separated by commas, similar to function arguments. Python then takes this list and all its contents and assigns them to the variable.
Your brain has been taught that the world is flat. Remember in the last exercise where you put if- statements inside if-statements? In programming nested struc- tures are all over the place. You will find functions that call other functions that have if-statements that have lists with lists inside lists. We now will build some lists using some for-loops and print them out: ex Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list.
Take a look at how you used range. Look up the range function to understand it. Could you have avoided that for-loop entirely on line 22 and just assigned range 0,6 directly to elements?
Find the Python documentation on lists and read about them. What other operations can you do to lists besides append? Common Student Questions How do you make a 2-dimensional 2D list? Depends on the language and the implementation. In Ruby though they call these arrays. In Python they call them lists. The variable is defined by the for-loop when it starts, initializing it to the current element of the loop iteration each time through.
Why does for i in range 1, 3 : only loop two times instead of three times? The range function only does numbers from the first to the last, not including the last. So it stops at two, not three in the preceding. This turns out to be the most common way to do this kind of loop.
It simply appends to the end of the list. Open up the Python shell and try a few examples with a list you make. Any time you run into things like this, always try to play with them interactively in the Python shell. A while-loop will keep executing the code block under it as long as a boolean expression is True. Wait, you have been keeping up with the terminology, right?
That if we write a line and end it with a : colon then that tells Python to start a new block of code? This is all about structuring your programs so that Python knows what you mean.
If you do not get that idea then go back and do some more work with if-statements, functions, and the for-loop until you get it. Back to while-loops. A while-loop runs until the expression is False. This is great if your intention is to just keep looping until the end of the universe. Otherwise you almost always want your loops to end eventually. To avoid these problems, there are some rules to follow: 1. Make sure that you use while-loops sparingly.
Usually a for-loop is better. Review your while statements and make sure that the boolean test will become False at some point. In this exercise, you will learn the while-loop while doing these three checks: ex Use this function to rewrite the script to try different numbers. Rewrite the script again to use this function to see what effect that has. Write it to use for-loops and range. Do you need the incrementor in the middle anymore? What happens if you do not get rid of it?
A while-loop can do any kind of iteration looping you want. However, while-loops are harder to get right, and you normally can get many things done with for-loops. Loops are hard. How do I figure them out? When a loop runs, it goes through its block of code, and at the end it jumps back to the top. Most of the chapters are under four pages in length. In fact, there are a lot of chapters that have a blank page between it and the next chapter, so there is some filler going on here.
Each chapter also has some drills and some common student questions in them. From simple things like strings, dictionaries, and lists, to conditionals, loops, functions, and classes. They are all covered here. In the introduction, Mr.
Shaw makes a big deal about how if you, the reader, feel like he is insulting your intelligence, then you are not in the intended audience for this book. I assume he is attempting to be funny, but he comes across as snarky, at best.
Regardless of whether you enjoy that type of writing, the core content is pretty good. I think beginners will benefit from the book. Think Python free PDF download. Facebook 0 Tweet 0. Previous Article Skype now has a new feature that helps conduct technical and coding interviews.
Next Article Which programming language should I spend time to? Search a tutorial Search for:.
0コメント