Cont ent s This Workbook.............................................. Workbook............................................................................... ................................. .................................. ......................... ..... + elp................................... ................................. ................................. ............................ ............. ...... ............. ............ ........ + (et -rganised............................................................................................................................................+ Contents................................................. ................................. ................................. .................................. ... nputting information and strings................................................................................................................../ print01 function.............................................. ................................. .................................. ....................... ................ .......... ... / nput01 function............................................. function.............................................................................. ................................. .................................. ................ .......... ............. .......... ... / 2ariables.......................................... .................................. ................................. .................... ............. ...... ............. ...... / )tring.................................. .................................. ................................. ................................ ............. ...... ............. ........ / Challenge + 3 Write a program that4....................................................................................................../ Challenge 3 Write a program that4....................................................................................................../ Working with NT and '%-5T to handle numbers in "ython...........................................................................6 Challenge 7 3 Write a program that4......................................................................................................6 2ariables......................................... .................................. ................................. .................... ............. ...... ............. .......... .... 8 *xtension............................................. ................................. .................................. ......................... ................... ............. ....... 9 !aking the program pause between messages............................................................................................ )ome more about )trings..............................................................................................................................; Challenge ; < am an excellent programmer..........................................................................................; ow to use "ython for math calculations....................................................................................................+= -perands............................................................................... -perands.............................................. ................................. ................................. ................. ........... ............. ............. ............ ...... ++ Challenge +8 3 >estaurant >estaurant Tip............................................. .................................. ...................... .......... ...... .... ++ !aking decisions in program................................................ program................................................................................. ................................. ................................ ...... + Challenge +9 < !agic ?all..................................................................................................................+ Comparison -perators.............................................. -perators................................................................................ .................................. ......................... ............ ...... ............. ........... .... +7 ndenting...................................... ................................. .................................. ................................. ........... ........ ... +7 !ore advanced ways to use an if................................................................................................................+/ Challenge + < !ega )ale.....................................................................................................................+8 Challenge < appy !essage............................................................................................................+8 Challenge 7 < !obile "hone Costs.......................................................................................................+8 Challenge / < )ecret password...........................................................................................................+8 ?oolean or logical expression.............................. expression.............................. ................................. .................................. ..................... ............... ...... +9 Challenge 6 < 'or loops.......................................................................................................................+9 Challenge 8 < 'or loops.......................................................................................................................+9 Challenge 9 < Times Table using 'or loops..........................................................................................+9 'or loops are really clever........................................ .................................. ............................. ............. ....... ............. ....... + Challenge < >eading a sentence......................................................................................................+ Conditional %oops................................................... .................................. ................................. .................. ............. ..... + Challenge ; < While loops...................................................................................................................+ 2alidation............................................. alidation............................................................................... .................................. ................................. ........................ ................. ............. ............ ...... +;
t h ec o mp mp ut i n g. z o ne
Cont ent s This Workbook.............................................. Workbook............................................................................... ................................. .................................. ......................... ..... + elp................................... ................................. ................................. ............................ ............. ...... ............. ............ ........ + (et -rganised............................................................................................................................................+ Contents................................................. ................................. ................................. .................................. ... nputting information and strings................................................................................................................../ print01 function.............................................. ................................. .................................. ....................... ................ .......... ... / nput01 function............................................. function.............................................................................. ................................. .................................. ................ .......... ............. .......... ... / 2ariables.......................................... .................................. ................................. .................... ............. ...... ............. ...... / )tring.................................. .................................. ................................. ................................ ............. ...... ............. ........ / Challenge + 3 Write a program that4....................................................................................................../ Challenge 3 Write a program that4....................................................................................................../ Working with NT and '%-5T to handle numbers in "ython...........................................................................6 Challenge 7 3 Write a program that4......................................................................................................6 2ariables......................................... .................................. ................................. .................... ............. ...... ............. .......... .... 8 *xtension............................................. ................................. .................................. ......................... ................... ............. ....... 9 !aking the program pause between messages............................................................................................ )ome more about )trings..............................................................................................................................; Challenge ; < am an excellent programmer..........................................................................................; ow to use "ython for math calculations....................................................................................................+= -perands............................................................................... -perands.............................................. ................................. ................................. ................. ........... ............. ............. ............ ...... ++ Challenge +8 3 >estaurant >estaurant Tip............................................. .................................. ...................... .......... ...... .... ++ !aking decisions in program................................................ program................................................................................. ................................. ................................ ...... + Challenge +9 < !agic ?all..................................................................................................................+ Comparison -perators.............................................. -perators................................................................................ .................................. ......................... ............ ...... ............. ........... .... +7 ndenting...................................... ................................. .................................. ................................. ........... ........ ... +7 !ore advanced ways to use an if................................................................................................................+/ Challenge + < !ega )ale.....................................................................................................................+8 Challenge < appy !essage............................................................................................................+8 Challenge 7 < !obile "hone Costs.......................................................................................................+8 Challenge / < )ecret password...........................................................................................................+8 ?oolean or logical expression.............................. expression.............................. ................................. .................................. ..................... ............... ...... +9 Challenge 6 < 'or loops.......................................................................................................................+9 Challenge 8 < 'or loops.......................................................................................................................+9 Challenge 9 < Times Table using 'or loops..........................................................................................+9 'or loops are really clever........................................ .................................. ............................. ............. ....... ............. ....... + Challenge < >eading a sentence......................................................................................................+ Conditional %oops................................................... .................................. ................................. .................. ............. ..... + Challenge ; < While loops...................................................................................................................+ 2alidation............................................. alidation............................................................................... .................................. ................................. ........................ ................. ............. ............ ...... +;
t h ec o mp mp ut i n g. z o ne
Comments.................................................. ................................. .................................. .......................... .... = "lanning the >ock, "aper, )cissors (ame.................................................................................................... 'unctions........................................ 'unctions........................................ .................................. ................................. .................................. ........ / "assing 'unctions a 2alue by using "arameters..........................................................................................9 !ethod +........................................... .................................. ................................. ............................ ........ ...... .. 9 !ethod ........................................... .................................. ................................. ............................ ........ ...... .. 9 !ethod 7........................................... .................................. ................................. ............................ ........ ...... .. (lobal variables............................................ variables............................................................................. ................................. ................................ ............. ...... ............. ............. .......... ... %ists.................................................................................. %ists................................................. ................................. .................................. ................................. ........ ; !ore lists.......................................... ................................. .................................. ................................. ....... 7= )licing lists........................................ ................................. ................................. ...................... ............. ....... ........... ..... 7= 5dding to a list...................................... ................................. .................................. ......................... ................... ............. .......... ... 7= @eleting from a list......................................... .................................. ................................. ...................... .... 7+ >andom choice from a list............................... .................................. ................................. ......................... .................. ....... 7+ @ictionaries....................................................... ................................. ................................. ................... ............. ........... ..... 7 Writing to and reading from a $le.................................. ................................. ................................. ............ 7/ Writing a %ist to a 'ile.............................. 'ile.............................. .................................. ................................. ......................... ........ ...... .. 7/ >eading from a 'ile............................... .................................. ................................. .................................. .. 76 "ickling and )helving %ists..........................................................................................................................79
t h ec o mp mp ut i n g. z o ne
I nput t i ngi nf or mat i onandst r i ngs pr i nt ( )f unct i on The print function prints prints information to the screen. Type this in: print (“Hello World”) World”)
I nput ( )f unct i on The input function allows allows the user to enter information information into the computer computer.. Type Type this in: name = input("Hi. What's your name? ") print ("Hello, ", name) name)
Var i abl es 5 variable is used in a program to store information. information. n the program above the variable is name. ?ecause the variable is in Auotes B or D&, the variable type is called a string.
St r i ng 5 string can contain letters, characters and numbers.
Chal l enge1-Wr i t eapr ogr am t hat …. +. 5sks for for the the $rst name and and then then a surna surname. me. . "rint "rint the 'irst 'irst name name and then then the second second name. name. 7. -n the next next line print print the second second name name and then the the $rst name. name. Ese variable names: $rstName surnameName )ave as: Challenge + 3 Names *xtension: The name may not have a space between $rst and second namesF can you work out how to add oneG )trings can be Hoined together:
Cha l l e nge2-Wr i t eapr ogr a mt ha t … Ese a new variable fullName.
5dd to your program:
fullName = rstName surnameName print (fullName)
Ioining strings together together is known as:
t h ec o mp mp ut i n g. z o ne
Wor ki ngwi t hI NTandFLOATt ohandl enumber si nPyt hon We have used the input command to ask the user to enter text. We&re going to use this again but with numbers. What do you think this code will doG
Cha l l e nge3-Wr i t eapr ogr a mt ha t … Type this in: num!erne = input(“#nter a num!er !et$een % and &%”) num!er$o = input(“#nter a num!er !et$een % and &%”) rint (num!erne num!er$o) What happenedG Why do you think this happenedG
Chal l enge4–Changet hePr ogr am Type this in: num!erne = int(input(“#nter a num!er !et$een % and &%”)) num!er$o = int(input(“#nter a num!er !et$een % and &%”)) rint (num!erne num!er$o) Type in 6 and 6 as your numbers to test your program Type in 6.6 and /.6 to test your program again. Jou should receive an error message. What happenedG Why do you think this happenedG
Chal l enge5–Changet hePr ogr am Type this in: num!erne = oat(input(“#nter a num!er !et$een % and &%”)) num!er$o = oat(input(“#nter a num!er !et$een % and &%”)) print (num!erne num!er$o)
Type in 6 and 6 as your numbers to test your program Type in 6.6 and /.6 to test your program again. Jou should receive an error message. What happenedG Why do you think this happenedG
t h ec o mp ut i n g. z o ne
Var i abl es What is a variableG
Variable Type
Description of what type of data this variable type can store
)tring nteger 0int1 'loat Data 6 %ondon .9797 +====== !r )mith =.==; 'ox 7/ x /6 =
What variable type is suitable?
Take a look at the program below: & + 0 1 3 8 9 : &% && &+
me*a sale sales-mount = oat(input(“#nter the amount of money spent in / “)) if sales-mount 2 +%/ print(“4ou 5ualify for a 6ou7her”) elif sales-mount 2 &%/ print(“4ou 5ualify for a & 6ou7her”) else/ print(“4ou didn;t spend enou*h for a 6ou7her<”)
'ollowing the program through, if the variable sales5mount has the value in the table, write down what will be printed in each case.
salesAmount 6 +6 6
What will be printed?
t h ec o mp ut i n g. z o ne
+= ++ +
Chal l enge6–Cal or i eCount er Now let&s build a calorie counter. The N) recommends that an adult male takes on board ,6== calories per3day and an adult woman takes on ,=== calories per3day. ?uild your program for a woman or a man. )ave your program as CalorieCounter . print("4> N-#;s 7alorie 7ounter") 7alories = int(input("Ho$ many 7alories ha6e you eaten today?")) s=+%%%@7alories print("4ou 7an eat", s, "more 7alories today")
%ine asks the user to enter how many calories they have eaten as the variable c. t stores it as an integer 0whole number1 %ine 7 of the code subtracts how many calories they&ve eaten and stores it as the variable s %ine / then prints out s in between &strings& of text
Ex t e ns i on Write a program that asks the user to enter how much they have spent on their school dinner. t should subtract how much they&ve spent from the amount they had
t h ec o mp ut i n g. z o ne
Maki ngt hepr ogr am pausebet weenmessages The program works but it&s very fast so we can add some delays in to make it more user friendly. "ython doesn&t have all of the commands we need but we can add some like this: import time print("4> N-#;s 7alorie 7ounter") time.sleep() 7alories = int(input("Ho$ many 7alories ha6e you eaten today?")) s=+%%%@7alories print("4ou 7an eat", s, "more 7alories today")
%ine 7 tells the program to pause for 7 seconds before moving onto the next line of code. Try 5dding your own delays into the program to see how it can make it a better program for the user.
Now try these challenges. Think carefully < what type of variable will you need to useG When you do these next tasks remember that by default variables are strings.
Chal l enge7–Ar eaCal cul at or Iennifer wants to carpet her new room with pink carpet. Create a program that will work out the area of any siKed room, 0length x width1. )ave as )Auare .
Cha l l e nge8–Da y sAl i v eCa l c ul a t or Write a program to work out how many days you have been alive for 0to the nearest year for the moment 3 there are 786 days in a year1 (et the program to ask for the person&s name and age. @evelop this to work out how many hours this is < / hours per day @evelop it further to work out how many minutes and seconds you have lived for < 8= minutes per hour # 8= seconds per minute. !ake sure the information is clearly displayed on the screen. )ave as 5ge
t h ec o mp ut i n g. z o ne
Somemor eaboutSt r i ngs )trings are variables that contain letters, numbers and symbols. There are lots of things that can be done with strings.
Chal l enge9–Iam anexcel l entpr ogr ammer Type this in: Luote M B am an *C*%%*NT programmer print 0Luote1 What is shown on the screen should be the same as you typed in. Now try changing your program to this: Type this in: Luote M B am an *C*%%*NT programmer "rint 0Luote.lower011 This is known as a string method Then instead of lower use these methods and write down what happens: !tring "ethod lower01 upper01 title01 swapcase01 capitaliKe01
Description of what it does
Chal l enge10–Concat enat i on )trings can be Hoined together < which is called concatenation. Write a programme that asks for 7 gifts that someone would like for Christmas. 5dd the variables 0something like this1 :giftTotal M gift+ O gift O gift7 Then print the variable giftTotal 0make sure there are spaces between each word1 )ave as Christmas (ifts *ift& = input(“What *ift $ould you liAe most”) *ift+ = *ift = *iftotal = *ift&*ift+*ift
t h ec o mp ut i n g. z o ne
t h ec o mp ut i n g. z o ne
How t ousePyt honf ormat hcal cul at i ons %et&s look at how python calculates using numbers.
Chal l enge11–Mul t i pl i cat i on %et&s see how much a student spends on food at school. @o you remember why we have to use int or #oat G)ave as 'ood spending food = oat(input(“Ho$ mu7h do you spend on lun7htime food in an a6era*e day?”)) food = food B1 “ “
Cha l l e nge1 2–Di v i di ng 5n 5unt wins on the lottery. )he gives P+=== to you. Jou are thinking of sharing it with some of your family. ow much would each person get 0try diQerent numbers of people to share it with1. )ave as: sharing my money out. To get you started: shares = int(input(“Ho$ many people do you $ant to share the money $ith?”)) money = &%%% C ???? nish this oD
Chal l enge13–Modul us f we divide two numbers and they don&t divide evenly we get a remainder. !odulus gives us the remainder of a sum. 'or example 9# M 7 with remainder +. Try this: Erint (8 F +)
Jou should get the answer +. Try some other numbers to see what you get.
Cha l l e nge14–Addi t i on 5ddition is easy. Try this: len*th = &% len*th = len*th +%
Jou should get the answer +. Try some other numbers to see what you get. 5nother way of writing this in python is: len*th = &% len*th = +%
Test it out. t&s Hust Auicker to writeR
t h ec o mp ut i n g. z o ne
Oper ands The O, 3, #, S symbols are called operators. That&s because they Boperate on the numbers. $perator SM #M UM OM 3M
%&le SM6 #M6 UM6 OM6 3M6
's %quivalent to M S6
Chal l enge15-For mat t i nghow number sar epr i nt edont hescr een "rinting information out accurately with the right number of digits is important. Type this program in and see what happens to the number of numbers printed after the decimal point. nne = .&+01389: n$o = :.98310+& ans =(nneBn$o) print (ans)
"rints:
rounds the ans$er to dps print (round(ans, +))
"rints:
addin* a Gero to a de7imal n =&.& print ("F%.+f"F (n))
"rints:
Cha l l e nge1 6-Re st a ur a ntTi p The basics Two people eat dinner at a restaurant and want to split the bill. The total comes to P+== and they want to leave a +6U tip. ow much should each person payG T". Jou can calculate an increase by multiplying the meal cost by +.+6. (arder !ake the program ask how many people there are, what percentage the tip should be and how much the bill comes to. (arder still These diners would like to go home in a taxi. The taxi costs P=./6 per mile. Can you work out the taxi costs 0the user should be able to input the distance they have to travel1 and how much the complete evening has cost overall and per personG
t h ec o mp ut i n g. z o ne
Maki ngdeci si onsi npr ogr am "ython can make decisions based on the input. To make decisions, programs check to see if a condition is true or not. "ython has a few ways to test something, and there are only two possible answers for each test: true or false.
Chal l enge17–Magi c8Bal l The code below will use "ython&s random number generator to make a magic ball game. !ake this game and save it as "agic)*all. import random ans$er&=(“-!solutely<”) ans$er+=(“No $ay Eedro<”) ans$er=(“o for it ti*er.”) print(“Wel7ome to the a*i7 9 Iall *ameJuse it to ans$er your 5uestions...”) 5uestion = input(“-sA me for any ad6i7e and K;ll help you out. ype in your 5uestion and then press #nter for an ans$er.”) print(“shaAin*.... Ln” B 0) 7hoi7e=random.randint(&,) if 7hoi7e == &/ ans$er=ans$er& elif 7hoi7e == +/ ans$er=ans$er+ else/ ans$er=ans$er print(ans$er)
'or testing whether two things are eAual "ython uses a double eAual sign 0MM1. @escribe below what each line of code is doing:
t h ec o mp ut i n g. z o ne
Compar i sonOper at or s These comparison operators are important to learn and use correctly. (etting a symbol wrong will mean that the program does the wrong thingR +omparison $perators MM RM V M VM
What the symbols mean
are two things eAualG are two things not eAualG less than greater than greater than -> eAual to less than -> eAual to
Cha l l e nge1 8–I f %et&s write a program that compares two numbers. )ave this as: compare numbers num& = oat(input("#nter the rst num!er/ ")) num+ = oat(input("#nter the se7ond num!er/ ")) if num& 2 num+/ print (num&, " is *reater than ", num+) if num& M num+/ print (num+, " is *reater than", num&) if num& == num+/ print (num&, "is e5ual to", num+)
This tests each combination and does something 0prints a line out1 if the test is T-% "ython can do other things if the test is /A0!%: @o another test < f the test is 'alse we can get "ython to another test: we use elif 0short for Belse if1 @o something else < f all the other tests come out false do something else: we •
•
t h ec o mp ut i n g. z o ne
Chal l enge19 We can re3write the code to use these features: num& = oat(input("#nter the rst num!er/ ")) num+ = oat(input("#nter the se7ond num!er/ ")) if num& 2 num+/ print (num&, " is *reater than ", num+) elif num& M num+/ print (num+, " is *reater than", num&) else/ print (num&, "is e5ual to", num+)
Why do we not need to test if num+MMnum but can print out: print (num&, "is e5ual to", num+) knowin it to be T>E*G
I ndent i ng ndenting is very important in "ython, it&s a necessary part of how you write the code. ndenting tells "ython where blocks of code start and where they end. The "ython @* will do this for you < Hust be aware what it is doing.
Mor eadvancedwayst ouseani f We might have a case where we want someone to type in an " or / to say if they are male or female. )o we could write: if 7hoi7e == ””/
?ut what if they type in a lowercase m this wouldn&t workR We could use: if 7hoi7e == "" or 7hoi7e == "m"/
This would work $ne but the code is getting long and harder to read and understand. 5 better way is to see if the variable is in a list of possible options:
t h ec o mp ut i n g. z o ne
Chal l enge20–Advancedi f Esing the following code as a basis: 7hoi7e = input("-re you male or female") if 7hoi7e in ("", "m")/ print ("We ha6e a spe7ial oDer of &%F oD *roomin* produ7ts for men today")
@evelop the code above to give a message to men and women about special oQers on sale in )uper@rug the chemists. !en get +=U oQ grooming products today, women get a free manicure. !en can type in male, ! or m and women female, ' or f. )ave as: beauty oQer %&tension 1ot equal to What if you want to do something when a value isn2t in a listG 7hoi7e = input("-re you male or female") if 7hoi7e not in ("", "m", "male","ale","", "f", "female", "emale")/ print ("Oorry you ha6e not made a 6alid 7hoi7e")
*xtend your code to allow for this option.
t h ec o mp ut i n g. z o ne
%ooking at the code below explain why the 0$3'+ is wrong in this example:
& me*a sale + sales-mount = oat(input(“#nter the amount of money spent in / “)) if sales-mount 2 &%/ 0print(“4ou 5ualify for a & 6ou7her”) 1if sales-mount 2 +%/ 3print(“4ou 5ualify for a 6ou7her”) 8else/ 9 print(“4ou didn;t spend enou*h for a 6ou7her<”)
%ooking at the code below explain why the 0$3'+ is wrong in this example:
& me*a sale + sales-mount = oat(input(“#nter the amount of money spent in / “)) if sales-mount 2 &%/ 0print(“4ou 5ualify for a & 6ou7her”) 1elif sales-mount 2 +%/ 3print(“4ou 5ualify for a 6ou7her”) 8else/ 9 print(“4ou didn;t spend enou*h for a 6ou7her<”)
%ooking at the code below explain if the 0$3'+will work in this example:
& me*a sale + sales-mount = oat(input(“#nter the amount of money spent in / “)) if sales-mount 2 +%/ 0print(“4ou 5ualify for a 6ou7her”) 1elif sales-mount 2 &%/ 3print(“4ou 5ualify for a & 6ou7her”) 8else/ 9 print(“4ou didn;t spend enou*h for a 6ou7her<”)
t h ec o mp ut i n g. z o ne
Chal l enge21–MegaSal e 5 local shop is having a promotion. f you spend over P+= you will get a P+ voucher to spend next time you come in the store. f you spend over P= you get a P7 voucher. Write a program to tell the sales assistant which voucher to give the customer. )ave this as: megasale
Chal l enge22–HappyMess age Write a program that gives a message depending upon how happy they say they are. Jou could get the user to rate how happy they feel on a scale between + and +=. f the reply is 7 or less it gives one message. ?etween / and 9 0including these numbers1 they get another message. and above they get a diQerent message. Try to make the messages ones to make them happy all day longR )ave this as: appy message
Chal l enge23–Mobi l ePhoneCost s Jou want to see how much a mobile phone will cost. There are charges for sending pictures 0P=.761, for texts 0P=.+=1 and for data 0P=.=6 for +!?1. +. Write a program that asks the user for how many pictures, texts and data they would use each month. t should then calculate a total bill for the month. . f the total comes to more than P+= they would be better on a contract. (et the program to give them this advice. )ave this as "obile 4hone +osts (arder @ata is charged at P.6= per 6==!?. )o even if only !? are used you still pay for P.6=. What we want to do is be able to round3up a number 0the function round () rounds up or down1. Jou will need to: import maths to get more maths features and use: math.7eil(num!er) P to roundup a num!er to the neQt inte*er
Chal l enge24–Secr etpasswor d !ake a program where the user has to enter a secret password to use the program. The program could be one you&ve already written, or make it display a message when they have got the password correct.
t h ec o mp ut i n g. z o ne
Bool ea norl ogi ca le xpr essi on ?oolean is a type of arithmetic that only uses two values: true or false, yes or no, + or =. t was invented by an *nglish mathematician (eorge ?oole. We use ?oolean expressions and can combine them with and, or and not to make decisions in our programs.
Chal l enge25–Forl oops )ometimes we want to do something a number of times. We may know how many times we want to do it < and we use a counting loop -> We may want to do it until something happens < and then we can use a conditional loop. +ounting 0oops This is the simplest loop. We use these when we know how many times we want to repeat the code. Try these out and explain what they do: for a in ran*e (&%)/ print(a)
for a in ran*e (&, &%)/ print(a)
for a in ran*e (&, &&)/ print(a)
for a in ran*e (&, &&,+)/ print(a)
Chal l enge26–Forl oops Write a loop that displays numbers += to +== in steps of 6.
Chal l enge27–Ti mesTabl eusi ngForl oops Write a loop that displays the 6 times table ere is the 6 times table: +x6M6 x 6 M += etc to + x 6 M 8= )ave as 6 times table. t h ec o mp ut i n g. z o ne
eal l y Forl oopsar er cl ever They can be used for even more things. senten7e = "Here is a senten7e. Ho$ many letter 'e''s are there in it?" num!er# = % for letter in senten7e/ if letter =="e"/ num!er# =& print ("he num!er of e's in the senten7e is/", num!er#) letter is Hust a variable that stores the letter from the sentence < try changing the name to something else and check that it still works
Chal l enge28–Readi ngasent ence Change the program shown above so that the user can type in their own sentence and the computer will calculate the number of Be&s. *xtension: count the number of vowels < a, e, i, o, u in the sentence 0instead of: if letter MM Be try using the method on page +6: if letter in4.1
Condi t i onalLoops 5 conditional loop is one that repeats until a condition is met. We use these when we aren&t sure how many times we will repeat the code, we want to repeat it until a condition is true.
Chal l enge29–Whi l el oops 5ll of this program should be familiar to you apart from the while loop. Think about what it does before typing it in.The while loop repeats whist the conditions is T-%. )ave as: challenge ;. num!er = &%% $hile num!er2&% or num!erM%/ num!er = int(input("Elease enter a num!er !et$een & and &%")) print("4our num!er multiplied !y &% is/", num!erB&%) Why is the int necessary in line 5?
t h ec o mp ut i n g. z o ne
Val i dat i on 2alidation is de$ned as: checking that data entered is sensible 0computers cannot check that the data is correct < the best they can do is spot obvious errors1. 5dding validation makes sure that our programs continue to run even when incorrect data is entered. We often know that we want a particular data type to be entered: Xoat, integer, string and if the wrong one is entered then the program can end. ere is a neat way to use a while loop to add validation to your program that stops these user errors from halting the program. *nter the code and see how it works. *nter letters and decimals and numbers not in the range + to +=. Try using it as a starting point with the >umplestiltskin program. #nter a num!er !et$een & and &% num!er = 0% $hile num!er not in ran*e (&,&&)/ try/ num!er = int(input("Elease enter a num!er !et$een & and &%")) eQ7ept/ print("#>>> in6alid input. ut of ran*e or $ron* type of data.") print("hanA you K ha6e re7orded your entry as /", num!er)
*xplain what each line of code does:
t h ec o mp ut i n g. z o ne
Cha l l e nge30–Rumpe l s t i l t s ki n >umpelstilitskin was a nasty character is a fairy tale 0surely you know this1. e wants to take a princesses& $rst baby < and will only let her oQ if she guesses his name correctly. e gives her three guesses. !ake a program that asks for a $rst name. f the $rst name is the same as your own then the program should print a welcome message. f the name entered is not your own name then it should print a suitable 0polite message1 to say the guess is wrong. t should repeat asking for the user&s $rst name until it enters your $rst name.
t h ec o mp ut i n g. z o ne
Comment s Comments are added to a program to explain what the program does and what the section of code is doing. "rogrammers do it so that if the code is looked at in the future 0either by themselves or others1 they can work out what the code is doing. Comments can easily be added using Y at the start of the line of code. "ython ignores anything on a line that begins with a Y. %oad your program: guess a number + to +=. 5dd your own comments to the program to explain what the parts of the code are doing: Y this program creates a random number between + and += Y the user guesses the number. t ends when the user guesses the number correctly import random guess MZZ print 0Z[ve thought of a number between + and +=. Try to guess it.Z1 randomNumber M random.randrange 0+,+=1 Y this loop runs until the number guessed eAuals the randomNumber while guess RM randomNumber: guess M int0input0Z(uess the numberZ11 print0ZJou got it wrongZ1 input 0ZWell done. "ress any key to exit.Z1
We can also add comments to many lines at a time by using three Auotes together B at the beginning and end of our descriptions: “” his pro*ram 7al7ulates ho$ mu7h sa6in*s you ha6e after a num!er of months. Written !y/ ay Rup Rate/ Sreated +C&&C&+ “””
)ome further challenges for you to have a go at. Ese this workbook and the programs you have already used to help you solve the problems.
t h ec o mp ut i n g. z o ne
Chal l enge31–Rock,Paper ,Sci ssor sGame We&ve all played the rock, paper, scissors game. The computer will play against you. (et the computer to ask for the player&s name. The game rules are simple: rock beats scissors, scissors beat paper, paper beats rock. Two of the same gives a draw. Jou can start with pseudo code to help you identify the steps needed. 5dd comments to the game so it&s clear what the code in the game is going. %&tension 5sk the user how many rounds they want to play, between 7 and +=. eep score and show this at the end of the game. /urther e&tension Check to make sure the user can only enter a number between 7 and += and give them an error message.
We can use a truth table 0Hust like with gates1 to see what the permutations are: >ock M +, "aper M , )cissors M 7 ser choice
>ock
1umb er +
>ock >ock "aper "aper "aper )cissors )cissors )cissors
+ + 7 7 7
+omputer +hoice
>ock
1umb er +
t h ec o mp ut i n g. z o ne
!coring
Eser OM+
# Computer OM+
Pl anni ngt heRock,Paper ,Sci ssor sGame (et the computer to ask for the player&s name. The game rules are simple: rock beats scissors, scissors beat paper, paper beats rock. Two of the same gives a draw. The program should display on the screen what the computer choose, how many points are awarded and who has won. !imple: play Hust one round (arder: play 6 rounds (arder still: ask the player how many rounds they want to play.
"lan you program using pseudocode. Think what variables you will have and what the main sections of the code will need to do. Jou will need to use a /$- loop and '/ 6 %0'/ 6 %0!%.
t h ec o mp ut i n g. z o ne
t h ec o mp ut i n g. z o ne
Cha l l e nge32–Ma ki ngat i me st a bl e( us i ngne st e df orl oops ) With a times table we start with a number and then multiply this by a series of numbers. 'or the times table we multiply it by + to +, before moving on to do the 7 times table, etc. Computers are very good at this sort of task and we can do it using loops within loops to consider every combination < these are called 1%!T%D 0$$4!. Type this code in 0try to predict what you will get before you do it1. fori in range(1,13): i is the rst num!er $e are *oin* to multiply !y print a title at the top of the times ta!le to sho$ $hi7h times ta!le $e are $orAin* on print (i, "Times table\n") for j in range (1,13): loop throu*h the num!ers $e are multiplyin* i !y and then print the results print (i, "times", j, " = ", i*j) %&tension
&
t h ec o mp ut i n g. z o ne
Funct i ons "rogramming languages have pre3made functions for us to use. "ython has some such as print01 or random. ?ut we can make our own functions, these are called user3de$ned functions: 5 function is a block of organised, reusable code that is used to perform a single action. ?y using functions we can make our programs modular 0made up of separate parts1 and simpler, because we don&t have to write the same instructions many time but reuse the same code. Y program that draws a sAuare import turtle Y import turtle module wn M turtle.)creen01 Y make a graphics windows to draw in tom M turtle.Turtle01 Y create a turtle called tom for a in range 0/1: Y loop to repeat instructions / times tom.forward0+6=1 Y move forward tom.right0;=1 Y turn right wn.exitonclick01 Y when window clicked end We can de$ne our own function to draw a sAuare: import turtle wn M turtle.)creen01 tom M turtle.Turtle01 def sAuare01: Y def ine our new function in this format for a in range 0/1: Y code is indented to show its part of the for loop tom.forward0+6=1 tom.right0;=1 wn.exitonclick01 sAuare01 Y call the function with this command
t h ec o mp ut i n g. z o ne
Chal l enge34–Makeshapes !ake other regular shapes: a triangle # hexagon # octagon using functions. Call the functions one after another. Try using an iterative statement 0a '-> loop1 to draw multiple shapes in patterns using this method. We can pass information to our functions, the data we transfer are called the function&s parameters. ere sAuare passes a value = to the function import turtle $n = turtle.O7reen() tom = turtle.urtle() def s5uare(len*th)/ for a in ran*e (0)/ tom.for$ard(len*th) tom.ri*ht(:%) $n.eQiton7li7A() s5uare(9%)
The function sAuare receives the parameter, and we have called it lengt. 1$T%: The variable length is used < but it only exists within the function < not the rest of the program. Type this in and then develop your program as shown below. import turtle $n = turtle.O7reen() tom = turtle.urtle() def s5uare(len*th)/ for a in ran*e (0)/ tom.for$ard(len*th) tom.ri*ht(:%) $n.eQiton7li7A() siGe = int(input("#nter the len*th of the s5uare")) s5uare(siGe)
t h ec o mp ut i n g. z o ne
t h ec o mp ut i n g. z o ne
ere we get the user to enter the width and length. These 4A-A"%T%-! are then sent to the area function and used
t h ec o mp ut i n g. z o ne
Chal l enge35–Ar eaorPer i met er %et&s make a program to calculate the area $- the perimeter of a rectangle. 5rea M length S width "erimeter M length S O width S We can de$ne a function to calculate area when we need it and one to calculate the perimeter when we need it: Iust as before with the shapes we de$ne a function using def and the function name: def area89
def area()/ shape-rea = len*th B $idth print("-rea = ",shape-rea) def perimeter()/ shapeEerimeter = len*thB+ $idthB+ print ("Eerimeter = ", shapeEerimeter)
ere is the code to type in. %ook at the code and think what it is doing as you enter it. fun7tion to 7al7ulate area def area(len*th,$idth)/ shape-rea = len*th B $idth print("-rea = ",shape-rea) def perimeter()/ shapeEerimeter = len*thB+ $idthB+ print ("Eerimeter = ", shapeEerimeter) response = None $hile response not in ("a","p")/ response = input("Ro you $ant to 7al7ulate area or perimeter? #nter a or p") response = response.lo$er() if response == "a"/ len*th = int(input ("#nter the len*th of the re7tan*le")) $idth = int(input ("#nter the $idth of the re7tan*le")) area(len*th, $idth) elif response == "p"/ perimeter()
*nter this into "ython and test it. Then add your own code so it works similarly if you chose to calculate perimeter. %&tension 5dd a function to calculate the volume. To work out the volume of a regular cuboid shape is: length S width S height 5dd an option to the program to calculate the volume de$ning a new function called
t h ec o mp ut i n g. z o ne
Passi ngFunct i onsaVal uebyusi ngPar amet er s We have learnt how useful making our own functions can be. We can also pass values of variables around using them, which is a useful thing to be able to do. 'unctions in other programming languages are known as sub3routines. There are a few diQerent ways of passing values between functions:
Met hod1 4ass the function a value and use this value within the function. 4ython +ode def display 0message1: print 0message1
What the code is doing The parameter in this code is:
within the function: display 0ZThis is a messageZ1 Type in the code above and then develop your program as shown below. 4ython +ode def display 0message1: print 0message1
What the code is doing -ften we create a function main01 and call other functions from here. t makes our code more organised and is easier to see how the sections of code work.
def main01: display 0ZThis is a messageZ1 display 0 BThis is a second message 1 main01
Met hod2 "ass a function a value and return a di:erent value. 4ython +ode def ask\yes\no0Auestion1: response M None while response not in 0ZyZ,ZnZ1: response M input0Auestion1 return response
What the code is doing
The parameter in this code is: within the function: and the returned value is:
def main01: answer M ask\yes\no0Z]n"lease enter y or n: Z1 print 0ZThanks for entering:Z, answer1 input 0Z]n"ress the key to exit.Z1
t h ec o mp ut i n g. z o ne
main01
Met hod3 4ython +ode
What the code is doing
def favourites 0subHect, meal1: print0Z!y favourite subHect is Z, subHect, Zand my favourite meal is Z, meal1 def main01: favourites 0ZComputingZ, Z?urgers and Chips]nZ1 favourites 0Z)pag ?olZ, ZComputing]nZ1
"ositional parameter "ositional parameter eyword arguments 0helps avoid errors and useful to make the code clear1
favourites 0meal M ZChicken wrapsZ, subHectMZComputingZ1 main01
Gl obalvar i abl es 2ariables and their values only exist inside the functions themselves. -nce the function has run and exited the values are no longer there. f we want to use a variable throughout our program we must declare it as a global variable. This can then be alterable by the main program and functions as well. To make a variable global de$ne it as global in the function and in the main body of the program 0at the start1. *lo!al name def printName()/ *lo!al name
This overcomes the need to pass parameters around.
t h ec o mp ut i n g. z o ne
Li st s We have seen how we can use variables to hold information for us as we program and have seen how necessary it is to temporarily store data. ?ut what if we want to store our school timetable, at the moment we would need to have lots of new variables such as mondayE&, mondayE+, et7. (or 0% for a $eeA at Tady anners). There is another way that uses lists 0these are often know as 5rrays in other languages1. ere is an example of a list: monday = U"ren7h", "#n*lish", "EOH#", "KS", "aths"V
mondayTT is the list name and the contents of the list are in the following positions: !ondayTT M^ "osition
B'rench
B*nglish
B")*
BCT
B!aths
=
+
7
/
Note: %ists always start with =.
t h ec o mp ut i n g. z o ne
Chal l enge35-Li st s Type this code in. >un it and then explain what it does. +ode mondayTT M ^Z'renchZ, Z*nglishZ, Z")*Z, ZCTZ, Z!athsZ_ print 0ZThe list monday contains the following information:Z1 print 0!onday^_1F
Description
Try changing the to another number and see what happens.
print 0ZWe can also Hust ask to print out the list. )o here is monday:Z1 print0monday1 print 0BWe can also print them out one at a time1 for i in monday: print 0i1 We can also add to lists, very easily in factR 5dd this line after the $rst line that de$nes !onday: monday.append ("eo*raphy")
What position is (eography inG
Mor el i st s %ists are very coolR We can do lots with them because they can store information with them, adding information and reading information. Type this simple list into a new "ython module: !ars = U“ars” , ”Iounty” , ”$iQ”V
To add to the list we use append. Type this in: !ars.append(“itat”)
We&ve seen that we can print information from the list using its position: print (!arsU&V)X
can you remember what this will printGG
t h ec o mp ut i n g. z o ne
Sl i ci ngl i st s We can slice a list. 5ll this means is that we can $nd part of the list and make a copy of it. Type this in: print (!arsU%/+V)X
Write down what prints:
)ee how it prints diQerently, Hust like a list. 5nd look at what it prints < position = and + < up to but not including . Try typing these in and write down what "ython is doing: 'nstruction print 0bars^:_F print 0bars^:_1F print 0bars^:_1F
What it does
Addi ngt oal i st 'nstruction bars.append0B)nickers1F print 0bars1 bars.insert0+,Jorkie1F print 0bars1 bars.extend0^Z"icnicZ,ZTwi rlZ_1 print 0bars1
What it does
1ote: f you want to add more than one item to a list use extend. )ave this $le as: adding to a list
t h ec o mp ut i n g. z o ne
Del et i ngf r om al i st %et&s start with a list. *nter this into a new program: !ars = U"ars" , "Iounty" , "$iQ", “4orAie”, ”itat”V
Then add the following instructions and see what they do 0the print8bars9 option is there Hust so you can see what has happened1. Jou can add each command after the previous ones: 'nstruction bars.remove0ZTwixZ1 print 0bars1 del bars ^=_ print 0bars1 my?ar M bars.pop01 print 0bars1 print 0my?ar1 my?ar+ M bars.pop0=1 print 0bars1 print 0my?ar+1
What it does
Random choi cef r om al i st We have used the random function in our programs before. "ython has an inbuilt way to select a random choice from a list which is really cool and saves lots of time: import random is placed at the start of the program.
Try this out : letter = U'a', '!', '7', 'd', 'e'V from random import 7hoi7e print (7hoi7e(letter))
t h ec o mp ut i n g. z o ne
Di ct i onar i es 5 dictionary in python is very much like a list. t stores lots of data. ?ut with a dictionary you store data in pairs so that they are related to each other: so you have a piece of information < the key < and a piece of data < a value. The format of a dictionary is: di7tionaryName = Y“Aey” / ”6alue Z
To look up a value from a key: dictionaryName^Bkey_
3 will give us the value
n this example we have stored computer terms. key
value
7omperms =Y"HRR"/"Hard disA dri6e", "ouse"/"Re6i7e used for maAin* sele7tions", "SE"/"Sentral Ero7essin* nit"Z print(7ompermsU"HRR"V)
This will print: ard disk drive
t h ec o mp ut i n g. z o ne
Chal l enge37-Di ct i onar i es Type in the following code: 7ountryEop = Y "[apan"/"&+8%%%%%%", "ermany"/"9&%%%%%%", "Kran"/"88%%%%%%", ""/"30%%%%%%","Sanada"/"%%%%%%","-ustralia"/"+%%%%%%","O-"/"&8%%% %%%", "Iul*aria"/"8%%%%%%","O$eden"/"&%%%%%%%"Z
The program should: +. 5sk the user to choose a $rst country . 5sk the user to choose a second country 7. 5dd together the populations of the two countries. /. !ake sure that you put in good messages to help the user and tell them what is going on To test the program enter Iapan and E)5: they should add up to: ///====== f you get the answer as: +9======7+9====== there is a small error. %ook back at Challenge / and 6 to $nd the answer. %&tension What if the user enters the word incorrectlyG ow could we deal with thisG 0country"op is the dictionary name and country+ is the name of the key1 7ountry& = “” $hile 7ountry& not in 7ountryEop/ 7ountry& = input("#nter the name of the rst 7ountry/") print("Oorry 7an't nd that information. Elease try a*ain") print("K'6e found the information for you. he population of ", 7ountry&, " is/ ",7ountryEopU7ountry&V, "Ln")
This code should be familiar to you. While country + cannot be found in country"op the computer keeps asking for a valid entry to be made. When country+ can be found
t h ec o mp ut i n g. z o ne
Wr i t i ngt oandr eadi ngf r om afil e )o far the information in our programs has disappeared as soon as the "ython program has stopped. "ython can write to a $le and can read from the $le. myile = open ("eQample.tQt", "$t") myile.$rite("Here is the rst le K ha6e $ritten<") myile.7lose()
)ave the $le as: write example That&s a good start but what we need to be able to do is keep the information separate so that we can do more with the data. 'f you run the program you will get and error. !ave the python program and then run it. The te&t ;le e&le.t&t will be made in the same folder as the program +heck to see if a ;le has been made. Double click it to open it in 1otepad.
-ne way is to write the data to separate lines in the $le. We can do this by adding the newline instruction: myile = open ("eQample.tQt", "$t") myile.$rite("Here is the rst line.Ln") myile.$rite(“Here is the se7ond line.Ln”) myile.7lose() The =n is the instruction to create a newline. $pen the ;le in notepad to see the result. +lose89 is very important > it closes the ;le when we have ;nished.
Wr i t i ngaLi stt oaFi l e This is all very exciting but how can we develop this and do more useful tasksG Writing a list to a $le would be even more useful. myile = open ("eQample.tQt", "$t") myTist = U"Tady a*a", "[ustin im!erlaAe", "-SRS"V for item in myTist/ myile.$rite(item"Ln") $rites the items in the list appendin* a Ln to put it on a ne$line myile.7lose()
Notice that the line myile = open ("eQample.tQt", "$t")has B$t at the end. This tells "ython to open a $le for writing to 0hence the Dw&1 and the Dt& means that the $le is text.
t h ec o mp ut i n g. z o ne
5n important thing to note is that using $t means that the contents of the $le are deleted each timeR
Readi ngf r om aFi l e )o how to do the other part < reading from a $leG myile = open ("eQample.tQt", "rt") 7ontents = myile.read() print (7ontents) myile.7lose() This time we open the ;le with the rt2 command. This means open it for reading. The contents of the ;le aren2t deleted this time@
That worked well, but what if we want to put the information from the $le back into a listG "ython does this easily. myile = open ("eQample.tQt", "rt") myTist= UV dene an empty list in $hi7h to store the information for line in myile/ myTist.append(line) print (myTist) myile.7lose()
Well it&s - but now we have newline commands in as text < so let&s get rid of them. 5dd after the line with for line in my'ile: line M line.strip0Z]nZ1 and run it again.
t h ec o mp ut i n g. z o ne
Chal l enge38 !tep . Write a program that asks the user to enter 8 numbers. )tore these in a list. Write these numbers to a $le. !tep B. Write another program that reads the $le. "rint out all of the numbers together with the total and average of the numbers. %&tension: )ort the numbers into ascending order 0smallest to largest1 !tep 5. Write a program that will allow you to add four new numbers to the list and write it to the $le: myile = open("eQample.tQt", "at") opens the le for appendin* (addin* to) for a in ran*e (0)/ ne$No = input("Elease enter ne$ num!er") myile.$rite(str(ne$No)"Ln") 7on6erts the inte*er to a strin* \ adds a ne$line instru7tion myile.7lose()
Chal l enge39 This list has the names, heights and weights of 6 people. The height is a digit whole number and the weight is a 7 digit decimal number. hei*htand$ei*ht = U[ames, 8, &.9+, Eeter, 89, &.9%, [ay, Ieth, 31, &.1, a*s, 33, &.1%, [oy, 3+, &.0V
+. . 7. /.
*nter this list as it is. )tore the data in a $le. Write a program that reads the data. "rint out the person&s name and their height and weight.
%&tension Work out the average height and average weight of all of the people. Work out the average height and weight of the men and the women.
t h ec o mp ut i n g. z o ne
Pi ckl i ngandShel vi ngLi st s f we write a single list to a $le using the commands we&ve already seen is straight3 forward. t gets harder to keep a log of the position of information when there are multiple pieces of information. "ickle allows information to be stored and read from a $le easily. This program saves a list to a $le: Write this program in "ython and test it out. )ave it as pi!le#data. import pi7Ale imports the pi7Ale module a = U"Earis", ">ome", "Tondon","Washin*ton", "os7o$"V a list to sa6e to le myile = open("testle.dat","$!") opens the le for $ritin* to pi7Ale.dump(a,myile) dumps the list (a) to the le myile.7lose() 7loses the le
-pening the $le created shows the data has been written but it has extra characters.
The code below adds a second list and a second command to pickle the data: import pi7Ale imports the pi7Ale module a = U"Earis", ">ome", "Tondon","Washin*ton", "os7o$"V a list to sa6e to le b = $"%ane","%anet","%ill", "%ean"& ' a se!ond list myile = open("testle.dat","$!") opens the le for $ritin* to pi7Ale.dump(a,myile) dumps the list (a) to the le pi!le.dump(b,mile) ' dumps te list (b) to te le myile.7lose() 7loses the le
The $le has been created adding the second list.
Now let&s try reading the information into a $le < a very simple process: import pi7Ale import the pi7Ale 7ommand myile =open("testle.dat","r!") name the le to use and open as "r!" read !inary names = pi7Ale.load (myile) read the rst list 7apitals = pi7Ale.load (myile) read the se7ond list print (names) print the rst list print (7apitals) print the se7ond list myile.7lose() 7lose the le
t h ec o mp ut i n g. z o ne