The write stuff book pdf




















Sling Bags. Lunch Bags. Passport Covers. Travel Organizers. Gadget Accessories. Lifestyle Gifts. Party Supplies. Make Your Own Combo. Desk Supplies. Fidget Pop It. Night Suits.

Hair Accessories. Log in. Quirky Stationery. Shop Now. Unicorn Stationery. New Arrivals. Quick view. Unicorn Pony Steel Bottle. Unicorn Rocking Mug. Bunny Ice Cream Keychain. Unicorn Pop it Sling Bag. Unicorn Desk Calendar. Cute Kitty Desk Lamp. Living in Full Colour sipper. Unicorn Gift Set.

Regular price Rs. Angel Cup and Saucer. View all. View all 19 products. Close esc. It is not guaranteed that at least one of the clauses will be executed.

When there is a chain of elif statements, only one or none of the clauses will be executed. For example, open a new file editor window and enter the following code, saving it as vampire. Figure shows the flowchart for this. The flowchart for multiple elif statements in the vampire. Remember that the rest of the elif clauses are automatically skipped once a True condition has been found, so if you swap around some of the clauses in vampire. Change the code to look like the following, and save it as vampire2.

You might expect the code to print the string 'Unlike you, Alice is not an undead, immortal vampire. Remember, at most only one of the clauses will be executed, and for elif statements, the order matters!

Figure shows the flowchart for the previous code. Optionally, you can have an else statement after the last elif statement. In that case, it is guaranteed that at least one and only one of the clauses will be executed.

If the conditions in every if and elif statement are False, then the else clause is executed. Else, if the second condition is true, do that. Otherwise, do something else. First, there is always exactly one if statement. Any elif statements you need should follow the if statement. Second, if you want to be sure that at least one clause is executed, close the structure with an else statement. The flowchart for the vampire2. The crossed-out path will logically never happen, because if age were greater than , it would have already been greater than Flowchart for the previous littleKid.

In code, a while statement always consists of the following: The while keyword A condition that is, an expression that evaluates to True or False A colon Starting on the next line, an indented block of code called the while clause You can see that a while statement looks similar to an if statement.

The difference is in how they behave. At the end of an if clause, the program execution continues after the if statement. But at the end of a while clause, the program execution jumps back to the start of the while statement.

The while clause is often called the while loop or just the loop. But when you run these two code snippets, something very different happens for each one. For the if statement, the output is simply "Hello, world. Take a look at the flowcharts for these two pieces of code, Figure and Figure , to see why this happens.

The flowchart for the while statement code The code with the if statement checks the condition, and it prints Hello, world. The code with the while loop, on the other hand, will print it five times. In the while loop, the condition is always checked at the start of each iteration that is, each time the loop is executed. If the condition is True, then the clause is executed, and afterward, the condition is checked again. The first time the condition is found to be False, the while clause is skipped.

This is so that the name! Since this is the last line of the block, the execution moves back to the start of the while loop and reevaluates the condition. If the value in name is not equal to the string 'your name', then the condition is True, and the execution enters the while clause again. But once the user types your name, the condition of the while loop will be 'your name'! Figure shows a flowchart for the yourName. A flowchart of the yourName. Press F5 to run it, and enter something other than your name a few times before you give the program what it wants.

Please type your name. Al Please type your name. Albert Please type your name. Here, the input call lets the user enter the right string to make the program move on. In other programs, the condition might never actually change, and that can be a problem. In code, a break statement simply contains the break keyword.

Pretty simple, right? Enter the following code, and save the file as yourName2. The expression True, after all, always evaluates down to the value True. The program execution will always enter the loop and will exit it only when a break statement is executed. An infinite loop that never exits is a common programming bug. Since this condition is merely the True Boolean value, the execution enters the loop to ask the user to type your name again.

See Figure for the flowchart of this program. Run yourName2. The rewritten program should respond in the same way as the original.

The flowchart for the yourName2. Note that the X path will logically never happen because the loop condition is always True. This is also what happens when the execution reaches the end of the loop. This will send a KeyboardInterrupt error to your program and cause it to stop immediately. To try it, create a simple infinite loop in the file editor, and save it as infiniteloop. Enter the following code into a new file editor window and save the program as swordfish.

What is the password? It is a fish. When it reevaluates the condition, the execution will always enter the loop, since the condition is simply the value True. Otherwise, the execution continues to the end of the while loop, where it then jumps back to the start of the loop. A flowchart for swordfish. The X path will logically never happen because the loop condition is always True. When used in conditions, 0, 0. You could have typed not name! Run this program and give it some input.

Who are you? I'm fine, thanks. Joe Hello, Joe. Mary Who are you? You can do this with a for loop statement and the range function. The first time it is run, the variable i is set to 0. The print call in the clause will print Jimmy Five Times 0. The variable i will go up to, but will not include, the integer passed to range. Figure shows a flowchart for the fiveTimes. The flowchart for fiveTimes. In fact, you can use continue and break statements only inside while and for loops.

If you try to use these statements elsewhere, Python will give you an error. As another for loop example, consider this story about the mathematician Karl Friedrich Gauss. When Gauss was a boy, a teacher wanted to give the class some busywork.

The teacher told them to add up all the numbers from 0 to Young Gauss came up with a clever trick to figure out the answer in a few seconds, but you can write a Python program with a for loop to do this calculation for you. By the time the loop has finished all of its iterations, every integer from 0 to will have been added to total. Even on the slowest computers, this program takes less than a second to complete.

Clever kid! An Equivalent while Loop You can actually use a while loop to do the same thing as a for loop; for loops are just more concise.

The Starting, Stopping, and Stepping Arguments to range Some functions can be called with multiple arguments separated by a comma, and range is one of them. This lets you change the integer passed to range to follow any sequence of integers, including starting at a number other than zero. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration. For example I never apologize for my puns , you can even use a negative number for the step argument to make the for loop count down instead of up.

Python also comes with a set of modules called the standard library. Each module is a Python program that contains a related group of functions that can be embedded in your programs. For example, the math module has mathematics-related functions, the random module has random number— related functions, and so on. Before you can use the functions in a module, you must import the module with an import statement. In code, an import statement consists of the following: The import keyword The name of the module Optionally, more module names, as long as they are separated by commas Once you import a module, you can use all the cool functions of that module.

Enter this code into the file editor, and save it as printRandom. Since randint is in the random module, you must first type random. With this form of import statement, calls to functions in random will not need the random. However, using the full name makes for more readable code, so it is better to use the normal form of the import statement.

Ending a Program Early with sys. This always happens if the program execution reaches the bottom of the instructions. However, you can cause the program to terminate, or exit, by calling the sys. Since this function is in the sys module, you have to import sys before your program can use it. Open a new file editor window and enter the following code, saving it as exitExample. This program has an infinite loop with no break statement inside. The only way this program will end is if the user enters exit, causing sys.

When response is equal to exit, the program ends. Since the response variable is set by the input function, the user must enter exit in order to stop the program. Summary By using expressions that evaluate to True or False also called conditions , you can write programs that make decisions on what code to execute and what code to skip.

You can also execute code over and over again in a loop while a certain condition evaluates to True. The break and continue statements are useful if you need to exit a loop or jump back to the start.

These flow control statements will let you write much more intelligent programs. What are the two values of the Boolean data type? How do you write them? What are the three Boolean operators? Write out the truth tables of each Boolean operator that is, every possible combination of Boolean values for the operator and what they evaluate to. What do the following expressions evaluate to?

What are the six comparison operators? What is the difference between the equal to operator and the assignment operator? Explain what a condition is and where you would use one. Write code that prints Hello if 1 is stored in spam, prints Howdy if 2 is stored in spam, and prints Greetings! What can you press if your program is stuck in an infinite loop? What is the difference between break and continue? What is the difference between range 10 , range 0, 10 , and range 0, 10, 1 in a for loop?

Write a short program that prints the numbers 1 to 10 using a for loop. Then write an equivalent program that prints the numbers 1 to 10 using a while loop. If you had a function named bacon inside a module named spam, how would you call it after importing spam? Extra credit: Look up the round and abs functions on the Internet, and find out what they do.

Experiment with them in the interactive shell. Python provides several builtin functions like these, but you can also write your own functions. A function is like a mini-program within a program. Type this program into the file editor and save it as helloFunc. This code is executed when the function is called, not when the function is first defined.

When the program execution reaches these calls, it will jump to the top line in the function and begin executing the code there. When it reaches the end of the function, the execution returns to the line that called the function and continues moving through the code as before. Since this program calls hello three times, the code in the hello function is executed three times.

When you run this program, the output looks like this: Howdy! Hello there. A major purpose of functions is to group code that gets executed multiple times. Without a function defined, you would have to copy and paste this code each time, and the program would look like this: print 'Howdy! You can also define your own functions that accept arguments.

Type this example into the file editor and save it as helloFunc2. A parameter is a variable that an argument is stored in when a function is called. One special thing to note about parameters is that the value stored in a parameter is forgotten when the function returns.

For example, if you added print name after hello 'Bob' in the previous program, the program would give you a NameError because there is no variable named name. This variable was destroyed after the function call hello 'Bob' had returned, so print name would refer to a name variable that does not exist. Return Values and return Statements When you call the len function and pass it an argument such as 'Hello', the function call evaluates to the integer value 5, which is the length of the string you passed it.

In general, the value that a function call evaluates to is called the return value of the function. When creating a function using the def statement, you can specify what the return value should be with a return statement.

A return statement consists of the following: The return keyword The value or expression that the function should return When an expression is used with a return statement, the return value is what this expression evaluates to. For example, the following program defines a function that returns a different string depending on what number it is passed as an argument.

Type this code into the file editor and save it as magic8Ball. Because the function is being defined and not called , the execution skips over the code in it. Next, the random. It evaluates to a random integer between 1 and 9 including 1 and 9 themselves , and this value is stored in a variable named r. Then, depending on this value in answerNumber, the function returns one of many possible string values.

A function call can be used in an expression because it evaluates to its return value. None is the only value of the NoneType data type. Other programming languages might call this value null, nil, or undefined. One place where None is used is as the return value of print.

But since all function calls need to evaluate to a return value, print returns None. This is similar to how a while or for loop implicitly ends with a continue statement.

Also, if you use a return statement without a value that is, just the return keyword by itself , then None is returned. Keyword Arguments and print Most arguments are identified by their position in the function call. For example, random. The function call random. However, keyword arguments are identified by the keyword put before them in the function call. Keyword arguments are often used for optional parameters. For example, the print function has the optional parameters end and sep to specify what should be printed at the end of its arguments and between its arguments separating them , respectively.

If you ran the following program: print 'Hello' print 'World' the output would look like this: Hello World The two strings appear on separate lines because the print function automatically adds a newline character to the end of the string it is passed. However, you can set the end keyword argument to change this to a different string. Instead, the blank string is printed.

This is useful if you need to disable the newline that gets added to the end of every print function call. Similarly, when you pass multiple string values to print , the function will automatically separate them with a single space. For now, just know that some functions have optional keyword arguments that can be specified when the function is called.

Variables that are assigned outside all functions are said to exist in the global scope. A variable that exists in a local scope is called a local variable, while a variable that exists in the global scope is called a global variable. A variable must be one or the other; it cannot be both local and global. Think of a scope as a container for variables. There is only one global scope, and it is created when your program begins.

When your program terminates, the global scope is destroyed, and all its variables are forgotten. Otherwise, the next time you ran your program, the variables would remember their values from the last time you ran it.

A local scope is created whenever a function is called. Any variables assigned in this function exist within the local scope. When the function returns, the local scope is destroyed, and these variables are forgotten. The next time you call this function, the local variables will not remember the values stored in them from the last time the function was called. Scopes matter for several reasons: Code in the global scope cannot use any local variables.

However, a local scope can access global variables. You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.

The reason Python has different scopes instead of just making everything a global variable is so that when variables are modified by the code in a particular call to a function, the function interacts with the rest of the program only through its parameters and the return value.

This narrows down the list code lines that may be causing a bug. If your program contained nothing but global variables and had a bug because of a variable being set to a bad value, then it would be hard to track down where this bad value was set. It could have been set from anywhere in the program — and your program could be hundreds or thousands of lines long!

But if the bug is because of a local variable with a bad value, you know that only the code in that one function could have set it incorrectly. While using global variables in small programs is fine, it is a bad habit to rely on global variables as your programs get larger and larger.

Once the program execution returns from spam, that local scope is destroyed, and there is no longer a variable named eggs. So when your program tries to run print eggs , Python gives you an error saying that eggs is not defined. This is why only global variables can be used in the global scope. Local Scopes Cannot Use Variables in Other Local Scopes A new local scope is created whenever a function is called, including when a function is called from another function. Multiple local scopes can exist at the same time.

When bacon returns, the local scope for that call is destroyed. This is what the program prints. The upshot is that local variables in one function are completely separate from the local variables in another function. This is why 42 is printed when the previous program is run. Local and Global Variables with the Same Name To simplify your life, avoid using local variables that have the same name as a global variable or another local variable.

Since these three separate variables all have the same name, it can be confusing to keep track of which one is being used at any given time. This is why you should avoid using the same variable name in different scopes. The global Statement If you need to modify a global variable from within a function, use the global statement.

No local spam variable is created. There are four rules to tell whether a variable is in a local scope or global scope: 1. If a variable is being used in the global scope that is, outside of all functions , then it is always a global variable. If there is a global statement for that variable in a function, it is a global variable.

Otherwise, if the variable is used in an assignment statement in the function, it is a local variable. But if the variable is not used in an assignment statement, it is a global variable.

Type the following code into the file editor and save it as sameName3. If you run sameName3. NOTE If you ever want to modify the value stored in a global variable from in a function, you must use a global statement on that variable.

If you try to use a local variable in a function before you assign a value to it, as in the following program, Python will give you an error. To see this, type the following into the file editor and save it as sameName4. Later chapters in this book will show you several modules with functions that were written by other people. Exception Handling Right now, getting an error, or exception, in your Python program means the entire program will crash.

Instead, you want the program to detect errors, handle them, and then continue to run. Open a new file editor window and enter the following code, saving it as zeroDivide. This is the output you get when you run the previous code: From the line number given in the error message, you know that the return statement in spam is causing an error. Errors can be handled with try and except statements. The code that could potentially have an error is put in a try clause.

The program execution moves to the start of a following except clause if an error happens. You can put the previous divide-by-zero code in a try clause and have an except clause contain code to handle what happens when this error occurs. After running that code, the execution continues as normal. The output of the previous program is as follows: None The reason print spam 1 is never executed is because once the execution jumps to the code in the except clause, it does not return to the try clause.

Instead, it just continues moving down as normal. When you run this program, the output will look something like this: I am thinking of a number between 1 and Take a guess. You guessed my number in 4 guesses! Type the following source code into the file editor, and save the file as guessTheNumber. This is a guess the number game.

Then, the program imports the random module so that it can use the random. The return value, a random integer between 1 and 20, is stored in the variable secretNumber.

The code that lets the player enter a guess and checks that guess is in a for loop that will loop at most six times. The first thing that happens in the loop is that the player types in a guess. This gets stored in a variable named guess.

In either case, a hint is printed to the screen. If the guess is neither higher nor lower than the secret number, then it must be equal to the secret number, in which case you want the program execution to break out of the for loop. In both cases, the program displays a variable that contains an integer value guessesTaken and secretNumber.

Since it must concatenate these integer values to strings, it passes these variables to the str function, which returns the string value form of these integers. Summary Functions are the primary way to compartmentalize your code into logical groups. Since the variables in functions exist in their own local scopes, the code in one function cannot directly affect the values of variables in other functions.

This limits what code could be changing the values of your variables, which can be helpful when it comes to debugging your code. Functions are a great tool to help you organize your code. In previous chapters, a single error could cause your programs to crash. In this chapter, you learned about try and except statements, which can run code when an error has been detected. This can make your programs more resilient to common error cases. Why are functions advantageous to have in your programs?

When does the code in a function execute: when the function is defined or when the function is called? What statement creates a function? What is the difference between a function and a function call? How many global scopes are there in a Python program? How many local scopes?

What happens to variables in a local scope when the function call returns? What is a return value? Can a return value be part of an expression? If a function does not have a return statement, what is the return value of a call to that function? How can you force a variable in a function to refer to the global variable?

What is the data type of None? What does the import areallyourpetsnamederic statement do? If you had a function named bacon in a module named spam, how would you call it after importing spam? How can you prevent a program from crashing when it gets an error?

What goes in the try clause? What goes in the except clause? Practice Projects For practice, write programs to do the following tasks.

The Collatz Sequence Write a function named collatz that has one parameter named number. Then write a program that lets the user type in an integer and that keeps calling collatz on that number until the function returns the value 1.

The output of this program could look something like this: Enter number: 3 10 5 16 8 4 2 1 Input Validation Add try and except statements to the previous project to detect whether the user types in a noninteger string. Normally, the int function will raise a ValueError error if it is passed a noninteger string, as in int 'puppy'.

In the except clause, print a message to the user saying they must enter an integer. Lists and tuples can contain multiple values, which makes it easier to write programs that handle large amounts of data. And since lists themselves can contain other lists, you can use them to arrange data into hierarchical structures.

The List Data Type A list is a value that contains multiple values in an ordered sequence. The term list value refers to the list itself which is a value that can be stored in a variable or passed to a function like any other value , not the values inside the list value. A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].

Just as string values are typed with quote characters to mark where the string begins and ends, a list begins with an opening square bracket and ends with a closing square bracket, [].

Values inside the list are also called items. Items are separated with commas that is, they are comma-delimited. But the list value itself contains other values. The value [] is an empty list that contains no values, similar to '', the empty string. Getting Individual Values in a List with Indexes Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam. The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate to 'bat', and so on.

The integer inside the square brackets that follows the list is called an index. The first value in the list is at index 0, the second value is at index 1, the third value is at index 2, and so on. Figure shows a list value assigned to spam, along with what the index expressions would evaluate to.

A list value stored in the variable spam, showing which value each index refers to For example, type the following expressions into the interactive shell. Start by assigning a list to the variable spam. Python will give you an IndexError error message if you use an index that exceeds the number of values in your list value.

For example, spam[0][1] prints 'bat', the second value in the first list. If you only use one index, the program will print the full list value at that index.

Negative Indexes While indexes start at 0 and go up, you can also use negative integers for the index. The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last index in a list, and so on.

A slice is typed between square brackets, like an index, but it has two integers separated by a colon. Notice the difference between indexes and slices.

In a slice, the first integer is the index where the slice starts. A slice goes up to, but will not include, the value at the second index. A slice evaluates to a new list value. Leaving out the first index is the same as using 0, or the beginning of the list.

Leaving out the second index is the same as using the length of the list, which will slice to the end of the list. However, you can also use an index of a list to change the value at that index.

All of the values in the list after the deleted value will be moved up one index. If you try to use the variable after deleting it, you will get a NameError error because the variable no longer exists.

In practice, you almost never need to delete simple variables. The del statement is mostly used to delete values from lists. It turns out that this is a bad way to write code. For one thing, if the number of cats changes, your program will never be able to store more cats than you have variables. These types of programs also have a lot of duplicate or nearly identical code in them.

Consider how much duplicate code is in the following program, which you should enter into the file editor and save as allMyCats1. This new version uses a single list and can store any number of cats that the user types in. In a new file editor window, type the following source code and save it as allMyCats2.

Using for Loops with Lists In Chapter 2, you learned about using for loops to execute a block of code a certain number of times. Technically, a for loop repeats the code block once for each value in a list or list-like value. For example, if you ran this code: for i in range 4 : print i the output of this program would be as follows: 0 1 2 3 This is because the return value from range 4 is a list-like value that Python considers similar to [0, 1, 2, 3]. The following program has the same output as the previous one: for i in [0, 1, 2, 3]: print i What the previous for loop actually does is loop through its clause with the variable i set to a successive value in the [0, 1, 2, 3] list in each iteration.

NOTE In this book, I use the term list-like to refer to data types that are technically named sequences. A common Python technique is to use range len someList with a for loop to iterate over the indexes of a list.

Best of all, range len supplies will iterate through all the indexes of supplies, no matter how many items it contains. Like other operators, in and not in are used in expressions and connect two values: a value to look for in a list and the list where it may be found. To see what your friends thought of this book, please sign up. To ask other readers questions about The Write Stuff , please sign up. Lists with This Book. This book is not yet featured on Listopia. Add this book to your favorite list ».

Community Reviews. Showing Average rating 4. Rating details. More filters. Sort order. Start your review of The Write Stuff. Aug 17, Debbie rated it it was amazing.

Where has this book been all my teaching life! Can't wait to give it a go in September. Highly recommend this to all primary school teachers. Apr 05, Gillian rated it liked it Shelves: reference-writing. I had looked forward to reading this book for ages, having heard great things about it.

Having read it, I'm now thinking perhaps I need to be teaching UK curriculum to get excited about this one. There are certainly some ideas and elements that I can adapt but it felt a lot like it was written to enable teachers to tick off UK curriculum boxes, rather than to grow amazing writers.

Mar 09, Simon Mark Watson rated it it was amazing. Perfect reading for any teacher interested in improving their literacy teaching. I taught my first lesson today and wow what a marked difference. Looking forward to what lies ahead for my year 6 and the school as a whole as literacy lead. Mar 19, Elizabeth rated it it was amazing. Truly inspiring read. Lots of common sense stuff too. Why did we not think of it before.

Dec 17, Sophiebeth rated it it was amazing. Wow this book was very inspirational. May 23, Clare Marie rated it really liked it.



0コメント

  • 1000 / 1000