Python coding the hard way pdf download






















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. There are no heavy text explanations but just practical coding examples to help beginners to learn through writing codes using 52 exercises that teach basics to advanced level coding and help to develop a solid foundation. Click on the button below to get learn python 3 the hard way pdf free download to your devices:.

All the important information and the details about this Python learning Pdf book are shared below:. Save my name, email, and website in this browser for the next time I comment. Terms and Conditions.

Press ESC to close. 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. 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.



0コメント

  • 1000 / 1000