Learn python 3 the hard way free pdf download
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. 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. Checkout the different books links which we have mention below which will be used for the various exams also at the last we have given the link so that you can buy from this books.
For any queries or questions feel free to ask below in comments. Surely this book will be a boon for you guys which will help you to clear your doubts easily.
Also if candidates who are can not study from PDF can also download the Hard copy book from the below image link we have provided. This book will help surely clear all your basics of all the topics asked in the exam paper. Also we have provided some other books links too you can check them all and prepare yourself for the written examinations.
Hope you have a enjoyable preparations and surely you can clear your written exams. You also buy this book from our website you will get it in the left side bar column from amazon you can have it or can also study from the PDF. Follow us on Facebook. Hope you have downloaded the books required for the exams. For any questions feel free to ask below in comments. Also keep following us on Facebook for more updates or can subscribe us on mail.
You Will Learn Python 3!
0コメント