Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Help your kids with computer coding _ a unique step-by-step visual guide, from binary code to building games_clone

Help your kids with computer coding _ a unique step-by-step visual guide, from binary code to building games_clone

Published by THE MANTHAN SCHOOL, 2021-02-25 04:09:36

Description: Help your kids with computer coding _ a unique step-by-step visual guide, from binary code to building games

Search

Read the Text Version

GHOST GAME DECODED 99 2 The main loop while feeling_brave: This selects a This loop tells the story ghost_door = randint(1, 3) random number and receives the player’s guess. between 1 and 3 It keeps on going as long as there isn’t a ghost behind the door print(‘Three doors ahead...’) that’s picked. When a ghost appears, the “feeling_brave” print(‘A ghost behind one.’) The “print” variable changes to “False” and command displays the loop stops repeating. print(‘Which door do you open?’) the text onscreen 3 Branching part The program takes a door = input(‘1, 2 or 3?’) This line asks for different path depending on door_num = int(door) the player’s answer whether or not there was a ghost behind the door that was if door_num == ghost_door: This branch runs picked. If there was a ghost, the print(‘GHOST!’) if there’s a ghost “feeling_brave” variable is set to feeling_brave = False behind the door “False” but if not, the player’s the player picks score increases by one. else: If there’s no ghost, the print(‘No ghost!’) player sees this message print(‘You enter the next room.’) score = score + 1 This shows a message The score increases by one telling the player to run each time the player enters a away from the ghost room without meeting a ghost 4 Game ending print(‘Run away!’) This runs just once, when print(‘Game over! You scored’, score) you meet the ghost and the loop ends. Python knows this The score is a variable—it will isn’t part of the loop because change depending on how many it’s not indented. rooms the player gets through REMEMBER Achievements Congratulations—you’ve created Run a program: You’ve learned how your first Python game! You’ll learn to run a Python program. more about these commands later in the book, but you’ve already Structured a program: You’ve used achieved a lot: indents to structure a program. Entered a program: You’ve typed a Used variables: You’ve used variables program into Python and saved it. to store the score. Displayed text: You’ve displayed messages on the screen.

100 P L A Y I N G W I T H P Y T H O N SEE ALSO Program flow  30–31 Colored blocks Before learning more about Python, it’s important to and scripts understand how programs work. The programming basics learned in Scratch can also be applied to Python. Simple 102–103 From input to output commands A program takes input (information in), processes it Harder 104–105 (or changes it), and then gives back the results (output). It’s a bit like a chef taking ingredients, turning them commands into cakes, and then giving you the cakes to eat. Input Processing Output Input command Variables Print command Keyboard Math Mouse Loops Screen Branches Functions Graphics △ Program flow in Python In Python, the keyboard and mouse are used to input information, which is processed using elements such as loops, branches, and variables. The output is then displayed on the screen.

Looking at the Ghost game through 101P R O G R A M F L O W Scratch goggles EXPERT TIPS Program flow works the same in most programming languages. Here are some examples of input, processing, One script at a time and output in Python’s Ghost game—and what they might look like in Scratch. There’s an important difference between Scratch and Python. Python and Scratch In Scratch, lots of scripts can are more similar run at the same time. In Python, than they appear. however, the program is made up of only one script. 1 Input The question in In Python, the “input()” function takes the Scratch block an input from the keyboard. It’s similar to the “ask and wait” block in Scratch. ask 1, 2 or 3? and wait door = input(‘1, 2 or 3?’) “ask and wait” Scratch block The question This Scratch block appears on screen sets the value of the variable “score” to 0 2 Processing Variables are used to keep track of the score and the function “randint” picks a random door. Different blocks are used to do these things in Scratch. score = 0 set score ▾ to 0 “set score to 0” Scratch block Sets the variable “score” to 0 ghost_door = randint(1, 3) pick random 1 to 3 Selects a random “pick random” Scratch block whole number between 1 and 3 This Scratch block selects a random number 3 Output Shows a speech bubble The “print()” function is used to output things in Python, while the “say” Displays “Ghost game” containing the words block does the same thing in Scratch. on the screen “Ghost game” print(‘Ghost game’) say Ghost game “say” Scratch block

102 P L A Y I N G W I T H P Y T H O N Simple commands SEE ALSO At first glance, Python can look quite scary,  86–87 What is especially when compared to Scratch. However, the two languages aren’t actually as different as Python? they seem. Here is a guide to the similarities between basic commands in Python and Scratch. Harder 104–105 commands Command Python 3 Scratch 2.0 Run program “Run” menu or press “F5” (in code window) Stop program Press “CTRL-C” (in shell window) Write text print(‘Hello!’) say Hello! to screen Set a variable magic_number = 42 set magic_number ▾ to 42 to a number Set a variable word = ‘dragon’ set word ▾ to dragon to a text string Read text from age = input(‘age?’) ask age? and wait keyboard into say join I am print(‘I am ’ + age) variable answer Add a number cats = cats + 1 change cats ▾ by 1 to a variable or a +2 cats += 1 Add a + 2 Subtract a-2 a –2 Multiply a*2 a *2 Divide a/2 a /2

Command Python 3 103S I M P L E C O M M A N D S Forever loop while True: Scratch 2.0 jump() forever jump Loop 10 times for i in range (10): jump() repeat 10 jump Is equal to? a == 2 a =2 Is less than? a < 2 a <2 Is more than? a > 2 a >2 NOT not not OR or AND and or and if a = 2 then say Hello! If then if a == 2: print(‘Hello!’) if a = 2 then say Hello! If then else if a == 2: print(‘Hello!’) else say Goodbye! else: print(‘Goodbye!’)

104 P L A Y I N G W I T H P Y T H O N SEE ALSO Harder commands  86–87 What is Python can also be used to do some of the more Python? complicated things that are possible in Scratch: for example, creating complex loops, playing with strings  102–103 Simple and lists, and drawing pictures with turtle graphics. commands Command Python 3 Scratch 2.0 repeat until roll = 6 jump Loops with while roll != 6: conditions jump() Wait from time import sleep wait 2 seconds sleep(2) set roll ▾ to pick random 1 to 6 Random numbers from random import randint roll = randint(1, 6) Define a def jump(): define jump function or print(‘Jump!’) think Jump! subprogram jump Call a function jump() or subprogram Define a def greet(who): define greet who function or print(‘Hello ’ + who) subprogram with input say join Hello who Call a function greet(‘chicken’) greet chicken or subprogram

Command Python 3 105H A R D E R C O M M A N D S Turtle from turtle import * Scratch 2.0 graphics clear() pendown() clear forward(100) pen down right(90) move 100 steps penup() turn 90 degrees pen up Join strings print(greeting + name) say join greeting name Get one letter name[0] letter 1 of name of a string length of name Length of len(name) Make a List a string add thing to menu ▾ length of menu ▾ Create an menu = list() empty list Add an item menu.append(thing) to end of list How many len(menu) items on list? Value of 5th menu[4] say item 5 ▾ of menu ▾ item on list Delete 2nd del menu[1] delete 2 ▾ of menu ▾ item on list if menu ▾ contains olives then say Oh no! if ‘olives’ in menu: Is item on list? print(‘Oh no!’)

106 P L A Y I N G W I T H P Y T H O N Which window? SEE ALSO There are two different windows to choose from  92–93 Introducing in IDLE. The code window can be used to write and save programs, while the shell window runs IDLE Python instructions right away.  96–97 Ghost The code window game So far in this book, the code window has been used to write programs. You enter the program, save it, run it, ▽ Running programs and the output appears in the shell window. This process is used for running Python programs. Enter code Save Run module Programs always have to be saved before running them. Output 1 Enter a program in the code window 2 Output in the shell window Enter this code in the code window, save When the program runs, its output it, and then click on “Run module” in the “Run” (the results of the program) is shown in menu to run the program. the shell window. a = 10 Give “a” the value 10 >>> b=4 14 print(a + b) Give “b” the value 4 6 print(a - b) The “print” command The answers to the sums shows the answers to appear in the shell window these sums The shell window Python can also understand commands that are typed in the shell window. They run as soon as they are typed in, and the result is shown straight away. >>> a = 10 The first two commands have △ Test your ideas no output because they are just The shell window gives you an immediate >>> b = 4 assigning values to “a” and “b” response, which makes it ideal for testing instructions and exploring what they can do. >>> a + b ◁ Code and output together 14 Output appears The shell window shows the code and the output together. It’s easier immediately to tell which answer belongs to which sum when the commands >>> a - b are typed in the shell window. 6

107W H I C H W I N D O W ? Python playground EXPERT TIPS The shell window can be used to try out all sorts of Colors in the code Python commands, including drawing. The turtle is used to draw on screen in the same way that the pen IDLE color-codes the text. is used in Scratch. The colors give you some clues about what Python thinks each Loads all the commands piece of text is. that control the turtle ◁ Built-in functions >>> from turtle import * ◁ Enter the code Commands in Python, such as >>> forward(100) “print”, are shown in purple. >>> right(120) Type these >>> forward(100) instructions in the ◁ Strings in quotes shell window. They Green indicates strings. If the Moves the turtle forward run after each one brackets are green too, there’s is typed. As the a missing quote mark. turtle moves, it draws a line. ◁ Most symbols and names Most code is shown in black. ◁ Turtle graphic Can you work out how to ◁ Output draw other shapes, such as Python’s output in the shell a square or a pentagon? window is shown in blue. To start over, type “clear()” into the shell window. ◁ Keywords Keywords, such as “if” and “else”, Which window should you use? are orange. Python won’t let you use keywords as variable names. Should you use the code window or the shell window? It depends on the type of ◁ Errors program you’re writing, and whether it has Python uses red to alert you to be repeated. to any error messages in the shell window. ▷ Code window Code vs Shell ◁ Shell window The code window is ideal for The shell window is perfect for longer pieces of code quick experiments, such as because they can be saved checking how a command and edited. It’s easier than works. It’s also a handy retyping all the instructions calculator. It doesn’t save the if you want to do the same instructions though, so if you’re thing again or try something trying something you might similar. It needs to be saved want to repeat, consider using and run each time, though. the code window instead.

108 P L A Y I N G W I T H P Y T H O N Variables in Python SEE ALSO Variables are used to remember pieces of information Types of data 110–111 in a program. They are like boxes where data can be Math in 112–113 stored and labeled. Python Strings in 114–115 Python Creating a variable Input and 116–117 output When a number or string is put into a variable Functions 130–131 it’s called assigning a value to the variable. You use an “=” sign to do this. Try this code in the shell window. REMEMBER Variable Value assigned Variables in Scratch name to the variable >>> bones = 3 The command to assign a variable in Python does the same job as this Scratch block. However, in △ Assign a number Python you don’t have to click a button to create To assign a number, type in the variable name, a variable. Python creates the variable as soon as an equals sign, and then the number. you assign a value to it. Variable String assigned set bones ▾ to 3 name to the variable Scratch block for giving >>> dogs_name = ‘Bruno’ a value to a variable △ Assign a string To assign a string, type in the variable name, an equals sign, and then the string in quote marks. Printing a variable The “print” command is used to show something on the screen. It has nothing to do with the printer. You can use it to show the value of a variable. >>> print(bones) >>> print(dogs_name) No quote Bruno marks here 3 Variable name △ String output △ Number output The variable “dogs_name” contains a string, so the The variable “bones” contains the string is printed. No quote marks are shown when number 3, so that’s what the shell you print a string. window prints.

VARIABLES IN PYTHON 109 Changing the contents >>> gifts = 2 Changes the value of a variable >>> print(gifts) of the variable 2 To change the value of a variable, >>> gifts = 3 simply assign a new value to it. >>> print(gifts) Here, the variable “gifts” has the 3 value 2. It changes to 3 when it’s assigned a new value. Using variables EXPERT TIPS The value of one variable can be assigned to another Naming variables one using the “=” sign. For example, if the variable “rabbits” contains the number of rabbits, we can use There are some rules you have to it to assign the same value to the variable “hats”, so that follow when naming your variables: each rabbit has a hat. All letters and numbers can be used. 1 Assign the variables You can’t start with a number. This code assigns the number 5 to Symbols such as -, /, #, or @ can’t the variable “rabbits”. It then assigns the be used. same value to the variable “hats”. Spaces can’t be used. An underscore ( _ ) can be used Variable Value assigned instead of a space. name to the variable Uppercase and lowercase letters are different. Python treats “Dogs” and >>> rabbits = 5 “dogs” as two different variables. >>> hats = rabbits Don’t use words Python uses as a command, such as “print”. “hats” now has the same value as “rabbits” 2 Print the values 3 Change the value of “rabbits” To print two variables, put them both in If you change the value of “rabbits”, it doesn’t brackets after the “print” command, and put a affect the value of “hats”. The “hats” variable only comma between them. Both “hats” and changes when you assign it a new value. “rabbits” contain the value 5. >>> rabbits = 10 Give “rabbits” a new value >>> print(rabbits, hats) >>> print(rabbits, hats) 55 Leave a space 10 5 Value for “hats” after the comma remains the same

110 P L AYI N G W I T H PYT H O N Types of data SEE ALSO There are several different types of data in Python. Maths in 112–113 Most of the time, Python will work out what type Python is being used, but sometimes you’ll need to change data from one type to another. Strings in 114–115 Python Numbers Making 118–119 decisions Python has two data types for numbers. “Integers” are whole numbers, (numbers without a decimal point). “Floats” are numbers with a Lists 128–129 decimal point. An integer can be used to count things such as sheep, while a float can be used to measure things such as weight. >>> sheep = 1 An integer >>> sheep = 1.5 1.5 is a whole is a float >>> print(sheep) number >>> print(sheep) 1 1.5 △ Integers △ Floats An integer is a number without A float is a number with a decimal a decimal point, such as the 1 point, such as 1.5. They aren’t normally in the variable “sheep”. used to count whole objects. Strings Always remember that strings need quote Just like in Scratch, a piece of text in Python is called marks at the start a “string”. Strings can include letters, numbers, spaces, and the end. and symbols such as full stops and commas. They are usually put inside single quote marks. The string in quotes ▷ Using a string >>> a = ‘Coding is fun!’ To assign a string to >>> print(a) The value of a variable, put the Coding is fun! the variable “a” text inside single printed out quote marks.

111T Y P E S O F D A T A Booleans EXPERT TIPS In Python, a Boolean always has a value Spotting data types that is either “True” or “False”. In both cases, the word begins with a capital letter. In Python, there are many data types. To find out what data type something is, you can use the No quote “type” command. marks “type” >>> a = True command >>> print(a) ▷ True True >>> type(24) 24 is an When the value <class ‘int’> integer (“int”) “True” is put into Boolean value >>> type(24.3) a variable, it will be printed <class ‘float’> 24.3 is a float a Boolean variable. >>> type(‘24’) (“float”) >>> a = False <class ‘str’> ▷ False ‘24’ is a string (“str”) When the value >>> print(a) because it is in “False” is put into quote marks a variable, it will False Boolean value be a Boolean printed variable too. Converting data types Variables can contain any type of data. Problems occur if you try to mix types together. Data types sometimes have to be converted; otherwise, an error message will appear. Variable name String in quote marks shown on screen ▷ Mixed type >>> apple = input(‘Enter number of apples ’) The “input” command Enter number of apples 2 Tries to add the number 1 always gives a string, >>> print(apple + 1) to the variable “apple” even if a number is entered. In this example, TypeError since “apple” actually contains a string, an error The program gives an error message because Python message is displayed. doesn’t know how to add a number to a string ▷ Converting data types >>> print(int(apple) + 1) 3 To convert the string into a number, the “int()” The program now works The variable turns from a string into an command is used to turn and shows the result integer, so a number can be added to it it into an integer.

112 P L AYI N G W I T H PYT H O N Math in Python SEE ALSO Python can be used to solve all sorts of  52–53 Math mathematical problems, including addition,  108–109 Variables subtraction, multiplication, and division. Variables can also be used in sums. in Python Simple calculations You can’t divide by zero, so you’ll always get an error In Python, simple calculations can be made by typing them into the shell window. The “print()” function is not needed if you try to do so. for this—Python gives the answer straight away. Try these examples in the shell window: >>> 12 + 4 Use the shell window >>> 12 - 4 16 to get instant results 8 △ Addition The answer △ Subtraction Use the “+“ symbol to add appears when Use the “-” symbol to subtract the numbers together. you press “Enter” second number from the first one. Computers use the “*” symbol, not “x”, for multiplication >>> 12 * 4 >>> 12 / 4 Division in Python gives an 48 3.0 answer as a float (a number with a decimal point) △ Multiplication Use the “*” symbol to multiply two △ Division numbers together. Use the “/” symbol to divide the first number by the second one. Using brackets First it works out that First it works out 6 + 5 = 11, then 11 that 5 * 3 = 15, then Brackets can be used to instruct is multiplied by 3 Python which part of a sum to 15 is added to 6 do first. Python will always work out the value of the sum in the >>> (6 + 5) * 3 >>> 6 + (5 * 3) bracket, before solving the rest of the problem. 33 21 Different answer △ Addition first △ Multiplication first In this sum, brackets are Brackets here are used to do the used to instruct Python to multiplication first, in order to end do the addition first. up with the correct answer.

113M A T H I N P Y T H O N Putting answers in variables 1 Do a simple addition This program adds together the If variables are assigned number values, you variables “ants” and “spiders”, and puts can use them within sums. When a sum is the answer into the variable “bugs”. assigned to a variable, the answer goes into the variable, but not the sum. >>> ants = 22 >>> spiders = 35 >>> bugs = ants + spiders >>> print(bugs) Adds the values of the 57 two variables together 2 Change the value of a variable Prints the value in “bugs” Change the value of the “ants” or “spiders” variable. Add the variables together again and put 3 Skipping the assignment the answer in the variable “bugs”. If the sum is not assigned to the variable “bugs”, even if the value of “ants” and “spiders” changes, the value of “bugs” won’t. >>> ants = 22 Change the value >>> ants = 11 Prints the >>> spiders = 18 in “spiders” >>> spiders = 17 value in “bugs” >>> print(bugs) >>> bugs = ants + spiders 40 >>> print(bugs) Add the variables together again The answer hasn’t changed (it’s still 18 + 22) 40 The answer changes Random numbers REMEMBER To pick a random number, you first need to load the Random block “randint” function into Python. To do this, use the “import” command. The “randint()” function is already programmed The “randint()” function works like with code to pick a random integer (whole number). the “pick random” block in Scratch. In Scratch, the lowest and highest Adds the “randint()” possible numbers are typed into function the windows in the block. In Python, the numbers are put in >>> from random import randint brackets, separated by a comma. >>> randint(1, 6) Picks a random number pick random 1 to 6 3 between 1 and 6 △ Whole numbers 3 has been picked at random Both the Python “randint()” function and the Scratch block pick a random △ Roll the dice whole number—the result is never The “randint()” function picks a random number between in decimals. the two numbers in the brackets. In this program, “randint(1, 6)” picks a value between 1 and 6.

114 P L AYI N G W I T H PYT H O N Strings in Python SEE ALSO Python is excellent for using words and sentences  54–55 Strings within programs. Different strings (sequences of characters) can be joined together, or individual and lists parts of them can be selected and pulled out.  110–111 Types of data Creating a string A string might include letters, numbers, symbols, or spaces. These are all called characters. Strings can be placed in variables. The quotation marks indicate the variable contains a string ▷ Strings in variables >>> a = ‘Run! ’ Variables can store strings. Type these two strings into the variables “a” and “b”. >>> b = ‘Aliens are coming.’ Adding strings EXPERT TIPS Adding two numbers together creates a new number. Length of a string In the same way, when two strings are added together, one string simply joins on to the other one. The “len()” function is used to find out the length of a string. Python >>> c = a + b The variables “a” and “b” counts all of the characters, >>> print(c) combine to become including spaces, to give the total variable “c” number of characters in a string. Run! Aliens are coming. Calculates the length of the string △ Adding strings together A new string is added in variable “a” (“Run! ”) The “+” symbol joins one string to another. to variable “c” and the answer becomes the variable “c”. >>> len(a) 4 >>> c = b + ‘ Watch out! ’ + a >>> print(c) >>> len(b) Aliens are coming. Watch out! Run! 18 △ Adding another string in between The new string The string in variable “b” A new string can also be added between appears in the middle (“Aliens are coming.”) is two strings. Try the example above. of the message 18 characters long

115S T R I N G S I N P Y T H O N Numbering the characters Each character in a string is allocated a number according to its position. This position number can be used to look at individual letters or symbols, or to pull them out of a string. 1 Count begins from zero 2 Counting the characters When counting the positions, Python The position number is called an starts at 0. The second character is in position “index”. It can be used to pull out a 1, the third in position 2, and so on. particular letter from a string. >>> a = ‘FLAMINGO’ The sixth letter, >>> a[3] “N”, is in position 5 ‘M’ Square brackets go GO around the index 67 F L AM I N The character in position 3 012345 from the variable “a” The last character, “O”, is in position 7 The first character, “F”, is in position 0 3 “Slicing” 4 From the start or the end Two indexes can be used to pull out If you leave off the start or end a part of the string or “slice” it. The letter in index, Python will automatically use the the last position isn’t included. first or the last character of the string. >>> a[1:7] Colon defines the >>> a[:3] ‘LAMING’ range of characters ‘FLA’ >>> a[3:] A slice from index 1 to Starts at ‘MINGO’ Ends at index 7 index 6 of variable “a” index 0 Apostrophes >>> print(‘It\\’s a cloudy day.’) It’s a cloudy day. Strings can go in single or double quotation marks. However, the string The apostrophe △ Escaping the apostrophe should start and end with the same type is included in of quotation mark. This book uses single the string So Python doesn’t read an quotes. But what happens if you want to apostrophe as the end of the use an apostrophe in your string? string, type a “\\” before it. This is called “escaping” it.

116 P L AYI N G W I T H PYT H O N Input and output SEE ALSO Programs interact with users through input and output.  100–101 Program Information can be input into a program using a keyboard. Output is shown as information printed on the screen. flow  110–111 Types of data Loops 122–123 in Python Input The “input()” function allows users to interact with a program The “input()” function is used to accept input from the using their keyboard keyboard into a program. It waits until the user finishes typing and presses the “return” or “Enter” key. 1 Using input Adding a space 2 Output in the shell window A program can prompt the after the colon When the program is run, the message user what to type. The message is makes the output “Enter your name: ” and its response appear in put inside the brackets of “input()”. look tidier the shell window. name = input (‘Enter your name: ’) Enter your name: Jina print(‘Hello’, name) Hello Jina What the program outputs depends Program outputs User types in on what name the user types message their name Output The “print()” function is used to display characters in the shell window. It can be used to show a combination of text and variables. Output is displayed on the screen 1 Create some variables 2 Using the “print()” function Set up three variables for this simple You can put several items inside the brackets experiment. Two are strings and one is an of the “print()” function. You can combine variables of integer (whole number). different types, and even combine strings and variables. >>> a = ‘Dave’ Quote marks >>> print(a, b, c) >>> b = ‘is’ show these Dave is 12 >>> c = 12 are strings >>> print(‘Goodbye’, a) Goodbye Dave No quote marks as Comma separates this is an integer the different items

117I N P U T A N D O U T P U T Two ways to separate strings The separator So far, the output has been printed on one >>> print(a, b, c, sep=‘\\n’) line with a space between the items. Here are two other ways of separating strings. Dave Each variable starts is on a new line >>> print(a, b, c, sep=‘-’) Dave-is-12 12 △ Hyphenate the outputs The character △ Outputs on new lines A hyphen can be put between the variables between the The space or character between the outputs when they’re printed. Other characters, outputs is called a “separator” (“sep”). Using “\\n” prints such as “+” or “*”, can be used too. each output on a new line. Three ways to end output EXPERT TIPS There are several different ways you Options at the end can signal the end of the output of a “print” function. The “end” and “sep” labels tell Python that the next item in the program isn’t just another >>> print(a, ‘.’) Period added string. Remember to use them; otherwise, the Dave . as a string program will not work correctly. >>> print(a, end=‘.’) Period added end sep Dave. as an “end” character △ Add a period to the output A period can be added as another string to be printed, but it will print with a space before it. To avoid this, use “end=‘.’” instead. Space >>> print(a, end=‘\\n\\n\\n\\n’) as “end” Loop to print character Dave three times Each “\\n” starts Blank space a new line before the >>> for n in range(3): prompt print(‘Hurray!’ end=‘ ’) >>> Hurray! Hurray! Hurray! △ Output on one line Output is △ Blank lines at the end Usually, each new “print” command starts all printed Using “\\n” starts each output from a new on a new line. To get the output all on one on one line line. Several of them can be used together line use a space as the “end” character. to add blank lines at the end of a program.

118 P L AYI N G W I T H PYT H O N Making decisions SEE ALSO Programs make decisions about what to do  62–63 True or by comparing variables, numbers, and strings using Boolean expressions. These give an false? answer of either “True” or “False”.  108–109 Variables in Python Logical operators Logical operators are used to compare variables against numbers or strings, or even against other variables. The resulting answer is either “True” or “False”. == “Equals” operator “Not equal >>> toys = 10 This checks whether >>> toys == 1 “toys” is equal to 1 != to” operator False This checks whether “Less than” >>> toys > 1 “toys” is more than 1 < operator > “Greater than” True This checks whether <= operator >>> toys < 1 “toys” is less than 1 >= False “Less than or >>> toys != 1 This checks if “toys” equal to” operator True is not equal to 1 “Greater than or This checks if “toys” is less equal to” operator than or equal to 10 △ Types of comparison operators >>> toys <= 10 The “not” logical operator True reverses the answer (in this There are six comparison operators. Python >>> not toys == 1 example, from “False” to “True”) uses two equals signs to compare if two True things are the same. (A single equals sign The “or” logical operator is used to assign a value to a variable.) checks if “toys” is 9 or 10 >>> toys == 9 or toys == 10 True ▷ Use the shell to check >>> toys == 9 and toys == 10 Logical operators also work in the False The “and” logical operator is shell window. Use this example to used to check if “toys” is both 9 try out several logical operators, and 10. This can never be true, including “not”, “or”, and “and”. so the answer is “False”

119M A K I N G D E C I S I O N S Is it Ella’s birthday? 1 Check for the birthday Create variables for a day and a month. Ella’s birthday is July 28th. This Use the “and” logical operator to check program takes a day and a month whether it is July 28th. and uses logical operators to check whether it’s Ella’s birthday. >>> day = 28 The “and” operator >>> month = 7 checks to see if both 2 Not the birthday detector conditions are true You can reverse the answer using the “not” logical operator. You will get the answer “True” on >>> day == 28 and month == 7 every day, except for Ella’s birthday. True Remember to use two equals signs It’s Ella’s birthday! 3 Birthday or New Year’s Day? Use the “or” logical operator to check whether it’s Ella’s birthday or New Year’s Day. Use brackets to combine the correct days and months. >>> day = 28 >>> day = 28 Checks for the >>> month = 7 28th of July >>> month = 7 This character is used to make >>> not (day == 28 and \\ code go over >>> (day == 28 and month == 7) \\ two lines month == 7) or (day == 1 and month == 1) False It’s Ella’s birthday, so the True The answer will be “True” if it’s answer is “False” Ella’s birthday or New Year’s Day Strings EXPERT TIPS Two strings can be compared using the Operator for strings “==” operator or the “!=” operator. Strings have to match exactly to get a “True” output. The “in” operator can be used to see whether one string is inside another >>> dog = ‘Woof woof’ The strings match string. Use it to check if a string >>> dog == ‘Woof woof’ exactly, so the contains a particular letter or a answer is “True” group of letters. True The strings don’t match >>> dog == ‘woof woof’ because there isn’t a This checks whether “a” is in “abc” capital “W” False >>> dog == ‘Woof woof ’ The strings don’t >>> ‘a’ in ‘abc’ match because there’s False extra space before True the quotation mark △ Exactly the same >>> ‘d’ in ‘abc’ Strings must match for them to be equal. That means they must use capital letters, spaces, False “d” is not in “abc”, so and symbols in exactly the same way. the answer is “False”

120 P L A Y I N G W I T H P Y T H O N SEE ALSO Branching  64–65 Decisions Boolean expressions can be used to determine which and branches route a program should follow, depending on whether the answer to the expression is “True” or “False”. This is  118–119 Making known as “branching”. decisions Do or do not The “if” command means that if a condition is “True”, then the program runs a block of commands. If the condition isn’t “True”, the block is skipped. The block after the “if” command is always indented by four spaces. Prompts users what to type in 1 “if” condition ans = input(‘Is it your birthday? (y/n)’) This code asks the user if it’s their birthday. It checks if ans == ‘y’: This part of the whether the answer is “y”. If so, print(‘Happy Birthday!’) program only runs a birthday message is printed. if the user types “y” Indented by four spaces Type in “y” 2 Output if condition is “True” Is it your birthday? (y/n)y Run the program and enter “y”. The message is printed. It doesn’t Happy Birthday! The message appears appear if anything else is entered. Do this or that The “if” command can be combined with an “else” command. This combination means that if something is “True”, one thing happens, and if not, something else happens. 1 “if-else” condition ans = input(‘Is it New Year? (y/n)’) If “y” is entered, the program prints a special message for New if ans == ‘y’: Remember the colon This message only Year. It shows a different message appears if the if anything else is entered. print(‘Happy New Year!’) user enters “y” Remember to put print(‘Time for Fireworks.’) a colon here too else: Only runs if user print(‘Not yet!’) does not enter “y”

121B R A N C H I N G 2 Output if condition is “True” 3 “else” condition output Type in “n” Run the program and type in “y”. The program Type in “n”, or any other character, shows your New Year message. It doesn’t show the and the New Year message isn’t shown. other message. Instead, the “Not yet!” message appears. Is it New Year? (y/n)y Type in “y” Is it New Year? (y/n)n Happy New Year! Not yet! Time for Fireworks. A different message appears Do one of these things The “elif“ command is short for “else-if”. It means that if something is “True”, do one thing; otherwise, check if something else is “True” and do something else if it is. The following calculator program uses the “elif“ command. 1 “if-elif-else” condition 2 Output for the condition that’s “True” This program checks what is typed Test the program. Enter two numbers and in. If it’s “add”, “sub”, “mul”, or “div”, the type in “sub”. The answer will be the first number result of the sum is shown. minus the second number. Asks the user to Remember to a=7 Enter two numbers Type in “sub” input a number add quote marks b=5 to subtract and brackets 5 from 7 a = int(input(‘a = ’)) add/sub/mul/div:sub b = int(input(‘b = ’)) Answer = 2 op = input(‘add/sub/mul/div:’) if op == ‘add’: Type “add” to Answer is calculated c=a+b add the variables by subtracting variable together “a” from variable “b” elif op == ‘sub’: c=a-b 3 “else” condition output The “else” condition runs if something other than elif op == ‘mul’: Type “div” to “add”, “sub”, “mul”, or “div” is typed in, and an error message c=a*b divide the is displayed. variables elif op == ‘div’: c=a/b Shows an error message a=7 Type something else: in “c” if something else b=5 different here is typed in add/sub/mul/div:try Answer = Error Error message c = ‘Error’ Shows the displays print(‘Answer = ’,c) answer or error message

122 P L A Y I N G W I T H P Y T H O N Loops in Python SEE ALSO Programs that contain repeating lines of code can be  48–49 Pens time-consuming to type in and difficult to understand. A clearer way of writing them is by using a loop command. and turtles The simplest loops are ones that repeat a certain number of times, such as “for” loops. While loops 124–125 Escaping 126–127 loops Repeating things A “for” loop repeats the code without having to type it in again. It can be used to repeat something a certain number of times, for example, if you want to print the names of a class of 30 students. 1 Program the turtle from turtle import * A “for” loop can also be used to shorten the code. This program allows the user to control a turtle forward(100) Loads all the that draws a line as it moves around the screen. The right(120) commands user can draw shapes on the screen, such as a triangle, forward(100) that control by directing the turtle’s movements. the turtle This makes the right(120) This command moves turtle turn 120 forward(100) the turtle forward degrees to the right right(120) 2 The turtle draws a triangle 3 Use a “for” loop The program tells the turtle how to draw a The program above gives the turtle the same two triangle by giving it the length of the three sides and commands, “forward(100)” and “right(120)”, three times – the angles between them. The turtle will appear in once for each side of the triangle. An alternative to this a separate window when you run the program. is to use these two commands inside a “for” loop. Try drawing a triangle simply using the code shown below. for i in range(3): The turtle forward(100) The “for” loop tells the in Python right(120) program to repeat the instructions three times The program The block of instructions makes the turtle in a loop is indented by draw a triangle four spaces

123L O O P S I N P Y T H O N Loop variables The loop variable The loop repeats ten times A loop variable counts the number of times for i in range(10): print(i, end=‘ ’) a loop has repeated itself. It starts at the first >>> 0 1 2 3 4 5 6 7 8 9 value in the range (0) and stops one before △ Simple loop variable the last value. Python stops Here, the loop’s range doesn’t state what the starting value should be. So Python starts counting from 0, the counting one before same way as it does with strings. the last value This tells the program to count backward This tells the program to count in twos for i in range(2, 11, 2): for i in range(10, 0, -1): print(i, end=‘ ’) print(i, end=‘ ’) >>> 2 4 6 8 10 The output >>> 10 9 8 7 6 5 4 3 2 1 appears in twos △ Counting backward △ Counting in twos This time the program counts backward from 10, like in This loop has a third value in its range, which tells the a rocket launch. The loop variable starts at 10 and takes loop to count in twos. It stops at 10, which is one loop steps of -1 until it reaches 1. before the loop variable gets to 11. Nested Loops >>> The value of “a” Loops inside a loop are called “nested loops”. The value 1x1=1 First time around In nested loops, the outer loop only repeats of “b” 2x1=2 the outer loop (the after the inner loop has gone round its 3x1=3 inner loop repeats required number of times. Outer three times) loop To make the loops repeat “n” number of times, 1x2=2 Second time around the last number in the range must be “n + 1” 2x2=4 the outer loop n=3 3x2=6 for a in range(1, n + 1): 1x3=3 Third time around for b in range(1, n + 1): 2x3=6 the outer loop print(b, ‘x’, a, ‘=’, b * a) 3x3=9 △ Loops inside a loop Inner △ What happens loop In this example, each time the outer The nested loops print the first three lines loop goes around once, the inner loop This sum will be of the 1, 2, and 3 times tables. The value of goes around three times. So in total, the printed nine times “a” only changes when the outer loop outer loop is executed three times and repeats. The value of “b” counts from 1 the inner loop is executed nine times. to 3 for each value of “a”.

124 P L A Y I N G W I T H P Y T H O N SEE ALSO While loops  118–119 Making “For” loops are useful when you know how many times a decisions task needs to be repeated. But sometimes you’ll need a loop to keep repeating until something changes. A “while”  122–123 Loops loop keeps on going around as many times as it needs to. in Python Escaping 126–127 loops While loops No A while loop keeps repeating as long as a certain ▷ How it works Monster friendly? condition is true. This condition is called the Yes “loop condition” and is either true or false. A while loop checks if the Stay very still 1 Create a while loop condition is true. Set the starting value of the “answer” variable in If it is, it goes the loop condition. The loop condition has to be true around the loop to start with or the program will never run the loop. again. If it’s not, it skips the loop. The code The “answer” variable is set to “y” Run away! inside the loop must answer = ‘y’ be indented four spaces while answer == ‘y’: The while loop only runs print(‘Stay very still’) if the condition is true answer = input(‘Is the monster friendly? (y/n)’) print(‘Run away!’) If the condition is false, unindented code after the loop runs and a different message appears 2 What the program looks like REMEMBER The value entered is stored in the variable “answer”. The loop condition is “answer == ‘y’”. If you type “y”, “repeat until” block the loop keeps going. If you type “n”, the loop stops. Python’s “while” loop is similar to >>> the “repeat until” block in Scratch. Both keep on repeating until Stay very still something different happens in the program. Is the monster friendly? (y/n)y repeat until Stay very still Answer is “y”, so the loop keeps running Repeats blocks inside it until condition is true Is the monster friendly? (y/n)y Stay very still Is the monster friendly? (y/n)n Run away! Answer is “n”, so the loop ends and a new message appears

125W H I L E L O O P S Forever loops △ Going loopy Some loops run forever. If you set the condition in a “while” A loop with the loop to be “True”, it can never be false and the loop will condition “True” is never end. This can either be useful or very annoying. called an “infinite” loop. If something is 1 Create a forever loop The typed word infinite it has no end. The loop condition here is set to “True”. Nothing is stored in the that happens inside the loop will make “True” equal variable “answer” anything but “True”, so the loop runs forever. while True: The loop is always “True” so will never end answer = input(‘Type a word and press enter: ’) print(‘Please do not type \\’’ + answer + ‘\\’ again.’) 2 What the program looks like No matter what is typed, On the opposite page the monster program’s loop condition this loop just keeps on going checked to see what the user’s answer was. If the answer isn’t “y”, the loop will stop. The loop shown above doesn’t check the REMEMBER answer, so the user can’t make it stop. “forever” block >>> Type a word and press enter: tree Remember the “forever” block in Please do not type ‘tree’ again Scratch? It repeats the code inside Type a word and press enter: hippo it until the red stop button is Please do not type ‘hippo’ again clicked. A “while True” loop does Type a word and press enter: water exactly the same thing. It can be Please do not type ‘water’: again used to make a program keep Type a word and press enter doing something, such as asking questions or printing a number, as EXPERT TIPS Ctrl-C long as the program is running. Stop the loop forever If you get stuck in an infinite loop, you can The “forever” block keeps stop it from IDLE. Click in the Python shell the sprite moving endlessly window, then hold down the “CTRL” key and press the “C” key. This asks IDLE to stop the program. You might have to press “CTRL-C” a few times. This is similar to clicking the red stop button in Scratch.

126 P L A Y I N G W I T H P Y T H O N SEE ALSO Escaping loops  122–123 Loops Programs can get stuck in a loop, but there are ways in Python to escape. The word “break” leaves a loop (even a “forever” loop), and the word “continue” skips back  124–125 While to the start of the next loop. loops Inserting breaks table = 7 The variable “i” will for i in range(1, 13): count from 1 to 12 Putting a break into a loop makes the program jump out of the print(‘What\\’s’, i, ‘x’, table, ‘?’) loop at once—even if the loop condition is true. Any commands guess = input() “i” is the loop variable inside the loop that come after ans = i * table the break are ignored. if int(guess) == ans: The backslash (“\\”) tells 1 Write a simple program print(‘Correct!’) Python the next quote This program tests the user on the mark is an apostrophe, 7 multiplication table. The program else: not the end of the string continues looping until all 12 questions are answered. Write this program in the code print(‘No, it\\’s’, ans) window because it will be edited later. print(‘Finished’) 2 Insert a “break” table = 7 A “break” can be added so the user can escape the loop. The program for i in range(1,13): executes a break if the user types “stop”. print(‘What\\’s’, i, ‘x’, table, ‘?’) If “guess” equals “stop”, the program skips the rest of the guess = input() loop and prints “Finished” if guess == ‘stop’: break ans = i * table The “ans” variable if int(guess) == ans: holds the correct answer to the print(‘Correct!’) question else: print(‘No, it\\’s’, ans) print(‘Finished’)

>>> 127E S C A P I N G L O O P S What’s 1 x 7 ? 3 How it works If the user decides not to carry on 1 The first time around the after the third question and types “stop”, No, it’s 7 loop “i” is equal to 1 the break command is executed and the program leaves the loop. What’s 2 x 7 ? 14 The value of “i” changes to Correct! 2 next time around the loop What’s 3 x 7 ? stop This executes the break Finished command and the program exits the loop Skipping The “continue” keyword can be used to skip a question without leaving the loop. It tells the program to ignore the rest of the code inside the loop and skip straight to the start of the next loop. table = 7 4 Insert a continue Add an “if” statement inside the loop for i in range(1,13): to see if the user answered “skip”. If so, the program will print “Skipping” and print(‘What\\’s’, i, ‘x’, table, ‘?’) execute a “continue” to skip to the next go around the loop. guess = input() Asks the question if guess == ‘stop’: “What’s 1 x 7?” first 5 What happens time around the loop If the user doesn’t want to answer break if guess == ‘skip’: a question, he or she can type “skip” and continue to the next question. print(‘Skipping’) Skips straight >>> continue to the next loop ans = i * table What’s 1 x 7 ? if int(guess) == ans: skip Type “skip” to go to print(‘Correct!’) Skipping the next question else: What’s 2 x 7 ? The loop goes around print(‘No, it\\’s’, ans) 14 again as normal when Correct! the answer is correct print(‘Finished’) What’s 3 x 7 ?

128 P L A Y I N G W I T H P Y T H O N Lists SEE ALSO If you need to keep lots of data in one place, then you  54–55 Strings can put it in a list. Lists can contain numbers, strings, other lists, or a combination of all these things. and lists Silly 132–133 sentences What is a list? ▽ Looking at lists A list is a structure in Python where items are kept in Each item in a list sits inside single order. Each entry is given a number that you can use to quote marks, and is separated from refer back to it. You can change, delete, or add to the the next item by a comma. The whole items in a list at any point. list sits inside a pair of square brackets. The list is stored in the variable “mylist” >>> mylist = [‘apple’, ‘milk’, ‘cheese’, ‘icecream’, \\ This character is used to make code ‘lemonade’, ‘tea’] The items in a list are go over two lines separated by commas The items in the list [0] Just like with strings, Python starts counting sit inside a pair of [1] the items in a list from zero. So, here, the square brackets [2] position (or “index”) of “apple” is “0” ▷ How it works Typing “mylist[1] = ‘cake’” You can think of a list as a row would replace “milk” on shelf 1 of shelves in a kitchen. Each with “cake” shelf holds one item from the list. To make changes to an The value of “mylist[2]” item, you must refer to the is “cheese” shelf it is on. To get to an item [3] You could add an orange in front of the ice on the list, you [4] cream by typing “mylist.insert(3, ‘orange’)”. must go to the The ice cream would then move to position right shelf 4, and so on Writing “del mylist[4]” would delete “lemonade” from the list, and move “tea” into position 4 instead The position of an [5] You could add a new item, “pie”, at item in a list is the end of the list by writing “mylist. append(‘pie’)”. This will then be called its “index” added after “tea”, in position 6

L I S T S 129 Using lists LINGO Once a list has been created, you can write programs to Mutable objects manipulate the data inside it—in a loop, for example. You can also combine lists to make new lists. Lists in Python are “mutable”. This means that they can change. The list is stored in the variable “names” You can add or delete items, or switch around their order. Other >>> names = [‘Simon’, ‘Kate’, ‘Vanya’] functions in Python, such as tuples >>> for item in names: (see pp.134–135), can’t be altered once you create them. These are print(‘Hello’, item) called “immutable”. Hello Simon The body of the loop must ◁ Lists in loops Hello Kate be indented by four spaces You can use a loop to work through every Hello Vanya item in a list. This program says “Hello” to When run, this program displays “Hello”, a series of names, one after the other. followed by each name on the list x = [1, 2, 3, 4] Remember, lists are contained ◁ Adding lists within square brackets Two lists can be y = [5, 6, 7, 8] added together. The new list will z=x+y This adds the The new list contains contain the items lists together everything from list “x” from both of the followed by everything old lists. print(z) from list “y” z = [1, 2, 3, 4, 5, 6, 7, 8] ▽ Lists in lists Because the list is inside square “suitcase[1]” brackets, it becomes an The items in a list can be lists themselves. The individual item within the “suitcase” list below contains two lists of “suitcase” list—“suitcase[0]” clothes—it is like a suitcase shared by two people, where they each pack three items. >>> suitcase=[[‘hat’, ‘tie’, ‘sock’],[‘bag’, ‘shoe’, ‘shirt’]] >>> print(suitcase) This will print the whole suitcase list [[‘hat’, ‘tie’, ‘sock’],[‘bag’, ‘shoe’, ‘shirt’]] >>> print(suitcase[1]) This will print everything in the [‘bag’, ‘shoe’, ‘shirt’] second list, “suitcase[1]” >>> print(suitcase[1][2]) This prints the item at index 2 in shirt “suitcase[1]”—remember, Python starts counting the items from zero

130 P L A Y I N G W I T H P Y T H O N SEE ALSO Functions Silly 132–133 A function is a piece of code that performs a specific task. sentences It bundles up the code, gives it a name, and can be used any time by “calling” it. A function can be used to avoid Variables and 138–139 entering the same lines of code more than once. functions Useful functions Python contains lots of useful functions for performing certain tasks. When a function is called, Python retrieves the code for that function and then runs it. When the function is finished, the program returns to the line of code that called it and runs the next command. print() input() randint() △ “print()” function △ “input()” function △ “randint()” function This function lets the program This function is the opposite of the This function gives a random send output to the user by “print()” function. It lets the user number (like throwing a dice). printing instructions or results give instructions or data to the It can be used to add an element on the screen. program by typing them in. of chance to programs. Making and calling functions The functions that come with Python aren’t the only ones that can be used. To make a new function, collect the code you want to use in a special “wrapper” and give it a name. This name allows the function to be called whenever it is needed. 1 Define a function A colon marks the end 2 Call the function The definition of a function will always of the function’s name Typing the function name followed have the keyword “def” and the function’s and the start of the by parentheses into the shell window calls name at the beginning of the code. code it contains the function and shows the output. def greeting(): >>> greeting() print(‘Hello!’) Hello! This is the code The “greeting” Parentheses within the function function is called show that this is a function call, and the output not a variable is displayed

131F U N C T I O N S Passing data to functions A function has to be told which values to work with. For example, in “print(a, b, c)”, the function “print()” is being passed the values “a”, “b”, and “c”. In “height(1, 45)”, the values 1 and 45 are being passed to the function “height”. 1 Add parameters to the function 2 Values are defined Values passed to a function are called The code inside the function “parameters”. Parameters are put inside the parentheses uses the values that are passed to it. next to the function’s name in its definition. Calls the function to give “m” and “cm” are the parameters the answer when “m” = 1 and “cm” = 45 def height(m, cm): >>> height(1, 45) total = (100 * m) + cm 145 cm tall print(total, ‘cm tall’) To work out the total in Shows that 1 m 45 cm Prints the value of “total” “cm”, the value of “m” needs is equal to 145 cm followed by “cm tall” to be multiplied by 100 (because 1 m = 100 cm) Getting data back from functions Functions are most useful when they send some data back to the program—a return value. To make a function return a value, add “return” followed by the value to be sent back. 1 Define a function that returns a number The number 2 Number as output Python’s “input()” function always returns a string, is stored as a If the program used the function even if a number is entered. The new function below string in the “input”, “a + b” would put the strings “10” gives back a number instead. variable “typed” and “7” together to give “107”. def num_input(prompt): Enter a 10 Enter b 7 typed = input(prompt) a + b = 17 num = int(typed) return num Returns the value stored in the variable This converts the string a = num_input(‘Enter a’) into a number and stores Adding “a + b” outputs it in the variable “num” “17” because the function “num_input” b = num_input(‘Enter b’) gives back numbers, not strings print(‘a + b =’, a + b)

132 P L A Y I N G W I T H P Y T H O N SEE ALSO PROJECT 5  124–125 While Silly sentences loops Loops, functions, and lists can be used individually  128–129 Lists for lots of different tasks. They can also be used  130–131 Functions together to create interesting programs that can do even more complex tasks. Try using different words from the ones shown here to create Make silly sentences your own silly sentences. This program will make sentences by using three separate lists of words. It will pick one word from each list and put them together randomly in a silly sentence. Enter the three lists shown Single quotes show that each item in the 1 below into a new code window. This list is a string defines the lists that will be used to make the sentences. name = [‘Neha’, ‘Lee’, ‘Sam’] Square brackets verb = [‘buys’, ‘rides’, ‘kicks’] mean that this noun = [‘lion’, ‘bicycle’, ‘plane’] is a list Each sentence is made up of words picked This loads the function for generating a random 2 at random from the lists you have created. number (“randint”) Define a function to do this, because it will be used several times in the program. from random import randint Finds out how many words def pick(words): are in the list (the function works for lists of any length) num_words = len(words) Picks a random number num_picked = randint(0, num_words - 1) that refers to one of the items in the list word_picked = words[num_picked] return word_picked Stores the random word that has been picked in the variable “word_picked”

133S I L L Y S E N T E N C E S Print a random silly sentence by running Add an “a” so that the sentence makes sense 3 the “pick” function once for each of the (see below) three lists. Use the “print” command to show the sentence on the screen. print(pick(name), pick(verb), ‘a’, pick(noun), end=‘.\\n’) Save and run the program to get This adds a period at the end, while 4 a silly sentence made from the lists the “\\n” starts a new line of names, verbs, and nouns. Neha kicks a bicycle. The sentence is randomly selected each time the program is run Silly sentences forever! EXPERT TIPS A forever loop can be added to the silly sentences Readable code program to keep it running forever, or until the user presses “Ctrl-C” to escape the loop. It’s very important to write a program that can be easily The program keeps printing silly sentences understood. It makes the program easier to change in the future 1 if the “print” command is wrapped in a “while because you don’t have to start by solving the puzzle of how it works! True” loop. while True: Wraps the print command in a loop print(pick(name), pick(verb), ‘a’, pick(noun), end=‘.’) input() Prints a new sentence every time the “Enter” key is pressed The program will keep on creating random sentences The “input()” function 2 waits for the user to press Sam rides a lion. the “Enter” key before printing another sentence. Neha kicks a plane. Without this it would print Lee buys a bicycle. them too fast to read.

134 P L A Y I N G W I T H P Y T H O N SEE ALSO Tuples and dictionaries  110–111 Types Python uses lists for keeping data in order. It also has of data other data types for storing information called “tuples” and “dictionaries”. Data types such as these, which hold  128–129 Lists lots of items, are called “containers”. Tuples Tuples are a bit like lists, but the items inside them can’t be changed. Once a tuple is set up it always stays the same. Tuples are surrounded by brackets >>> dragonA = (‘Sam’, 15, 1.70) ◁ What is a tuple? >>> dragonB = (‘Fiona’, 16, 1.68) A tuple contains items separated by The items in a tuple are commas and surrounded by brackets. separated by commas Tuples are useful for collecting several bits of data together, such as a dragon’s name, age, and height. ▷ Grabbing an item from a tuple >>> dragonB[2] 1.68 To get an item from a tuple, use its position in the tuple (its index). This selects the item Tuples count from zero, just like from position 2 lists and strings. >>> name, age, height = dragonA ◁ Splitting a tuple into variables >>> print(name, age, height) Sam 15 1.7 Assign three variables to the tuple “dragonA”—“name“, “age“, and “height“. Python splits the tuple into three items, putting one in each variable. The items that make up the tuple Create a list of tuples Lists go in “dragonA” are displayed separately called “dragons” square brackets ▷ Putting tuples in a list >>> dragons = [dragonA, dragonB] >>> print(dragons) Tuples can be put into a list because [(‘Sam’, 15, 1.7), (‘Fiona’, 16, 1.68)] containers can go inside each other. Use this code to create a list of tuples. Each tuple is surrounded by Python displays all the items round brackets inside the that are in the list, not just list’s square brackets the names of the tuples

TUPLES AND DICTIONARIES 135 Dictionaries Dictionaries are like lists but they have labels. These labels, called “keys”, identify items instead of index numbers. Every item in a dictionary has a key and a value. Items in a dictionary don’t have to stay in a particular order, and the contents of a dictionary can be changed. ▷ Create a dictionary Dictionaries Items in a dictionary Use a colon between use curly are separated a key and a value This program creates a brackets by commas dictionary called “age”. The key for each item >>> age = {‘Mary’: 10, ‘Sanjay’: 8} is the name of a person. The value is their age. A key works in the A value stored in same way as an the dictionary (always index number comes after a colon) >>> print(age) Name of the dictionary ◁ Print the dictionary {‘Sanjay’: 8, ‘Mary’: 10} The order of the items can change, because the The key for this The value of positions of items in a item is ‘Sanjay’ ‘Mary’ is 10 dictionary are not fixed. Dictionary name New key ▷ Add a new item >>> age[‘Owen’] = 11 Adds a new item to A new value can be >>> print(age) the dictionary added to the dictionary by labeling it with the {‘Owen’: 11, ‘Sanjay’: 8, ‘Mary’: 10} new key. The new value is now The existing values in the dictionary are still there >>> age[‘Owen’] = 12 Assign a new value to the ◁ Change a value >>> print(age) item labeled ‘Owen’ Assign a new value to an existing key to change {‘Owen’: 12, ‘Sanjay’: 8, ‘Mary’: 10} its value. The value for ‘Owen’ This deletes the item has changed labeled ‘Owen’ ▷ Delete an item >>> del age[‘Owen’] The item labeled >>> print(age) ‘Owen’ no longer Deleting an item in a dictionary {‘Sanjay’: 8, ‘Mary’: 10} appears in the doesn’t affect other items because dictionary they are identified by their key, not by their position in the dictionary.

136 P L A Y I N G W I T H P Y T H O N SEE ALSO Lists in variables  108–109 Variables There’s something about how Python stores lists in Python in variables that might seem a bit odd at first. But take a look at what’s going on behind the scenes  128–129 Lists and it all makes sense. Remember how variables 2 only store values? 2 Variables are like boxes that hold values. ab The value in one variable can be copied and stored in another. It’s like photocopying △ How variables work the value contained in box “a” and storing Each variable is like a box containing a a copy in box “b”. piece of paper with a value written on it. 1 Assign a value to a variable >>> a = 2 This copies the contents Assign the value 2 to variable >>> b = a of “a” into “b” “a”, then assign the value in “a” to variable “b”. The value 2 is copied >>> print(‘a =’, a, ‘b =’, b) and stored in “b”. a=2b=2 Now “a” and “b” both This prints out the variable contain the value 2 names with their values 2 Change a value >>> a = 100 Change the value in “a” to 100 If you change the value stored in one variable it won’t affect the value >>> print(‘a =’, a, ‘b =’, b) stored in another variable. In the same way, changing what’s written on a piece a = 100 b = 2 of paper in box “a” won’t affect what’s on the paper in box “b”. Now “a” contains 100, but “b” still contains 2 3 Change a different value >>> b = 22 Change the value in “b” to 22. >>> print(‘a =’, a, ‘b =’, b) Variable “a” still contains 100. Even though a = 100 b = 22 the value of “b” was copied from “a” at the start, they are now independent— “b” now contains 22, changing “b” doesn’t change “a”. but “a” is still 100

137L I S T S I N V A R I A B L E S What happens if a list is put in a variable? Copying the value in a variable creates two independent Use square brackets copies of the value. This works if the value is a number, but to create a list what about other types of value? If a variable contains a list it works a bit differently. 1 Copy a list >>> listA = [1, 2, 3] This prints out the variable Store the list [1, 2, 3] in >>> listB = listA names alongside their values a variable called “listA”. Then to see what’s inside them store the value of “listA” in another variable called “listB”. >>> print(‘listA =’, listA, ‘listB =’, listB) Now both variables contain [1, 2, 3]. listA = [1, 2, 3] listB = [1, 2, 3] “listA” and “listB” both This changes the second item in the hold the same value list because lists count from zero 2 Change list A >>> listA[1] = 1000 Change the value in >>> print(‘listA =’, listA, ‘listB =’, listB) “listA[1]”to 1,000.“listB[1]” listA = [1, 1000, 3] listB = [1, 1000, 3] now contains 1,000 as well. Changing the original list has changed the copy of the list too. This is the third The second item of both item in the list “listA” and “listB” has been changed 3 Change list B >>> listB[2] = 75 Change the value of “listB[2]” to 75. “listA[2]” is now >>> print(‘listA =’, listA, ‘listB =’, listB) 75 as well. Changing the copy listA = [1, 1000, 75] listB = [1, 1000, 75] of the list has changed the original list as well. The third item of both “listA” and “listB” has been changed [1, 2, 3] EXPERT TIPS Copying lists listA listB To make a separate copy of a list, use the “copy” function. “listC” will contain a △ What’s going on? link to a completely new list whose values A variable containing a list doesn’t hold the list itself, are copies of those in “listA”. Changing just a link to it. Copying the value in “listA” copies the link. “listC” won’t change “listA”, and changing So both “listA” and “listB” contain a link to the same list. “listA” won’t change “listC”. >>> listC = listA.copy()

138 P L A Y I N G W I T H P Y T H O N Variables and functions SEE ALSO  130–131 Functions Variables created inside a function (local variables) Making 158–159 and variables created in the main program shapes (global variables) work in different ways. Local variables are like film stars Local variables in a car with mirrored windows— they are inside the car (function) but no one can see them Local variables only exist inside a single function, so the main program and other functions can’t use them. If you try to use a local variable outside of the function, an error message appears. 1 Variable inside the function 2 Variable outside the function The main program doesn’t Create a local variable called “a” If you try to print “a” directly know what “a” is, so it inside “func1”. Print out the value of “a” by from the main program, it gives an calling “func1” from the main program. error. “a” only exists inside “func1”. prints an error message >>> def func1(): >>> print(a) a = 10 Traceback (most recent call last): print(a) File “<pyshell#6>”, line 1, in <module> >>> func1() Calling “func1” print(a) prints the value NameError: name ‘a’ is not defined 10 given to “a” Global variables Global variables A variable created in the main program is are like people called a global variable. Other functions can read it, but they can’t change its value. walking along the 1 Variable outside the function 2 Same global variable street—everyone Create a global variable called “b” in the main program. The new function (“func2”) can can see them read the value of “b” and print it. We can also print “b” directly from the main program. “b” can be seen everywhere because it wasn’t created inside a function. >>> b = 1000 “func2” can see >>> print(b) >>> def func2(): the value of “b” 1000 because “b” is a print(b) global variable >>> func2() Global variable “b” can be used anywhere in 1000 Printing “func2” gives you the main program the value stored in “b”

139V A R I A B L E S A N D F U N C T I O N S Variables as input to functions When a variable is used as input to a function its value is copied into a new local variable. Therefore, changing the value of this new local variable inside the function doesn’t change the value of the original variable. 1 Changing values inside a variable 2 Print variable “func3” uses input “y”, which is a local Printing the value of “z” after calling “func3” shows variable. It prints the value of “y”, then changes it hasn’t changed. Calling “func3” copies the value in “z” that value to “bread” and prints the new value. (“butter”) into local variable “y”, but “z” is left unchanged. >>> def func3(y): “y” contains the >>> print(z) Prints the value in global print(y) value passed to butter variable “z” after “func3” has y = ‘bread’ it when “func3” finished running is called print(y) Here “y” contains Local variable “y” of “func3” holds a >>> z = ‘butter’ “bread” copy of the value in “z”. Although “y” >>> func3(z) has been changed to “bread”, the This creates a global value in global variable “z” isn’t variable called “z” affected and is still “butter” butter The input “y” now contains bread the value of “z” passed to it when “func3” is called Masking a global variable A global variable can’t be changed by a function. A function trying to change a global variable actually creates a local variable with the same name. It covers up, or “masks”, the global variable with a local version. 1 Changing a >>> c = 12345 Initial value EXPERT TIPS global variable in global Global variable “c” is given Calling functions the value 12345. “func4” >>> def func4(): variable “c” gives “c” the value 555 There are two different ways of and prints it out. It looks c = 555 calling functions. like our global variable “c” has been changed. print(c) function(a) 2 Print variable >>> func4() Prints the In Python, items of data are called If we print “c” from 555 value of “c” “objects”. Some functions are called by outside the function, we inside “func4” passing them the data object (“a”). see that “c” hasn’t changed at all. “func4” only prints >>> print(c) a.function() the value of its new local 12345 variable—also called “c”. Other functions are called by adding The value in global their name at the end of the data variable “c” hasn’t object (“a”) after a period. been changed

140 P L A Y I N G W I T H P Y T H O N SEE ALSO PROJECT 6  122–123 Loops Drawing machine in Python It’s time to try a more complex project. This program, the Libraries 152–153 drawing machine, turns a string of simple instructions into turtle commands to draw different shapes. The skills used in planning this program are essential for any coder. Choose a test shape from turtle import * To write a program that can draw any shape, reset() Loads all the commands it’s useful to choose a shape to start with. Use left(90) that control the turtle this house shape as an example to test the program at each stage. By the end of the forward(100) Resets the turtle’s position project it will be possible to draw this house right(45) and puts the pen down with far less code—by using a single string ready to draw containing several short drawing commands (for example, “F100”). forward(70) right(90) Moves the turtle forward(70) forward by 70 right(45) Makes the turtle turn forward(100) 90 degrees to the right right(90) ▷ Turtle draws a house forward(100) The arrow shows the final The turtle △ Program to draw a house direction and position of the This code tells the turtle to draw a house. turtle. Starting at the bottom It requires lots of lines of code for what is left, it has moved clockwise actually quite a simple program. around the house. Three parts Function 1 Function 2 Main program of the program △ Turtle controller △ String artist △ User interface The drawing machine will be a large program. To help This function takes a In this program, the The String artist needs with the planning, it can be simple command from user enters a string to get its input from broken down into three the user and turns it into of instructions. This somewhere. The User parts, each one related to a turtle command. The function splits the string interface allows the user a different task. user command will into smaller units, which to type in a string of come as a single letter are then fed to the commands for the String and a number. Turtle controller. artist to work on.

141D R A W I N G M A C H I N E Draw a flowchart EXPERT TIPS Coders often plan programs on paper, to help them write Squares and diamonds better code with fewer errors. One way to plan is to draw a flowchart—a diagram of the steps and decisions that Flowcharts are made up of squares the program needs to follow. and diamonds. The squares contain actions that the program This flowchart shows the plan for the performs. The diamonds are points where it makes a decision. 1 Turtle controller function. It takes a letter (input “do”) and number (input Action Decision “val”) and turns them into a turtle command. For example, “F” and “100” inputs—do and val will be turned into the command “forward(100)”. If the function doesn’t do == F? Y If “do” = F, the turtle recognize the letter, it reports an Y moves forward error to the user. N forward(val) Each command has two variables: do == R? “do” (a string) tells the turtle what If “do” = R, the turtle to do, and “val” (an integer, or turns right whole number) tells the turtle how much or how far to do it right(val) The function has to decide if the “do” value is a letter it recognizes If “do” isn’t F, the function runs through other letters it recognizes EXPERT TIPS “do” isn’t “R”. N Is it “U”? Letter commands Y The Turtle controller will use do == U? penup() these letters to stand for different turtle commands: N If “do” isn’t a letter Because “do” the function is “U”, the N = New drawing (reset) report unknown command recognizes, it command U/D = Pen up/down reports an error “penup()” F = Forward stops the B = Backwards turtle from R = Right turn drawing L = Left turn return from function Once the After any command is command is finished executed successfully, you return to the the program goes to main program the end of the function

142 P L A Y I N G W I T H P Y T H O N DRAWING MACHINE The Turtle controller Loads all the commands that control the turtle The first part of the program is a function that moves the turtle, one command at a time. It is planned out in the flowchart on the previous page. This code enables the turtle to convert the “do” and “val” values into movement commands. This code creates the Turtle from turtle import * Defines “do” and “val” as inputs for the function 2 controller function. It turns “do” def turtle_controller(do, val): inputs into directions for the turtle, and “val” inputs into do = do.upper() angles and distances. if do == ‘F’: This command converts all This command tells forward(val) the letters in “do” to upper the turtle to start case (capital letters) drawing on the page elif do == ‘B’: This tells the function to turn backward(val) a “do” value of F into the The starting turtle command “forward” position of elif do == ‘R’: the turtle right(val) As in the flowchart, the function Here are some examples of how elif do == ‘L’: checks the “do” letter against all the letters it understands 3 to use the Turtle controller. Each left(val) elif do == ‘U’: This command instructs time it is used, it takes a “do, val” the turtle to stop drawing command and turns it into code penup() on the page the turtle can understand. elif do == ‘D’: This command resets the pendown() turtle’s position to the center of the screen elif do == ‘N’: reset() This message appears if the “do” value is a letter that the else: function cannot recognize print(‘Unrecognized command’) This calls the function These “do” and “val” using its name inputs tell the turtle to move 100 steps forward >>> turtle_controller(‘F’, 100) This makes the >>> turtle_controller(‘R’, 90) turtle turn right >>> turtle_controller(‘F’, 50) 90 degrees

143D R A W I N G M A C H I N E Write some pseudocode EXPERT TIPS Another way to plan a program is to write it in Clear coding pseudocode. “Pseudo” means fake, so pseudocode isn’t real code that you can run. It’s rough code where you can It’s not only computers that need write your ideas in the style of the real thing. to be able to read your code, it should be clear to people too. So It’s time to plan the String artist. This function takes a it’s important to make your code as easy to understand as possible. 4 string of several “do” and “val” inputs and breaks it into pairs made up of a letter and a number. It then passes Use functions to break your code into smaller chunks. Each function should the pairs to the Turtle controller one at a time. do a single task in the program. Give your variables and functions Broken-down F100-R90-F50-R45 String of names that say what they do: “age_in_ string drawing years” makes more sense than “aiy”. commands Use plenty of comments (using the “#” symbol) to explain what’s ‘F’ 100 ‘R’ 90 ‘F’ 50 ‘R’ 45 happening. This makes it easier to read back over the code. This is the String artist written in pseudocode. Don’t use symbols that can be confused with others: an upper-case 5 It lets you organize the ideas and structure of the “O” looks like zero, and a lower-case “L” code without having to think about the details yet. can look like an upper-case “i” or a “1”. function string_artist(input—the program as a string): The function will take in a string split program string into list of commands of commands input by the user for each command in list: (for example, “F100-R90”) check it’s not blank —if it is go on to next item in list Splits string into command type is the first letter a list of separate if followed by more characters commands —turn them into a number call turtle_controller(command type, number) A blank command won’t work, so the function skips it Recognizes the first letter as a “do” command Recognizes the following characters as a “val” number Passes the simple command to Turtle controller

144 P L A Y I N G W I T H P Y T H O N DRAWING MACHINE Creating the String artist The pseudocode on the previous page plans a function called the String artist, which will turn a string of values into single commands that are sent to the Turtle controller. The next stage is to turn the pseudocode into real Python code, using a function called “split()”. The “split()” function splits a string into a list of This string lists the commands to create the 6 smaller strings. Each break point is marked by a sample house shape special character ( “-” in this program). >>> program = ‘N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100’ >>> cmd_list = program.split(‘-’) The “split()” function breaks the string >>> cmd_list down into a list of separate commands [‘N’, ‘L90’, ‘F100’, ‘R45’, ‘F70’, ‘R90’, ‘F70’, ‘R45’, ‘F100’, ‘R90’, ‘F100’] Now write out the pseudocode for the String artist Tells the program to split the string wherever it sees a “-” character 7 using real Python code. Use the “split()” function to slice up the input string into turtle commands. This makes the program loop through the list of strings—each item def string_artist(program): is one command for the turtle cmd_list = program.split(‘-’) If the length of the command is 0 (so for command in cmd_list: the command is blank), the function skips it and moves to the next one cmd_len = len(command) Gets the if cmd_len == 0: Takes the first character of the command length of the continue (remember, strings start at 0) and sets it as the command type (“F”, “U”, etc.) command cmd_type = command[0] string This takes all the remaining characters from the command num = 0 Checks if the command by cutting off the first one if cmd_len > 1: is followed by more Prints the command on the screen so you can see what characters (the number) the code is doing Converts the num_string = command[1:] characters from strings into num = int(num_string) numbers print(command, ‘:’, cmd_type, num) turtle_controller(cmd_type, num) Passes the command to the turtle

145D R A W I N G M A C H I N E When the string representing the instructions for 8 the house shape is passed into the String artist, it shows this output in the shell window. >>> string_artist(‘N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100’) N:N0 Resets the screen and puts The turtle commands L90 : L 90 the turtle back at the center are all separated by a “-” F100 : F 100 For command “F100”, the command R45 : R 45 type is “F” and “num” is “100” F70 : F 70 This makes the turtle turn 45 R90 : R 90 degrees before drawing the roof F70 : F 70 This command makes the R45 : R 45 turtle draw the right-hand F100 : F 100 side of the roof R90 : R 90 The turtle turns 90 degrees F100 : F 100 right, ready to draw the bottom of the house Each command in the F70 R90 REMEMBER F70 9 string that is passed to the R45 Commands “string_artist” function is F100 extracted, identified, and Here’s a reminder of the turtle executed. A picture of a commands in this program. Some house is drawn in the turtle of these are only one letter long, graphics window. while others include a number telling the turtle how far to travel R45 or turn. Each time you activate “string_artist”, it adds to the F100 drawing, until “N” clears the screen. L90 N = New drawing U/D = Pen Up/Down The program F100 F100 = Forward 100 makes the turtle B50 = Backwards 50 R90 R90 = Right turn 90 deg draw a house L45 = Left turn 45 deg

146 P L A Y I N G W I T H P Y T H O N DRAWING MACHINE Finish off the code with a user interface The drawing machine needs an interface to make it easier to use. This will let the user enter a string from the keyboard to tell the machine what to draw. This code creates a pop-up window where the The triple quote (‘‘‘) tells Python that everything until the next triple quote 10 user can input instructions. A “while True” loop is part of the same string, including the line breaks lets them keep entering new strings. instructions = ‘‘‘Enter a program for the turtle: eg F100-R45-U-F100-L45-D-F100-R90-B50 N = New drawing U/D = Pen Up/Down Tells the user what letters F100 = Forward 100 to use for different turtle B50 = Backwards 50 commands R90 = Right turn 90 deg End of the string L45 = Left turn 45 deg’’’ screen = getscreen() Gets the data needed to This line tells the program while True: create the pop-up window what to show in the pop-up window t_program = screen.textinput(‘Drawing Machine’, instructions) print(t_program) if t_program == None or t_program.upper() == ‘END’: break Stops the program string_artist(t_program) Passes the string to the if the user types String artist function “END” or presses the “Cancel” button This window pops Drawing Machine △ Turtle control 11 up over the turtle Enter a program for the turtle: Using this program, the turtle is window ready for eg F100-R45-U-F100-L45-D-F100-R90-B50 easier to control, and you don’t the user to type a N = New drawing have to restart the program to drawing machine U/D = Pen Up/Down draw another picture. program string. F100 = Forward 100 B50 = Backwards 50 Type the program string R90 = Right turn 90 deg here and then click “OK” L45 = Left turn 45 deg to run the program OK Cancel

147D R A W I N G M A C H I N E The drawing machine can be used to create more than 12 just outlines. By lifting up the turtle’s pen while moving to a new position, it’s possible to fill in details inside a shape. Run the program and try entering the string below. N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100- B10-U-R90-F10-D-F30-R90-F30-R90-F30-R90-F30 Lifts up the turtle’s Puts the pen down to pen so it moves draw a window without leaving a line The house now has a window Time for something different Now you know how to add details, you can really have fun with the drawing machine. Try drawing this owl face using the string of instructions below. N-F100-L90-F200-L90-F50-R60-F30-L120-F30-R60-F40- R60-F30-L120-F30-R60-F50-L90-F200-L90-F100-L90-U- F150-L90-F20-D-F30-L90-F30-L90-F30-L90-F30-R90-U- F40-D-F30-R90-F30-R90-F30-R90-F30-L180-U-F60-R90- D-F40-L120-F40-L120-F40 The string lifts the pen The arrow shows where the three times to draw the turtle stopped. This means that eyes and beak separately the owl’s beak was drawn last REMEMBER Created the function “turtle_controller” that works out what turtle command to execute from the letter Achievements and number it’s been given. You created the drawing machine program Created the function “string_artist” that produced by achieving several smaller targets: a turtle drawing from a string of instructions. Used a flowchart to plan a function by working out Made an interface that allows the user to tell the decision points and the resulting actions. the program what to draw from the keyboard. Wrote pseudocode to plan out a function before writing out the real code.

148 P L A Y I N G W I T H P Y T H O N SEE ALSO Bugs and debugging  94–95 Errors  122–123 Loops Programmers aren’t perfect, and most programs contain errors at first. These errors are known as in Python “bugs” and tracking them down is called “debugging”. What next? 176–177 Types of bugs Three main types of bugs can turn up in programs—syntax, runtime, and logic errors. Some are quite easy to spot, while others are more difficult, but there are ways of finding and fixing them all. The Python keyword This will cause Age cannot be less than 5 is ”for” not “fir” an error as no and greater than 8 at the number can be same time, so no free tickets divided by 0 fir i in range(5): a=0 if age < 5 and age > 8: print(10 / a) print(‘Free ticket!’) print(i) △ Harder to spot △ Hardest to spot △ Easy to spot A syntax error is a mistake in the Runtime errors appear only Logic errors are mistakes in a program’s program’s words or symbols, such when the program is running. thinking. Using “<” instead of “>”, for as misspelled keywords, missing Adding numbers to strings or example, or adding when you should be brackets, or incorrect indents. dividing by 0 can cause them. subtracting result in these errors. Find and fix a bug Syntax errors are easy to spot because IDLE highlights them in red when you run the program. Finding runtime and logic errors takes a bit more work. 1 Problem top_num = 5 The highest number in the series program total = 0 of numbers being added This program aims to for n in range(top_num): This command prints a sentence add all the numbers total = total + n to let the user know the result from 1 up to the value stored in the variable print(‘Sum of numbers 1 to’, top_num, ‘is’, total) “top_num”. It then prints the total. 2 Output Sum of numbers 1 to 5 is 10 The answer for the program should be (1 + 2 + 3 + 4 + 5), but it shows the The answer should be “15”, not “10” answer as “10”. You need to find out why.


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook