PENS AND TURTLES 49 Skywriting You can only use colors that appear In this program, you control a plane. As you fly it will leave on the Scratch a smoke trail, so you can draw in the sky. Start a new project interface. To select and add the plane sprite, then add this script. red, click in the square and then click on ▷ Flying high when clicked the red stop button above the stage Use the left and right keys to turn the set size to 20 % plane. Switch on the smoke with the “a” Makes the key and turn it off with the “z” key. Press set pen color to line thicker the spacebar to clear the sky. Keeps the plane set pen size to 3 on the stage forever move 2 steps if on edge, bounce Keeps the plane moving LINGO when right arrow ▾ key pressed turn 10 degrees Turtle graphics Rotates when left arrow ▾ key pressed Using sprites to draw pictures right turn 10 degrees is called “turtle graphics.” That’s because there’s a type of Rotates robot called a turtle that can be left moved around the floor to draw pictures. The first programming when a ▾ key pressed language to use turtle graphics was called LOGO. pen down Turns the pen on when z ▾ key pressed pen up Turns the pen off when space ▾ key pressed clear Clears the pen trail
50 S T A R T I N G F R O M S C R A T C H SEE ALSO Variables Maths 52–53 Variables 108–109 In coding, a variable is the name for a place where you can store information. Variables are in Python used to remember things such as the score, a player’s name, or a character’s speed. Creating a variable ◁ Storing data You can create a variable to use in your program Variables are like boxes using the “Data” section of the blocks palette. Once where you can store a variable has been created, new blocks appear in different bits of the blocks palette ready for you to use. information for use in your program. 1 Make a variable 2 Name the new variable First, click the “Data” button in the blocks Give the variable a name that will help you palette. Then select the “Make a Variable” button. to remember what it does. Select which sprites will use the variable, then click “OK.” Scripts Costumes Sounds Motion Events Type in a Choose whether the variable Looks Control name for your will be used by all sprites or Sound Sensing variable here just the one selected Pen Operators Click the Data More Blocks New Variable “Data” Variable name: steps button For all sprites For this sprite only Make a Variable Cloud variable (stored on server) Make a List OK Cancel Click here to Tick to show the The variable block can be create a variable variable on the stage used inside other blocks 3 A new variable is created steps Use this block to give Once a new variable has been the variable a value created, new blocks appear in the blocks set steps ▾ to 0 palette. The menus inside these blocks let Change the value of a you select which variable they apply to, if change steps ▾ by 1 variable using this block. you have created more than one. A negative number will decrease its value
VARIABLES 51 Using a variable Variables can be used to change a sprite’s speed. This simple script shows you how. 1 Set the value of a variable 2 Changing the value of a variable Create this script. Use the “set steps to 0” block Use the “change steps by 1” block to increase the and change the number to 5. Drag the “move 10 steps” value of the variable “steps” by 1. Put it inside the block into the script, but drop the “steps” variable “forever” block, so the cat keeps on getting faster. block over the “10.” when clicked This sets the value when clicked The “steps” of the “steps” variable keeps variable to 5 on increasing as the “forever”loop set steps ▾ to 5 set steps ▾ to 0 goes around and forever around forever Here, “steps” means 5, as the value has been set above move steps steps change steps ▾ by 1 if on edge, bounce move steps steps if on edge, bounce Set my speed using the “set steps to 0” block. Deleting variables EXPERT TIPS When you no longer want a variable, Read-only variables right-click on it in the blocks palette and then select “delete variable.”You’ll lose Some variables are set by Scratch and can’t any information that was in it. be changed. They’re still variables, though, because their values vary. These blocks are known as sensing blocks. Make a Variable Variables can distance to ▾ Tracks the distance to Make a List be renamed costume # something, such as the here direction mouse-pointer. steps Reports the number of the costume a sprite is rename variable wearing. delete variable Tells you which direction a sprite is travelling in.
52 S T A R T I N G F R O M S C R A T C H Math SEE ALSO As well as storing numbers in variables (see pp.50–51), 50–51 Variables Scratch can be used to carry out all sorts of calculations Math 112–113 using the “Operator” blocks. in Python Doing sums 7 + 22 64 – 28 There are four “Operator” blocks △ Addition △ Subtraction that can be used to do simple The “+” block adds the two The “–” block subtracts the calculations. These are addition, numbers in the block together. second number from the first. subtraction, multiplication, and division. The “think” block is used here to print the result think 2+5 11 * 10 120 / 4 △ Printing results △ Multiplication △ Division Drag a “think” block into the scripts area and Computers use the “*” There’s no division sign on drop a “+” block inside it. Now add two numbers symbol for multiplication, the keyboard, so Scratch together and watch your sprite think the answer. because “x” looks like a letter. uses the “/” symbol instead. Results in a variable Variables are useful if you want to repeat the same sum For more complex calculations, such as fixing the sale price of an item, instead of just using with different values. numbers you can use the value of a variable in a sum. The result can be stored in a variable too. 1 Create variables 2 Set the price set price ▾ to 50 Go to the “Data” section of the Select the “set price” blocks palette and create two block and fix the price of Use the drop-down variables—“sale price” and “price”. an item to 50. menu to select “price” 3 Calculate the sale price set sale price ▾ to price /2 Use this script to calculate half the price of an Drag the “price” variable Add the “/” block inside item and set it as the sale price. into the window to the “set sale price” block divide the price by 2
M AT H 53 Random numbers EXPERT TIPS The “pick random” block can be used to select a Gaming random number between two values. This block is useful for rolling dice in a game or for when Computers often use random you want to mix up a sprite’s costumes. numbers to add surprises to games. For example, an alien can pick random 1 to 10 ◁ Pick a random number be made to appear in a random place, or after a random amount You can change To pick a random month, of time. It can be used to select the numbers change the numbers to a random value, as if you were in the block choose a number between rolling a dice, or a random 1 and 12. costume for a sprite. when clicked This block makes the Chooses a costume sprite wait for two between 1 and 3 forever seconds before switching at random to another costume wait 2 sec ◁ Switching costumes pick random 1 to 3 This script changes a sprite’s switch costume to costume at random every two seconds. ◁ Random costumes Costumes can make a sprite appear to move its body, or might give it different clothes, as shown here. Hard math 10 mod 3 Divides 10 by 3 and gives the remainder—the Simple “Operator” blocks can do most Gives nearest whole number that is left over calculations, but Scratch can also do number to 44.7 more complex math. The “mod” ◁ More math block divides two numbers and gives round 44.7 The “Operator” section the remainder, which is the number has blocks of advanced that is left over. The “round” block Choose different functions math functions that rounds to the nearest whole number, from the drop-down menu can be used to do and the “sqrt” block gives the square sqrt ▾ of 9 complex calculations. root of a number. Calculates the square root of 9
54 S T A R T I N G F R O M S C R A T C H Strings and lists SEE ALSO 50–51 Variables In programming, a sequence of letters and symbols Strings 114–115 is called a “string”. Strings can contain any character in Python on the keyboard (including spaces) and be of any length. Strings can also be grouped together in lists. Keyboard characters are lined up as if they were hanging from a string A BC D E F G H I Working with words 1 Create a new variable Click the “Data” button in the blocks palette Programs often need to remember words, and click the “Make a Variable” button. Create a such as a player’s name. Variables can be variable called “greeting”. created to remember these words. Scratch programs can also ask the user questions, Make a Variable Name your which they answer by typing into a text Make a List variable “greeting” box that pops up. The following script asks for the user’s name, and then makes a greeting sprite say “Hello” to them. This block puts “Hello ” into the variable 2 Asking a question when clicked “greeting”. Leave a space at the end of “Hello ” This script makes the to make the output of the program neater sprite ask a question. set greeting ▾ to Hello Whatever the user types The “ask” box (from the “Sensing” into the text box that pops section of the blocks palette) makes a text box appear, which the user up on the screen is stored ask What’s your name? and wait types their answer into in a new variable called “answer”. The script then say join greeting answer combines the strings contained in the “greeting” and “answer” variables to The “answer” variable (from the “Sensing” greet to the user. The “say” bubble The “greeting” section) contains creates a speech variable holds the whatever the user bubble for the sprite string “Hello ” typed into the text box
STRINGS AND LISTS 55 Making lists Variables are perfect if you just want to remember one thing. To remember lots of similar things, lists can be used instead. Lists can store many items of data (numbers and strings) at the same time—for example, all of the high scores in a game. The following program shows one way of using a list. 1 Create a list 2 Using your list Start a new project. Go into the This script asks the user to type words into a “Data” section of the blocks palette and click the “Make a List” button. Give your list list. Each word appears in the sprite’s speech bubble the name “sentence”. as it is added to the list. This block makes sure the list is empty at the start when clicked of the program Make a Variable Select “Make delete all ▾ of sentence ▾ The “ask” block asks the Make a List a List” forever user to type in a word sentence ask Add a word and wait Call your list This adds the add answer to sentence ▾ “sentence” user’s answer think sentence for 2 secs to the list Adding “sentence” here means The “think” block that the list will be shown in the makes a thought thought bubble bubble appear 3 Seeing the list EXPERT TIPS If you check the box beside the list in the blocks palette, the list is shown on the Playing with lists stage. You can see each new word as it’s added to the list. These blocks can be used to change the contents of a list. Each item in a list has a number—the first item is number 1, sentence and so on. These numbers can be used to remove, insert, 1 apple or replace items. 2 pear 3 banana Deletes the first 4 orange item in the list length: 4 delete 1 ▾ of sentence ▾ Adds “cherry” as the first item in the list Scratch keeps track insert cherry at 1 ▾ of sentence ▾ Replaces the of how replace item 1 ▾ of sentence ▾ with cherry first list item many words with “cherry” are added to the list
56 S T A R T I N G F R O M S C R A T C H SEE ALSO Coordinates 38–39 Making To put a sprite in a particular spot, or to find out its things move exact location, you can use coordinates. Coordinates are a pair of numbers that pinpoint a sprite’s position 52–53 Math on the stage using an x and y grid. x and y positions x: 240 y: 180 The x and y positions of a sprite and the △ Position of the mouse-pointer mouse-pointer are shown on the Scratch The mouse-pointer’s coordinates are shown at the interface. It can be helpful to know a bottom right of the stage. Move the mouse-pointer sprite’s coordinates when writing a script. over the stage and watch the coordinates change. ◁ Position of a sprite x position ◁ Show coordinates y position on the stage You can see a sprite’s Check the boxes beside the current coordinates in the “x position” and “y position” blocks to show a sprite’s top right corner of position on the stage. the scripts area. x: -126 y: 96 x and y grid Untitled To pinpoint a spot, count the number of by abcd (unshared) steps left or right, and up or down, from the middle of the stage. Steps to the left 180 or right are called “x”. Steps up or down are y called “y”. Use negative numbers to move left and down. 120 The stage is based (x: –100, y: 100) 60 upon an x and y grid –180 –120 –60 (x: 180, y: 50) This sprite is 190 steps left (–190) –60 60 120 180 x and 150 steps down (–150) from –120 (x: 90, y: –130) the middle of the stage (x: –190, y: –150) –180
C O O R D I N AT E S 57 Moving the sprite -x +y Positive numbers Coordinates are used to move a sprite to a particular move sprites up spot on the stage. It doesn’t matter how near or far and right, negative away the spot is. The “glide 1 secs to x:0 y:0” block from numbers move the “Motion” section of the blocks palette makes the them down and left sprite glide there smoothly. +x when clicked Change the coordinate -y Moves to the numbers to make the sprite middle of the stage go somewhere else set x to 0 glide 1 secs to x: 150 y: 100 Moves the sprite left glide 1 secs to x: -150 y: -100 change x by -10 glide 1 secs to x: -200 y: 100 glide 1 secs to x: 0 y: 0 change y by 125 set y to 180 △ Control the sprite with a script △ Change x and y separately Moves up Can you work out the path the sprite These blocks can be used to change to the top will take when you run this script? x without changing y, and the other of the stage Try it and see! way around. Crazy horse’s trip Try this fun script to test out coordinates. Select the “Horse1” sprite from the sprite list and give it the below script. This program uses the “go to x:0 y:0” block to keep moving the horse to a random position, drawing a line behind it as it goes. when clicked pen down This block leaves a line when the horse moves forever go to x: pick random -240 to 240 y: pick random -180 to 180 wait 0.2 secs This block from the “Operators” menu Selects a random selects a random horizontal position vertical position
58 S T A R T I N G F R O M S C R A T C H SEE ALSO Make some noise! Sensing 66–67 Scratch programs don’t have to be silent. Use the pink and detecting “Sound” blocks to try out sound effects and create music. You can also use sound files you already have or record Monkey 74–81 brand new sounds for your program. mayhem Adding sounds to sprites Click the “Sounds” tab to show the sound To play a sound, it must be added to a option buttons sprite. Each sprite has its own set of sounds. To control them, click the “Sounds” tab Scripts Costumes Sounds above the blocks palette. New sound: Click here to select a sound effect from Scratch’s library Record a sound using Upload a recording the computer’s from the computer microphone Playing a sound Turn up the volume There are two blocks that play sounds: “play Each sprite has its own volume control, sound” and “play sound until done.” Until which is set using numbers. 0 is silent done” makes the program wait until the and 100 is the loudest. sound has finished before it moves on. 100 is the maximum volume Use the menu to choose which sound to play set volume to 100 % play sound meow ▾ This block makes a sprite louder or quieter—use a negative play sound meow ▾ until done number to make it quieter The next block in the script will change volume by -10 not run until after the meow sound has finished playing Ticking this box makes volume the sprite’s volume show on the stage
MAKE SOME NOISE! 59 Making your own music Scratch has blocks that can be used to invent musical sounds. You have a whole orchestra of instruments to conduct, as well as a full drum kit. The length of each note is measured in beats. This decides how low or high the pitch of a note is play note 60 ▾ for 0.5 beats set instrument to 1 ▾ Big numbers make a note Click here to choose longer. It can also be shorter an instrument from a than a beat, as shown here drop-down menu play drum 1 ▾ for 0.25 beats rest for 0.25 beats Use this menu to choose between This block adds a silent break in the different types of drum music. Higher numbers will give you a longer break Playing music EXPERT TIPS Connecting notes together makes a tune. Create a new Tempo variable called “note” (see pages 50–51), and then add the script below to any sprite to create a piece of music. The speed of music is called its tempo. The tempo decides how when clicked Set the value of the long a beat is within a piece of variable “note” first music. There are three blocks for managing the tempo. set note ▾ to 1 Choose an instrument set instrument to 1▾ set tempo to 60 bpm forever Add a “forever” loop around these The tempo is measured in beats per change note ▾ by 1 two blocks minute, or “bpm.” play note note for 0.5 beats change tempo by 60 △ Rising scale Drag the “note” variable Increase the tempo to make your from the “Data” section music faster, or use a negative number of the blocks palette to make it slower. This script makes a series of notes that play when the green tempo flag is clicked. The pitch of each note gets higher one step Checking this box makes the sprite’s tempo show on the stage. at a time, and each note plays for half a beat.
60 S T A R T I N G F R O M S C R A T C H PROJECT 2 Roll the dice SEE ALSO Simple programs can be both useful and fun. 40–41 Costumes This program creates a dice that can be rolled. 46–47 Simple loops Play it to see who can get the highest number, 50–51 Variables or use it instead of a real dice when you play 52–53 Math a board game. How to create a rolling dice The dice in this program uses six costumes. Each costume shows a face of the dice with a different number on it— from one to six. Select the paintbrush button Click the rectangle button on the left of the 1 under the stage to draw a 2 painting area. To make your dice colorful, select a new sprite. solid color from the palette (see box below). Then in the painting area hold down the “shift” key, New sprite: press the left mouse button, and then drag the mouse-pointer to make a square in the middle. Draws a new sprite The rectangle button makes a square when EXPERT TIPS the “shift” key is pressed Changing colors Under the painting area are the Click for outline Click for block Currently color controls. Click the solid selected color rectangle to draw a block of of block of solid color solid color. Click the empty rectangle to draw an outline of a square or rectangle. Use the slider to change the thickness of the square’s lines. To choose a color, simply click it. Change the line Click on Choose a Use this to select width using the slider this box for color from the a color already more colors on the drawing color palette
ROLL THE DICE 61 Right-click on your costume to the left of the painting area, and EXPERT TIPS 3 choose “duplicate”. Repeat this step until you have six costumes. Rotation tool 1 Use the menu To make the dice appear to roll to duplicate the when the script is run, you can duplicate dice costume rotate each costume to a different angle. Click on the “Convert to costume1 delete vector” button in the bottom 123x123 save to local file right-hand corner. When you click back on to the painting area, a Select a costume. Click the circle button rotation tool will appear. 4 on the painting area and choose a solid Click and drag white color from the palette. Add spots this control to rotate the dice to each of the six costumes until you have made all six sides of a dice. The circle button makes a “costume5” perfect circle when the has 5 spots “shift” key is pressed Add the script below to the dice sprite. Press 5 the spacebar to roll the dice. Try it a few times to check that you can see all of the costumes. when space ▾ key pressed Clicking the spacebar rolls the dice switch costume to pick random 1 to 6 Sometimes you’ll roll the same number twice, and it looks like This block selects a random costume 6 the program isn’t working because the image doesn’t change. This script makes the dice change costumes five times before it stops. Each time you press the spacebar, it looks like it’s rolling. when space ▾ key pressed Each costume is a repeat 5 different dice number switch costume to pick random 1 to 6 wait 0.2 secs Add a short pause to Don’t forget to save see the dice rolling your work
62 S T A R T I N G F R O M S C R A T C H SEE ALSO True or false? Decisions and 64–65 branches Computers decide what to do by asking questions Making 118–119 and determining whether the answers are true or false. decisions Questions that only have two possible answers are called “Boolean expressions”. Comparing numbers = ◁ The “=” block This block will give one of two answers: You can compare numbers using the “true” if the two numbers in the boxes “=” block from the “Operators” section are equal, and “false” if they aren’t. of the blocks palette. The numbers are true These numbers false equal, so “true” are not equal, so appears in the “false” appears in speech bubble the speech bubble say 3 = 3 say 3 = 2 △ True answer △ False answer Using an “=” block inside a speech block will make If the numbers in the block are different, the sprite’s “true” or “false” appear in a sprite’s speech bubble. speech bubble will contain the word “false”. Comparing variables age = 7 This sign means “equals”, so the age > 11 block is asking if “age” is equal You can use variables inside to 7. The answer here is “false”, comparison blocks. It’s not worth because “age” is 10 comparing fixed numbers because the result will always be This sign means “more than”, the same, whereas the value of so the block is asking if “age” is variables can change. greater than 11. The answer is “false”, because 10 is not bigger than 11 set age ▾ to 10 age < 18 This sign means “less than”, so the block is asking if “age” is less than △ Create a variable 18. The answer will be “true”, as 10 Click the “Data” button in the blocks is smaller than 18 palette and create a new variable called “age”. Set its value to 10 (click on the △ Comparing numbers block to make sure the value has Find the green comparison blocks in the “Operators” menu. changed). Drag the “age” variable into As well as checking whether two numbers are equal, you can the comparison blocks. check whether one is greater or less than another.
TRUE OR FALSE? 63 EXPERT TIPS Comparing words The “=” block is not just used for numbers; The variable “name” it can also be used to check whether two contains “Lizzie”, so the strings are the same. It ignores capital answer is true letters when comparing strings. name = Lizzie set name ▾ to Lizzie Drag and drop the The answer is false variable into the because the variable △ Create a variable doesn’t contain “Dan” To experiment with comparing strings, comparison block create a new variable called “name” and = Dan set its value to “Lizzie”. name Not! not ◁ The “not” block The “not” block changes the The “not” block can simplify things by reversing answer around, from true to the answer of a Boolean expression. For example, false and from false to true. it’s easier to check if someone’s age is not 10 than to check every other possible age. age = 7 not age = 7 △ Without the “not” block △ With the “not” block Here, 10 isn’t equal to 7, so the Adding the “not” block to the same question changes the answer is false. answer. Because 7 does not equal 10, the answer is now true. Combining questions or To ask more complicated questions, you can combine and comparison blocks and ask more than one question at the same time. △ Comparison blocks The “or” and “and” blocks are used age < 18 or age > 65 to combine Boolean expressions in different ways. Here, the answer is true The answer here is only when either the left or true when both the left ◁ In practice and right sides are true The top block checks whether the right side is true someone is younger than 18 or older and age < 15 than 65. The bottom block checks if age > 10 they are aged 11, 12, 13, or 14.
64 S T A R T I N G F R O M S C R A T C H Decisions and branches SEE ALSO Tests of whether something is true or false can be 62–63 True used to tell the computer what to do next. It will perform a different action depending on whether or false? the answer is true or false. Sensing and 66–67 detecting Drag a Boolean if then expression into Making decisions this window The “if” blocks use Boolean if then else expressions to decide what to do next. To use them, put other △ “if-then” block If false, blocks in the blocks inside their “jaws”. The If a Boolean expression is “else” jaws will run blocks inside the “if” blocks will true, the blocks between the only run if the answer to the “if-then” block’s jaws will run. △ “if-then-else” block Boolean expression is true. If the Boolean expression is true, the first set of blocks runs. If not, the second set runs. Using the “if-then” block The “if-then” block lets you choose whether or not to run part of a script depending on the answer to a Boolean expression. Attach this script to the cat sprite to try it out. when clicked Drag the “=” block from the Is answer yes? “Operators” section into the True False ask Do you want me to meow? and wait “if-then” block. Then put the “answer” variable (from the if answer = yes then “Sensing” section) inside it play sound meow ▾ until done This block is inside the jaws of the “if-then” block, so the cat will only meow if the Play Skip answer is true (“yes”) meow meow think hmm for 2 secs This is the end of the △ How it works “if-then” block think Time to eat some fish! for 2 secs The program checks These “think” blocks are whether the Boolean △ Meowing cat outside the “if-then” expression is true. If it is, This program checks the Boolean expression and will only loop, so they will run it runs the blocks inside run the part between the “if-then” block’s jaws if it is true. whatever the answer the “if-then” block’s jaws. This means that the cat only meows when you tell it to. to the question is
DECISIONS AND BRANCHES 65 Branching instructions Is answer yes? Often you want a program to do one thing if a condition is true, and something else if it is not. The “if-then-else” block gives a program two possible routes, called “branches”. Only one branch will run, depending on the answer to the Boolean expression. ▽ Branching program True False This program has two branches: one when clicked will run if the answer is “yes”, and the other will run if it is not. ask Do you like me? and wait if answer = yes then say say “I like “That’s not say I like you too! for 2 secs This branch will run you too!” very friendly!” else if the answer to the question is “yes” say That’s not very friendly! for 2 secs △ How it works The program checks whether you typed in “yes”. If so, it shows the first message. If not, it shows the second. EXPERT TIPS This branch will run if the answer to the question is Boolean shapes anything except “yes” The Boolean expression blocks in Scratch have pointed ends. You can put them into some nonpointed shaped holes too. mouse down? △ ”Sensing” blocks These blocks can test whether a sprite is touching another sprite, or whether a button is pressed. repeat until △ ”Control” blocks ▷ Branches Several “Control” blocks have Boolean-shaped Like the branches of a tree, holes in them for Boolean expressions. branches of a program split and go in different directions.
66 S T A R T I N G F R O M S C R A T C H Sensing and detecting SEE ALSO 40–41 Costumes The “Sensing” blocks enable a script to see what is 56–57 Coordinates happening on your computer. They can detect keyboard controls, and let sprites react when they touch each other. This block checks if a key is being pressed. You can choose Keyboard controls which key to check for Using “Sensing” blocks with “if-then” blocks allows you key space ▾ pressed? to move a sprite around the screen using the keyboard. This block checks if the mouse The “key pressed?” block has a menu of most of the button is being pressed keys on the keyboard, so a sprite can be programmed mouse down? to react to any key. You can also link actions to the click of a mouse button. △ “Sensing” blocks Adding these blocks into an “if-then” block when clicked Putting everything inside a allows the program to detect if a mouse “forever” block means the button or key is being pressed. script repeatedly checks for key presses forever key up arrow ▾ pressed? then The script checks to see if the up if arrow is pressed. If it is, the sprite moves upwards on the screen change y by 10 if key down arrow ▾ pressed? then change y by -10 if key left arrow ▾ pressed? then △ Controlling sprites change x by -10 then Keyboard controls give you precise control over your if key right arrow ▾ pressed? sprites, which is especially change x by 10 useful in games. ◁ Movement script This script lets you move sprites up, down, left, or right using the arrow keys on the keyboard.
SENSING AND DETECTING 67 Sprite collisions Use this block to identify when a sprite touches another sprite It can be useful to know when one sprite touches another—in touching frog ▾ ? games, for example. Use “Sensing” blocks to make things happen This block senses when a when sprites touch each other, or sprite touches an area of when a sprite crosses an area that a particular color is a certain color. touching color ? Using “Sensing” blocks Use the “Sensing” blocks to turn your controllable cat into a game. Start by adding the movement script created on the opposite page to the cat sprite, then add the “room1” backdrop and the elephant sprite. Using the “Sounds” tab, add the “trumpet2” sound effect to the elephant, then build it the script below. ▽ Find the elephant This script uses “Sensing” blocks to control the relationship between the cat and the elephant. As the cat gets nearer, the elephant grows. When the cat touches it, the elephant switches costume, makes a sound, and hides somewhere else. when clicked The “forever” loop keeps This checks how far the forever sensing and adjusting the cat is from the elephant elephant’s size and position set size to 200 – distance to Sprite1 ▾ % if touching Sprite1 ▾ ? then The farther away the switch costume to elephant-b ▾ cat is, the smaller the play sound trumpet2 ▾ until done elephant will be switch costume to elephant-a ▾ If the sprites touch, the blocks inside the “if-then” block run go to x: pick random -240 to 240 y: pick random -180 to 180 This block selects a random place for the elephant to hide
68 S T A R T I N G F R O M S C R A T C H Complex loops SEE ALSO Simple loops are used to repeat parts of a program 46–47 Simple forever, or a certain number of times. Other, cleverer loops can be used to write programs that decide loops exactly when to repeat instructions. 62–63 True or false? Looping until something happens repeat until Add the “Dog1” sprite to a project, and then give the △ “Repeat until” block below script to the cat sprite. When you run the script, the The blocks inside the “repeat “repeat until” block makes sure the cat keeps moving until until” block keep repeating until it touches the dog. It will then stop and say “Ouch!” the condition is true (the cat touches the dog). This block stops the cat from standing on its head when clicked set rotation style left-right ▾ Select “Dog1” from the drop-down menu repeat until touching Dog1 ▾ ? move 10 steps Ouch! if on edge, bounce These instructions keep on repeating until the cat touches the dog say Ouch! This will only happen when △ Testing the program the cat touches the dog Move the dog out of the cat’s way and run the program. Then drag and drop the dog into the cat’s path to see what happens. Stop! This stops all scripts This stops only the script in a program this block is in Another useful “Control” block is the “stop all” block, stop all ▾ This stops the sprite’s other which can stop scripts from all scripts, but continues to run running. It’s useful if you this script the script this block is in want to stop sprites from other scripts in sprite moving at the end of a game. ◁ Stopping scripts Use the drop-down menu to choose which scripts to stop.
COMPLEX LOOPS 69 Waiting wait 1 secs ◁ Waiting blocks wait until It’s easier to play a game or see what’s The “wait secs” block waits going on in a program if you can make a a set amount of time. The script pause for a moment. Different “wait until” block responds blocks can make a script wait a number to what’s happening in of seconds or until something is true. the program. Sprite waits 5 seconds when clicked Sprite waits until and then says something the mouse button is pressed forever As soon as the when clicked condition is true, the sprite moves to the wait until mouse down? mouse-pointer wait 5 secs say I’m tired of waiting go to mouse-pointer ▾ △ ”wait secs” block △ ”wait until” block With the “wait secs” block you can This block waits until the Boolean enter the number of seconds you expression in it is true. want a sprite to wait. Magnetic mouse when clicked The script repeats until the forever mouse button is released Different loops can be used together to make programs. The “not” block detects This program starts once when the mouse button the mouse button is pressed. The sprite follows is not being pressed the mouse-pointer until the mouse button is released. It wait until mouse down? then jumps up and down five times. The whole thing then repeat until not mouse down? repeats itself because it’s all inside a “forever” loop. go to mouse-pointer ▾ ▷ Nested loops repeat 5 This makes the Pay careful attention to how change y by 20 sprite jump up the loops are nested inside wait 0.25 secs the “forever” block. change y by -20 This makes the wait 0.5 secs sprite drop down The “repeat 5” block makes the sprite jump up and down five times
70 S T A R T I N G F R O M S C R A T C H Sending messages SEE ALSO Sometimes it’s useful for sprites to communicate 38–39 Making with each other. Sprites can use messages to tell other sprites what to do. Scratch also lets you things move create conversations between sprites. 40–41 Costumes 44–45 Events This “Events” block lets a sprite send a message to all the other sprites Broadcasting broadcast message1 ▾ The broadcast blocks in the “Events” menu This block starts a script when enable sprites to send and receive messages. a sprite receives a message Messages don’t contain any information other than a name, but can be used to fine-tune a when I receive message1 ▾ sprite’s actions. Sprites only react to messages that they are programmed to respond to— △ Broadcast blocks they ignore any other messages. One type of broadcast block lets a sprite send a message. The other tells the sprite to receive a message. Choose an existing message or create a new one. This message starts the script that makes the starfish swim away from the shark when clicked when I receive shark_here ▾ switch costume to starfish-b ▾ forever glide 1 secs to x: 133 y: 91 show broadcast shark_here ▾ Choose “new message...” The starfish glides out of glide 5 secs to x: 150 y: -150 from the menu to create the shark’s way, showing this name its scared costume hide This message tells the broadcast shark_gone ▾ starfish that the shark is gone, so it’s safe to return glide 5 secs to x: -150 y: 150 when I receive shark_gone ▾ △ Shark danger switch costume to starfish-a ▾ Choose two sprites—a shark and a starfish. Give the shark glide 1 secs to x: 0 y: 0 the script above, and the starfish the two scripts on the right. When the shark arrives it sends a message, which The starfish glides back to the middle of makes the starfish swim away. the screen, showing its happy costume
SENDING MESSAGES 71 Conversations broadcast message1 ▾ and wait To create a conversation between sprites use △ Waiting blocks “broadcast message and wait” blocks with “say” This block sends a message, then waits for all the blocks, which make your sprites talk using scripts that react to the message to finish before speech bubbles. Start a new project and add the program continues. two monkey sprites to it. Give the script on the left to one monkey, and the two scripts on the right to the other. The first monkey Hello! starts the conversation Hi! when clicked “Say” blocks let your The second sprites talk using monkey responds say Hello! for 2 secs speech bubbles to the first one broadcast hello ▾ and wait The “hello” message triggers say How are you? for 2 secs the second monkey’s script when I receive hello ▾ say Hi! for 2 secs broadcast howareyou ▾ How are you? When the second when I receive howareyou ▾ script ends, the first say Great thanks! for 2 secs script continues The “howareyou” message starts the third script Great thanks! △ Chatty monkeys This program works because it uses the “broadcast message and wait” block. If the “broadcast message” block was used, the monkeys would talk over each other.
72 S T A R T I N G F R O M S C R A T C H Creating blocks SEE ALSO To avoid repeating the same set of blocks over and over 50–51 Variables again, it’s possible to take a shortcut by creating new blocks. Time to 82–83 Each new block can contain several different instructions. experiment Making your own block You can make your own blocks in Scratch that run a script when they’re used. Try this example to see how they work. Programmers call these reusable pieces of code “subprograms” or “functions”. 1 Create a new block 2 New block appears Click on the “More Blocks” button, Your new block “jump” appears and then select “Make a Block”. Type the in the blocks palette, and a “define” word “jump” and click “OK”. block appears in the scripts area. Scripts Costumes Sounds Make a Block jump Motion Events define jump Looks Control Sound Sensing The new block Define the “jump” Pen Operators block in the Data More Blocks scripts area Make a Block Click here to make a new block 3 Define the block 4 Use the block in a script The “define” block tells Scratch which The new block can now be used in blocks to run when using the new block. any script. It’s as if those jumping blocks Add this script to define the block. were in the script individually. define jump Starts your block when clicked definition change y by 50 forever The new block runs wait 1 secs the jumping script that change y by -50 Jumps up jump has already been defined Drops down wait 1 secs Waits 1 second before repeating the loop
CREATING BLOCKS 73 Blocks with inputs New Block Windows in a new block can be used to slide steps and shout greeting give it numbers and words to work with. These holes can be used to change ▾ Options text how far the block moves a sprite. Add number input: Click here to see Add string input: all of the options Add boolean input: Add label text: 1 Make a new block Make a new block called “slide” and then Run without screen refresh click on “Options”. Now select “Add number input” and type “steps”. Select “Add label text” OK Cancel and change it to “and shout”. Click “Add string input” and call it “greeting”. Then click “OK”. The greeting variable The steps variable 2 Define the block define slide steps and shout greeting In the “define” block, the holes are replaced with change x by steps Drag variables from variables called “steps” and the “define” block “greeting”. Drag these say greeting for 1 secs into the script variables from the “define” block into the script wherever change x by 0 – steps you need them. Add this script to your sprite. This block makes the number of steps negative 3 Use the block in a script Starts the script Use a sensible name Now add the below script to a sprite. when the spacebar for a new block so the By putting different numbers of steps and is pressed program will be easier greetings into the block, you can make to read and change. your sprite behave differently. The sprite slides 20 steps and when space ▾ key pressed shouts “hello” slide 20 and shout hello wait 1 secs Now the sprite slides slide 80 and shout how’s it going? 80 steps and shouts “how’s it going?”
74 S T A R T I N G F R O M S C R A T C H PROJECT 3 Monkey mayhem SEE ALSO This exciting, fast-paced game brings together all of the 40–41 Costumes Scratch skills you’ve learned so far. Follow these steps to 38–39 Making create your very own “Monkey mayhem” and see if you can hit the bat with the bananas! things move 66–67 Sensing and detecting Getting started EXPERT TIPS Start a new Scratch project. The cat sprite isn’t needed Avoiding errors for this project. To remove it, right-click on it in the sprite list and then click “delete” in the menu. This will This is the biggest Scratch leave you a blank project to work on. program you’ve tried so far, so you might find that the game doesn’t Add a new backdrop from the Stage always work as you expect it to. Here are some tips to help things 1 backdrop library. This button is 1 backdrop run smoothly: found to the left of the sprite list. New backdrop: Make sure you add scripts to the Click here to add a correct sprite. new backdrop from the backdrop library Follow the instructions carefully. Remember to make a variable before using it. Check that all the numbers in the blocks are correct. Double-click to select the “brick wall1” Monkey mayhem 2 backdrop. The brick wall works well for by abcd (unshared) this game, but if you prefer, you could use a different backdrop instead. Double-click on a backdrop in the backdrop library to make it appear on the stage
M O N K E Y M AYH E M 75 Go to the sprite library to Sprites New sprite: 3 add a new sprite to the Monkey1 Click here to choose a new sprite game. Select “Monkey1” from the library from the “Animals” section. The user will control this sprite in the game. Give the monkey the script below. Remember—all of the different 4 blocks can be found in the blocks palette, organized by color. In this script, “Sensing” blocks are used to move the monkey around the stage using the keyboard arrow keys. Run the script when you’ve finished to check it works. when clicked This “Motion” block keeps The arrow keys on the the monkey upright keyboard will make the set rotation style left-right ▾ monkey run left and right Moves the monkey to go to x: 0 y: -90 his start position at the This “Sensing” block detects when bottom of the stage the left arrow key is pressed forever if key left arrow ▾ pressed? then point in direction -90 ▾ –90 makes the monkey move 10 steps point to the left next costume This block makes the monkey look like it is walking by switching between its costumes if key right arrow ▾ pressed? then point in direction 90 ▾ 90 makes the monkey move 10 steps point to the right next costume Moves the monkey 10 steps Don’t forget to save your work
76 S T A R T I N G F R O M S C R A T C H MONKEY MAYHEM Adding more sprites The monkey can now be moved across the stage using the left and right arrow keys. To make the game more interesting, add some more sprites. Give the monkey some bananas to throw, and a bat to throw them at! when clicked This makes the Add the “Bananas” sprite from the sprite bananas stay upright 5 library, then give it this script. When the set rotation style left-right ▾ game starts, the monkey will be holding the bananas. When the spacebar is point in direction 0 ▾ Sets the bananas’ pressed, they will shoot vertically up direction to up the stage. The bananas then reappear at one side of the stage, where they can show This block makes the bananas be picked up again. forever visible on the stage—they’ll be hidden later The bananas will stick to the monkey until the repeat until key space ▾ pressed? spacebar is pressed go to Monkey1 ▾ repeat 35 This loop moves the move 10 steps bananas up the stage if pick random 1 to 2 =1 then go to x: 210 y: -140 This “if-then-else” block else makes the bananas reappear go to x: -210 y: -140 on either the right or left side of the stage, randomly show touching Monkey1 ▾ ? wait until This makes the script wait until the monkey picks up the bananas
M O N K E Y M AYH E M 77 The next step is to add a flying bat and make it drop New Variable Name the Variable name: Speed new variable 6 to the ground if it’s hit by the bananas. Add “Bat2” “Speed” For all sprites For this sprite only from the sprite library, then create a new variable This variable Cloud variable (stored on server) will only be called “Speed” (for the bat sprite only). To create a used with the bat sprite new variable, first click the “Data” button in the OK Cancel blocks palette, and then select the “Make a Variable” button. Untick the box by the “Speed” variable in the “Data” section so it doesn’t appear on the screen. Add the below script to the bat. In the main “forever” 7 loop, the bat moves to a random position on the left of the stage, chooses a random speed, then moves backward and forward across the stage until the bananas hit it. When the bat is hit, it drops to the ground. when clicked This keeps the bat sprite upright set rotation style left-right ▾ The bat starts off on the left of the stage, at a forever Start of the bat’s main loop random height go to x: -300 y: pick random 1 to 100 Picks a random speed point in direction 90 ▾ Sets the bat’s direction to right set Speed ▾ to pick random 1 to 20 repeat until touching Bananas ▾ ? move Speed steps This makes the bat keep moving until it’s hit Drag the “Speed” variable from the if on edge, bounce “Data” section into this block broadcast hitbybananas ▾ Create this “broadcast” block to tell point in direction 180 ▾ other sprites that the bat has been hit. repeat 40 This will be useful later in the project move 10 steps Sets the direction of the bat to down Makes the bat fall down and off the stage Don’t forget to save your work
78 S T A R T I N G F R O M S C R A T C H MONKEY MAYHEM The finishing touches Create a new variable called “Time”. Make sure it’s To make the game even more exciting, you 8 available for all sprites in the game by selecting the can add a timer, use a variable to keep score of how many bats the player hits, and add a “For all sprites” option. Check that the box next to game over screen that appears once the the variable in the blocks palette is ticked, so that player is out of time. players can see the time displayed on the stage. Time Click on the small picture of the T Monkey mayhem 9 stage in the stage list, then select by abcd (unshared) the “Backdrops” tab above the GAME OVER blocks palette. Right-click the existing backdrop and duplicate it. Add the words “GAME OVER” to the new backdrop. Use the text tool to write on the duplicate backdrop Your “game over” screen will look something like this Click the “Scripts” tab and when clicked 10 add this script to the stage switch backdrop to brick wall1 ▾ This sets the time limit to 30 seconds to set up the timer. When set Time ▾ to 30 the timer begins, it starts a Counts down until the count-down loop. When repeat until Time =0 timer reaches zero the loop finishes, the “GAME OVER” screen is shown and the game ends. wait 1 secs change Time ▾ by -1 Ends the game switch backdrop to brick wall2 ▾ Switches to the “GAME stop all ▾ OVER” backdrop
M O N K E Y M AYH E M 79 Click the bananas sprite in Put a check in the box to show the 11 the sprite list. Create a new score on the stage variable called “Score” and Score make it available for all sprites. Move the score to the top right of the stage by dragging it. Add this short script to the bananas sprite. Add this script to the bananas sprite too. When the 12 It sets the score to 0 at the beginning 13 bananas hit the bat, it plays a sound, increases the of the game. score by 10, and hides the bananas. when clicked Makes the when I receive hitbybananas ▾ bananas disappear set Score ▾ to 0 hide Add the “pop” sound play sound pop ▾ from the sound library This resets the score to the banana sprite (see pp.58–59) change Score ▾ by 10 Next add some music to the 2 Each time the bat is hit the player 14 game. Click on the stage and scores 10 points select the “Sounds” tab above the REMEMBER blocks palette. Load the “eggs” Achievements music from the sound library. Congratulations—you’ve built a complete Scratch game. Here eggs are some of the things you have 00:15.2 achieved so far: Add the “eggs” music Made a sprite throw objects at from the “Sounds” tab another sprite. Made a sprite fall off the stage Add the script below to the stage. It plays the once hit. Added a time limit to your game. 15 “eggs” music on a loop, but will stop when the Added background music that plays “stop all” block ends the game. as long as the game continues. Added a game over screen that when clicked The background appears at the end of the game. forever music is repeated in an endless loop play sound eggs ▾ until done Don’t forget to save your work
80 S T A R T I N G F R O M S C R A T C H MONKEY MAYHEM Time to play Make up a new To make the game last title for the game longer, try increasing Now the game is ready to play. Click the the time limit green flag to start and see how many and type it in times you can hit the bat with the bananas before the time runs out. Untitled by abcd (unshared) Left cursor key Right cursor key Time 30 Spacebar Space △ Controls To make the Steer the monkey left and right with game harder, the keyboard cursor keys. Tap the make the bat spacebar to fire bananas at the bat. move faster EXPERT TIPS Adding more sprites To add more bats to aim at, right-click the bat in the sprite list and select “duplicate”. A new bat will appear with all the same scripts as the first one. Try adding some other flying sprites: 1. Add a sprite from the sprite library. The flying hippo (“Hippo1”) is great for this game. 2. Click on the bat in the sprite list. 3. Click the bat’s script and hold the mouse button down. 4. Drag the bat’s script on to the new sprite in the sprite list. 5. The script will copy across to the new sprite.
M O N K E Y M AYH E M 81 Try out different Play the game three backdrops and see times and see how high how the game looks you can score Score 0 Click the red stop button to end the game early You can edit the program to give the player more points for each successful hit To make the game harder, try changing the code to make the bananas move more slowly Try changing the monkey into a different sprite ◁ Going bananas There are countless ways to change Monkey Mayhem. By adjusting the speeds, scores, sounds, and sprites, you can create your own unique version of the game.
82 S T A R T I N G F R O M S C R A T C H SEE ALSO Time to experiment What is 86–87 Now you’ve learned the basics of Scratch, you can Python? experiment with some of its more advanced features. The more you practice, the better your coding will become. Simple 102–103 commands Things to try ◁ Join a coding club Is there a coding club in Not sure what to do next with your school or local area? Scratch? Here are a few ideas. They’re great places to If you don’t feel ready to write meet other Scratch users a whole program on your own and share ideas. yet, you can start with one that has already been written and change parts of it. Scratch allows you to look at the coding of all projects on its website △ Look at code ▷ Remix existing projects Looking at other programs is a great Can you improve the projects on way to learn. Go through projects the Scratch website? Scratch lets shared on the Scratch website. What you add new features and then can you learn from them? share your version. Backpack Drag and drop when clicked to copy a script The backpack enables you to store useful or sprite into the forever scripts, sprites, sounds, and costumes and move them from project to project. It’s backpack say hello! found at the bottom of the Scratch screen. Backpack move 10 steps ▷ Drag and drop A sprite in the Sprite 1 You can drag sprites and scripts into backpack your backpack, then add them to other projects.
TIME TO EXPERIMENT 83 Help! Tips degrees It can be hard to write a program if you turn don’t know about some of the blocks you Turn left could use. Scratch has a help menu to make sure you understand every block. 1 Block help To find out more about a particular block, click the “block help” button on the when left arrow ▾ key pressed turn 30 degrees cursor tools bar at the top of the screen. 30° The help ? window explains every block This is the “block help“ button 2 Ask a question The cursor The cursor will turn into a becomes a question mark. Use this to click on question mark the block you want to know about. ? turn 15 degrees Type in the number of degrees you want the 3 Help window sprite to rotate. The help window opens to tell you how the block works, with (If you type in a negative number, the sprite will tips on how it can be used. go in the opposite direction.) Learn another language You’re now on your way to mastering your first programming language. Learning other languages will enable you to write different types of programs. Why not try Python next? What you’ve already learned about Scratch will help you pick up Python quickly. ▷ Similar to Scratch Python uses loops, variables, and branches too. Use your Scratch knowledge to start learning Python!
Playing with Python
86 P L A Y I N G W I T H P Y T H O N What is Python? SEE ALSO Python is a text-based programming language. Installing 88–91 It takes a bit longer to learn than Scratch, but can Python be used to do much more. Simple 102–103 A useful language commands Python is a versatile language that can be used to make many different types of programs, from word Harder 104–105 processing to web browsers. Here are a few great reasons to learn Python. commands 1 Easy to learn and use 2 Contains ready-to-use code Python programs are written in a Python contains libraries of simple language. The code is quite easy to preprogrammed code that you can read and write, compared to many other use in your programs. It makes it easier programming languages. to write complex programs quickly. 3 Useful for big organizations Python contains Python is powerful. It can be used lots of programs to write real-world programs. It is used by you can use and Google, NASA, and Pixar, among others. build on EXPERT TIPS Getting started Before learning how to program in Python, it’s useful to get familiar with how it works. The next few pages will teach you how to: Install Python: Python is free, but you’ll have to install it yourself (see pp.88–91). Use the interface: Make a simple program and save it on the computer. Experiment: Try some simple programs to see how they work.
WHAT IS PYTHON? 87 Scratch and Python Lots of elements that are used in Scratch are also used in Python—they just look different. Here are a few similarities between the two languages. when clicked print(‘Hello World!’) say Hello World! Type the message you want here This block displays the message in a The message appears speech bubble on screen like this Hello World! Hello World! △ Print in Python △ Print in Scratch In Scratch, the “say” block is used to show In Python, a command called “print” displays something on the screen. text on the screen. Turns the pen on pen down Repeats the blocks from turtle import * repeat 24 inside it 24 times to draw a circle pendown() This starts a loop move 10 steps Moves the sprite for n in range(24): turn 15 degrees forward forward(10) Turns the sprite right(15) Turns the penup() turtle clockwise 15 degrees pen up Turns the pen off △ Turtle graphics in Scratch △ Turtle graphics in Python The script above uses the “pen down” block There’s also a turtle in Python. The code above to move the cat sprite and draw a circle. can be used to draw a circle.
88 P L A Y I N G W I T H P Y T H O N Installing Python Before you can use the Python programming language, you need to download and install it on your computer. Python 3 is free, easy to install, and works on Windows PCs, Macs, and Linux operating systems such as Ubuntu. What is IDLE? EXPERT TIPS When you install Python 3, you’ll also get a free program Saving code called IDLE (Integrated DeveLopment Environment). Designed for beginners, IDLE includes a basic text editor When saving work in Python, you that allows you to write and edit Python code. will need to use the “File > Save As...” menu command so you can WINDOWS name your files. First create a folder to keep all your files in. Give △ Windows the folder a clear name, like Before you download Python, check “PythonCode”, and agree with the what kind of operating system your person who owns the computer computer has. If you have Windows, where to keep it. find out whether it’s the 32-bit or 64-bit version. Click the “Start” button, right-click “Computer”, and left-click “Properties”. Then choose “System” if the option appears. MAC UBUNTU △ Mac △ Ubuntu If you use an Apple Mac, find out which Ubuntu is a free operating system that operating system it has before you install works just like Windows and Macs. To Python. Click the apple icon in the top find out how to install Python on left and choose “About This Mac”. Ubuntu, turn to page 91.
INSTALLING PYTHON 89 Python 3 on Windows Before you install Python 3 on a Windows PC, make sure you get permission from the computer’s owner. You may also need to ask the owner to provide an admin password during installation. 1 Go to the Python website 2 Download Python Type the address below into your Internet Click on the latest version of Python for browser to open the Python website. Click on Windows, beginning with the number 3, which “Download” to open the download page. will be near the top of the list. http://www.python.org • Python 3.3.3 Windows x86 MSI Installer • Python 3.3.3 Windows x86-64 MSI Installer This is the URL (web Choose this if Don’t worry about Choose this if address) for Python you have a 32-bit the exact number, you have a 64-bit version of Windows as long as it has a version of Windows 3 at the front 3 Install 4 Run IDLE The installer file will download automatically. Now check that the program installed When it finishes, double-click it to install Python. correctly. Open the Windows “Start” menu, click on Choose “install for all users” and click “next” at each “All Programs”, “Python”, and then choose “IDLE”. prompt, without changing the default settings. Python 3.3 Make sure you IDLE (Python GUI) select Python 3 Module Docs Python (command line) The Windows installer Python Manuals icon appears while Uninstall Python Python is installing 5 A Python window opens A window like the one below should open up. You can now start coding – just type into the window after the angle brackets (>>>). IDLE File Edit Shell Debug Window Help Untitled Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)] on win32 Type “copyright”, “credits” or “license()” for more information. >>> Begin typing code here
90 P L A Y I N G W I T H P Y T H O N Python 3 on a Mac Before you install Python 3 on a Mac, make sure you get permission from the computer’s owner. You may also need to ask the owner to provide an admin password during installation. 1 Go to the Python link 2 Download Python Type the address below into your web Check which operating system your Mac has browser to open the Python website. Click on “Download” in the navigation panel to go to (see page 88) and click on the matching version of the download page. Python 3. You’ll be prompted to save a .dmg file. This version is Save it on your Mac desktop. for newer Macs http://www.python.org • Python 3.3.3 Mac OS X 64-bit... (for Mac OS X 10.6 and later) Don’t worry about the • Python 3.3.3 Mac OS X 32-bit... (for Mac OS X 10.5 and later) exact number, as long as This version runs it has a 3 at the front on most Macs 3 Install 4 Run IDLE Double-click the .dmg file. A window During installation, click “next” at each prompt to will open with several files in it, including accept the default settings. After installation ends, open the Python installer file “Python.mpkg”. the “Applications” folder on your Mac and open the “Python” Double-click it to start the installation. folder (make sure you select Python 3, not Python 2). Double-click “IDLE” to check the installation worked. IDLE icon Python installer file Python.mpkg 5 A Python window opens A window like the one below should open. You can now start coding—just type into the window after the angle brackets. IDLE File Edit Shell Debug Window Help Untitled Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type “copyright”, “credits” or “license()” for more information. >>>
INSTALLING PYTHON 91 Python 3 on Ubuntu If you use the Linux operating system Ubuntu, you can download Python 3 without having to use a browser—just follow the steps below. If you have a different version of Linux, ask the computer’s owner to install Python 3 for you. 1 Go to Ubuntu Software Center 2 Enter “Python” into the search bar Find the Ubuntu Software You will see a search box in the Centre icon in the Dock or the Dash top right. Type “Python” in the box and and double-click it. press enter. 3 Select IDLE and click “Install” Python Look for “IDLE (using Python)”. Highlight the version beginning with Look for version 3 the number 3 and click “Install”. IDLE (using Python-3.3) (17) Integrated Development Environment for Python (using Python-3.3) More info Install 4 Select Dash 5 Run IDLE After installation finishes, check Enter “IDLE” into the search the program works. First, select the bar and double-click on the Dash icon in the top right. blue-and-yellow “IDLE (using Python 3)” icon. Dash icon IDLE icon 6 A Python window opens A window like the one below should open. You can now start coding—just type into the window after the angle brackets. IDLE File Edit Shell Debug Window Help Untitled Python 3.2.3 (default, Sep 25 2013, 18:25:56) [GCC 4.6.3] on linux2 Type “copyright”, “credits” or “license()” for more information. >>>
92 P L A Y I N G W I T H P Y T H O N SEE ALSO Introducing IDLE 88–91 Installing IDLE helps you write and run programs in Python. Python See how it works by creating this simple program that writes a message on the screen. Which 106–107 window? Working in IDLE EXPERT TIPS Follow these steps to make a Python Different windows program using IDLE. It will teach you how to enter, save, and run programs. Python uses two different windows—the “shell” window and the “code” window (see pages 1 Start IDLE 106–107). We’ve given them different colors Start up IDLE using the instructions for your to tell them apart. computer’s operating system (see pp.88–91). The shell window opens. This window shows the Shell window program output (any information the program produces) and any errors. Code window IDLE File Edit Shell Debug Window Help Untitled Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type “copyright”, “credits” or “license()” for more information. >>> Messages from What appears here will Python appear here depend on which operating system you’re using 2 Open a new window IDLE File Edit Shell Debug Window Help Click the “File” menu Untitle New Window at the top of the shell Click here to open This is the window and select “New Open the code window shell window Window”. This opens the Open Module code window. Recent Files Class Browser Path Browser
INTRODUCING IDLE 93 3 Enter the code print(‘Hello World!’) In the new code window, type in this text. It’s an instruction to write the Use single words “Hello World!” quote marks 4 Save the code window IDLE File Edit Shell Debug Window Help Click the “File” menu and select Untitle New Window “Save As”. Enter the file name “HelloWorld” Click here to and click “Save”. prin Open save the file If you get an error message, Open Module check your code carefully Recent Files to make sure you haven’t Class Browser Path Browser made any mistakes. Close Save Save As Save Copy As 5 Run the program IDLE File Edit Format Run Window Help In the code window, click the “Run” HelloWorld Python Shell menu and select “Run Module”. This will Check Module run the program in the shell window. print(‘Hello World!’) Run Module Click here to run the program 6 Output in the shell window REMEMBER Look at the shell window. The “Hello World!” message should appear when the How IDLE works program runs. You’ve now created your first bit of code in Python! Always follow these three steps in IDLE: write the code, save it, and then run it. Remember, code that hasn’t been saved won’t >>> run. A warning will come up if you try. Hello World! >>> Enter code Save Run The message will appear without quote marks
94 P L A Y I N G W I T H P Y T H O N SEE ALSO Errors Bugs and 148–149 Sometimes programs don’t work the first time, but debugging they can always be fixed. When code for a program isn’t entered correctly, Python will display an error What next? 176–177 message telling you what has gone wrong. Errors in the code window When trying to run a program in the code window, you might see a pop-up window appear with an error message (such as “SyntaxError”) in it. These errors stop the program from running and need to be fixed. 1 Syntax error 2 Error highlighted If a pop-up window appears with Click “OK” in the pop-up window and a “SyntaxError” message, it often means you’ll go back to your program. There will there’s a spelling mistake or typing be a red highlight on or near the error. error in the code. Check that line for mistakes carefully. SyntaxError print(‘Hello World!) invalid syntax There is a missing The error is quote mark here highlighted OK There is a EXPERT TIPS SyntaxError typing error in the code Classic errors unexpected indent Some mistakes are particularly easy to make. Keep an eye out for these common problems: OK Upper vs lower case: The case has to match exactly. If you write “Print” instead of “print”, Python won’t There is incorrect understand the instruction. spacing in the code, which is preventing the Single and double quotes: Don’t mix up single and program from running double quotes. All opening quotes need a matching closing quote. Minus and underscore: Don’t confuse the minus sign (-) with the underscore sign (_). Different brackets: Different-shaped brackets, such as (), {} and [], are used for different things. Use the correct ones, and check there’s a complete pair.
ERRORS 95 Errors in the shell window Red text means there’s something wrong! Sometimes, an error message will appear in red text in the shell window. This will also stop the The line in the code (in the program from working. code window) where the error was found 1 Name error If the error message “NameError” appears, it means Python can’t understand one of the words that has been used. If the error is in code entered in the code window, right-click on the error message in the shell window and select “Go to file/line”. >>> Traceback (most recent call last): File “C:\\PythonCode\\errors.py”, line 1, in <module> pront(‘Hello World!’) Cut NameError: name ‘pront’ is not defined Copy The word Python Click here to highlight the line Paste doesn’t understand where the error appears in the Go to file/line 2 Fix the error code window The line with the error is highlighted in the code window. The word “pront” has pront(‘Hello World!’) been typed instead of “print”. You can then edit the code to fix the error. Change this to read “print” Spotting errors ERROR BUSTING Use the tips on these two pages to find Check your code for the following points the line in the code where the errors appear, then double-check that line. Go Have you copied exactly what you were asked to enter? through the checklist on the right to help you find out what has gone wrong. Have you spelled everything correctly? ▷ When things Are there two quote marks (‘) around the expression you go wrong want to print? There are some Do you have extra spaces at the beginning of the line? methods you can Spacing is very important in Python. use to find errors Have you checked the lines above and below the more easily. Here’s highlighted line? Sometimes that’s where the problem is. a handy checklist. Have you asked someone else to check the code against the book? They might spot something you have missed. Are you using Python 3 not Python 2? Programs for Python 3 don’t always work in Python 2.
96 P L A Y I N G W I T H P Y T H O N SEE ALSO PROJECT 4 Ghost game 98–99 decoded Ghost game Program 100–101 This simple game highlights some of the things flow to watch out for when writing programs in Python. Once the code has been typed in, run the program to play the game. Can you escape the haunted house? Start IDLE, and use the # Ghost Game 1 “File” menu to open a new from random import randint window. Save the game as print(‘Ghost Game’) Use single quotes “ghost game.” Arrange the windows so you can see feeling_brave = True Only use capital letters them both, then type this score = 0 where they are shown into the code window. while feeling_brave: Make sure to add These must be a colon here underscores, not ghost_door = randint(1, 3) minus signs print(‘Three doors ahead...’) This section needs to be indented by four spaces. print(‘A ghost behind one.’) If this doesn’t happen print(‘Which door do you open?’) automatically, check that door = input(‘1, 2, or 3?’) there is a colon after “feeling_brave” door_num = int(door) Use two equals if door_num == ghost_door: signs here This indent will start at eight spaces and print(‘GHOST!’) needs to be reduced to just four spaces feeling_brave = False Delete all else: indents here print(‘No ghost!’) print(‘You enter the next room.’) score = score + 1 print(‘Run away!’) print(‘Game over! You scored’, score) There should be no quotes around “score” here
GHOST GAME 97 Once the code has been carefully typed in, use the The game begins in the shell window. The ghost is 2 “Run” menu to select “Run Module.”You must save 3 hiding behind one of three doors. Which one will you pick? Type 1, 2, or 3 then press “Enter.” the program first. Run Ghost Game Python Shell Three doors ahead... Check Module A ghost behind one. Run Module Which door do you open? 1, 2, or 3? Choose “Run Module” from the “Run” menu in Type in your guess the code window The aim of the game is to pick a door with no ghost If you’re unlucky you’ll pick a door with a ghost 4 behind it. If this happens, you’ll move to the next 5 behind it, and the game ends. Run the program room and keep playing the game. again to see if you can beat your last score. Ghost Game Ghost Game Three doors ahead... Three doors ahead... A ghost behind one. A ghost behind one. Which door do you open? Which door do you open? 1, 2, or 3?3 The number you type 1, 2, or 3?2 No ghost! in appears here GHOST! This is what appears if the Run away! ghost is behind your door This is what you’ll Game over! You scored 0 see if there is no ghost behind the door you choose 12 The score shows how many rooms you survived 3
98 P L A Y I N G W I T H P Y T H O N Ghost game decoded SEE ALSO The ghost game displays some of the key features 96–97 Ghost game of Python. You can break down the code to see how Program 100–101 the program is structured and what the different parts of it do. flow Code structure # Ghost Game Python uses spaces at the start of lines from random import randint to work out which instructions belong 1 together. These spaces are called “indents.” print(‘Ghost Game’) Game setup For example, the code after “while feeling_brave” is indented by four spaces feeling_brave = True The main loop to show it’s all part of the main loop. score = 0 ◁ Code key Branching part This diagram shows the while feeling_brave: structure of the ghost This is a “comment”. It’s not game. The numbered shown when the game is run ghost_door = randint(1, 3) parts are explained in more detail below. print(‘Three doors ahead...’) Game ending 2print(‘A ghost behind one.’) print(‘Which door do you open?’) door = input(‘1, 2 or 3?’) door_num = int(door) if door_num == ghost_door: print(‘GHOST!’) feeling_brave = False 3 else: print(‘No ghost!’) print(‘You enter the next room.’) score = score + 1 4print(‘Run away!’) print(‘Game over! You scored’, score) 1 Game setup # Ghost Game This sets up the “randint” These instructions only from random import randint command, which generates run once—at the beginning print(‘Ghost Game’) random numbers of the game. They set up feeling_brave = True the title, variables, and the score = 0 The “print” command “randint” command. displays text when the game is run This resets the score to 0 EXPERT TIPS Type carefully When using Python, enter the code very carefully. If you leave out a colon, quotation mark, or parenthesis, the program won’t work properly. You need to match the use of capital letters and spaces exactly too.
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226