Download as pdf
Download as pdf
You are on page 1of 49
cane coding for beginners CONTENTS What is coding? Staiting Python Playing with numbers... Variabies Making decisions... PAaNNINg PrOETAS They're heeaere! Bat and ball Downloading Python .. Managing your files Debugging Which wind Code at a glance. CH) USBORNE QUICKLINKS: ong Python ak he Uabarnie Quin swt usborne.com /quicklinks WHY CHOOSE PY: WHAT 1S CODING? Coding means writing instructions for computers, anda Compal programms control ever thir smartphones to space rockets. SPEAKING THE RIGHT LANGUAGE e Conga lee ahr bit = eepcont fo { SSH ‘WHAT'S A COMPUTER LANGUAGE? compar language re tr human rage ba wi fever woras re ery Drees about how toxse thems Python 2 txt amet computer ungusge hich rear ty mace up of wares, rumors an sees uch a * an). NSTI @& python” “Commoner fo STARTING PYTHON savnewo Once you've got Python on your machine, you can start creating programs immediately. DID TT WORK? on -— “nm — “nm “nn ow “— -— ore im “ ~—_ - “— gee —_ —_ -—_ -_ -: —_ -_ —_ —_ PLAYING WITH NUMBERS Python makes it easy to do maths. In the Shell window, You just type in a question and press return for the answer. = 2 (Code window [cat on Fite artnet) to. open the Fite ADDING UP i Open the She window and type tis i us! SUBTRACTING [AND MORE) youwant to aubtrat, use te -symbo PERATORS Dette weer ¢— Bivpe im tetebeion, pein tate wesainye TAA smeansa Pyren fi) Bie sreuincow sous popup ana tee wore elo wer hold aspoar VARIABLES A variable is like a labelied box that stores ABR etormation, You can change this information, but the label stays the same. NAMING VARIABLES. “oe con gre yore oy mane you I Here’ an warping bnarat so Dest inow yx cect npr, Loven the sya wrow. 2. typ nt toon “emiowecmr | ‘You rave now created. a arable cated bananas and pv value 6. WANTS PUT YOUR BANANAS INTO ACTION we your “bananas vara actly to something, yar ted to wre ‘LET THE USER DECIDE you want ne ker ofa progam to deci wht voli a variate shoul have, youcan thea function ates tnput6. ‘coding any formation entered ba Aeris non as inp (2 Bu BOO. Du Input()# function tat tla the cornoutor ‘tmtap the program wl he user has typed something and preeecreturn INPUT IN ACTION ‘YouAcan es the input furcton to ask {er someone'srame. Logan te Snettwinaow ane ype SP pe REE Ete roe Crise | | tenet tna mosare 1. Prone return, Pe computer should now ask | Mat fe your samt ype inyourrame nei tothe question and prose return, Your name snow stored Incsd evarai, rare Aon mene te, types ‘S.precs return, mo computer should show See ee | = sf venus ieee ae Eas ebetrcae Bare ny eter Soe ee aes Bt Sonne aes WT Wh CREATE A CHARACTER Yuan ute variables and the print and Input) functions to ereate a ensracton Lopen the shel window. cick on File and select ‘New Flo which rings i the Cada window, Now lek 7 Fite in tho Cas window, sleet Save As nd type in 8 ram foryeur program 2 create a tte to intreduce your program by typing thi je your program by typing ie elsedrCeeute your churseveri*) 4. vse tne input decide the char Athen, ao serge ans weakrisoes each ona ne ine, age © Inpet("Bow a year eharactar?“) inque(neuat ae your elurtetse's wtxengea™) ngihdas ate yoee character's: weckneeed?=) 5. Now mak the ‘uaracter sing te print function, Pat each el: pele (ttiat characte! wane Aye, alle) Prise(*tour character Le", age, “years ols") Beint(rascengtnair, atrengtbay [princ(-wealnecaasi*, vaaksansas) Sekshiotony ‘batty “thas ou ccsetg psn SPELLING STRINGS alah etl you code ping Sher ne ai ne yon antigo cd sonore, bacon Secteee ret bt a cont th yok crying wt B.youroraparn srinaned.clexon Fite abd yoct Sve to sz Then cick on thea mena undasaet Bur Me ADDING NUMBERS AND STRINGS er ges &peepram input. Pthon oper in & Tey cresting your oor charactor ty sere Fret yovsne to RESTART wii | Fan your eraractars nama, then prom Spies ine Peso WARS ry pooner onan hese eta a poe ontbanser ‘Lrttinyourenaractars age and prea return gan. Arawor the foowmg.qutations nthe mare 1. pen yu proms our ater fl qvston hans | tha coven Hap Brune, uuynga wena - net ‘your charater on serten, lang wth a greeting 2 Hee 1 Hi hs Fo ection ! Ee oontne Soe 14 fa MAKING DECISIONS §=——-% “cise _ To write a program that allows you to make decisions, . . the computer needs to react differently to different answers. For this, you need conditions to compare pieces of information, and conditionals to create different paths through the program. ‘WHAT ARE CONDITIONS? ‘condition aa of coe that compares two ‘econ ef frration. Coneitons use operaters (Gee page 9) toma these comparisons. For eerble the opertor =» choca two pieces ot nw iF stormaten aretha same STATEMENTS WORK (pen te et window ae iype oe a res ers FALSE TRUE Press ret, You shou se this on te next ne: ‘The coven False because age’ i st to 10, ot 12. Toa computer, a concen can ony ever Deru or Fale Ty typing ne into the Sra Ey The time, you shows see True ote rat Cie Cae Here's rogram stewing an if statement in ation DO YOU LIKE ROBOTS? Lopenanew Then type his mn of cato Be soee cepiy = snputer00 you Line rotore? (nype yar or 20)7) 2. Press netun and type this line, eee } ¢ a Sten 4. prom retum. the Code window snout _autoruticaly aan indent of four spaces atthe arto the nor na: Typotha afar the nao 4 Save anctrun the program. you typ in os When asked if yu ie robots, the computer wil Print a cher Bea 0099! ety Hf youtype inno Cor amjhing ese fort imation, the program won respon, ‘nit statement can incude more branches YoU nude the keywords ele and aif ELSE Th Word els’ tels the computer which path to alow when te conaition for ant met |LOnen the pregram from tha praious page ant cd these tines bio the Fal ne Seen a in the program, ty nario “activate the else prt th cae. INDENTS: eur slit a short for ‘eso, ati aways come ater an itand spnng into action when conditions fr the it Pave fot been mat. als hs ts own condtlon ad ony rune f that ras boon met 1. Save your robot program with anew name, ‘Thon type inthe changes ighghtec bolo IF ELIF AND ELSE cu eM nde ac a sate re Saee_ewply = apt 00 pos Like rebHtaY (pe lges, so, sajbe ox caiy onan with ianec ope) ‘inc zeply = *yes"t (or reply == *eort | lne(eiell, robots done ke yes either.) WORE hangs tones offends wa.) 2.Srecandrunthe progran. To rumingit Savera tines, choosing ferent opton each tine. if you get an error message. ek athe spoing ana punctuation & correct, rewing inyour ancwers. Gee pags 88:89 for more dlbuagnetipa) ELIF DY fy DARE YOU ENTER CASTLE DRAGONSNAX? Nowe to make the game rea a . PLANNING PROGRAMS When you're writing code with lots of branches, it’s worth planning ‘Out what will happen on each branch, This helps you keep track oF what's going on, so.you end up with fewer errors in your code. 1 nag print, pelst (fo ae te (etn feat of you are earn: dae ‘press return, ther ereate an statement a 4 Se ee ae ee 5. hen, tet te aor the wer tf ves/meue ia I on ELSE YES /TRUE Bonin VUVESAS SSE stayartbson 21 pagan ierepsnaeey 3) Sinem om. B.presuretirn. Thon, bypass cod that wl cun nie fist ‘Se printer go Lae she at hn dragon wala ad ate ‘Tver rie ype someting oe Toeover soa ese cm peintimecy, re aise 't eater rays ct a ine tt tots tus when te game's oer EES tbe ge soe to Save asstbar 40.4) sae and eunthe progr several mes, choosing a rave DEBUGEING ‘Youcanadd more at anc ee options to Bee the gare more tt anetures Youn ‘lg ade an elomert of craves, wing function ‘ca randing Lope your gine and alee sao the Fe fren, then gue ta dtterare name Ths savee Aen veri 9 Yuan tinker wah it wrt solinetne erga: —_ _— —_ _ — —_ _ _ —_ —_— peintq'to from ot you are Cs dooce, You mat hice e08*) playerchaoe » input (chose 1, 2, 3 se 6.2") La tne printo the btn hd delete laerciatce = ‘on 9° Late the roam and fisd aledpiag dea.) 4, aatthroe new print command underneat, sme pcist(-1) ty #2 steak sone of the dtaga's gutdar) mpcint(*2) ep to ween ound Cha dragon to Whe elt") 5. Press return, Now creat wih ale ‘he dragon's gla or aneskng aroun rupectolce * iopit{"Tyge 1 or 2...*) 1. press return Nest. you atea now Hf statement which arupeccooice ("Re seepenuien op sed mats yous tos ary aeticion 3 ent NE OWE, OU £058") = Wh Press retin, Now aid an oti anc tivo print) f THE RANDOM SPHINK functions. te th, to create aranch that runs if 1. ter the code you acted in stap 9, create a new Sepa stors womans oars RN se oe inmatcoranoe Hess ae = A kere Fo nt tc, gn hi sei aceres oe mem Tesco cr wom a ten) aa fe oe oe me eo i, Se ‘AL onthe naxt tne, add an eles, which will run if tes = ae Wat manter de you chooee?”)) oroen omnes Touesdiat nar antec rine rn dans mtr 0 2°) eres what your code afar should ook the: I To generate a random numba forth sai you need a naw function, called randint, i 6 ce rom to myterions cane ‘the rancor number tancions are sored PORTING: ee FUNCTIONS 4 Import. Go tothe verytap of sour progr ‘ ype oa 2. ster ine cis mutt noep 10st eed an if with an wise to-create two branches in “ ‘Se prin 2) yt moat cron the dragon to th enl8.*) Pseagnciciee * Lage | OL degenthoten = «161 —t were) ere [SS relate ceare water up anne yee. Yo mre dlistons.*) | leneedencetoel Ss reimrau com, Soe) a dmectoice — “2's me me resents soe ine shoul lb a print tora te game again toh ADDING LOOPS acon aka yo. Case Dragons program teatart automaticaly tout having to Ft pun ty aaairga wnite top GSUSSSSSSASSSSENNNDD Dontreneatlie adda white reture to play again, or type anrt ta ties) is earn the program wnt tart the game again rom the bnginning i yu reas reture of sap raring you type EXT B. Save tho pragram and run @ several timo, Pex acferent path each tena, to test al the branches THEY'RE HEEEERE! ‘Aliens are invading the Earth. This program gives humanity a ‘chance to stop them. But the odds aren't on our side. ‘these aliens muitiply very, very quickty. ‘oBAL pereNce ProciaM & agit. Teepe «= KR (eS acre hohemmetgunral = ieee 2 XX 2 pres returntnen create anctrervaratia DK ‘pranrct'= “asm prea return. Ten ts the corrputerarnt to sme pnne = top tek! Plauen tae the wierd *) per) 1, Finish wah an Weise statement. Uk this Thee & Se riede ene ae tec ae GUESSING GAME You can create a simple guessing game using conditions, -conditionals, randomly -generated numbers and loops ~ that is, ll stuff you know already. Intia gas, the computer wi generate _aranoom nine from 1-29, whch yo then yt pss Leerxtyopeneganan rape ansimocrn he tandomiaie Trevi anit pserce terme Dekh player to gine amber andstre eareeer as ners one pee == (eta Sak ceptga = tening of w vember from i to 28. Weak La 481")) Brew beg awhite loop. (That keep the game ving nite layer gunoes corey} A Preme roturn ont eine aa on “matement that wi check the pues és ower Pan trariamber the computer hae prorat = WSS {tet wl appear every tna the gues ls wrong poser = Lae aapes cntaae try apt Brose inde, ts cusi¢e the while Loop, eink Congratatetienet correct ater!) SLsaveandrunthe program to test Tis vt tha finan codes wil ook Un on eerean ‘elst ("Your aber was 0 I eioe( ‘Hear sumer ws 120 Mis gase » inet lopst{"Pleae ty apn, print ("Goopeatalutlons| Correct anit WHILE LOOP Wile loops eat stop wen sonetnirg changes Wedoasn'eharya, thay could goon Tower HOW MANY TIMES? Exch inayou use. for loop, you need tora ow manta ta repest- To otis you noes a tye of function cal ranged, To sreate ver rye for Loop axing range), open aim fhe, ave Ran type ti eee FOR LOOPS A while loop makes a section of code repeat and repeat ‘until a certain condition is met, If you want to say exactly hhow many times it should repeat, you can use a for loop. FOR LOOP \ith For tops, you can te them exact ‘WHAT DOES TT Do? you run the ee yo typed in on the previous Page. you should eee the numbers 0-9 appear in ‘he shel window, THE NUTS AND BOLTS ms for loop has ot going onto harw'e a A TIMES TABLES SHORTCUT You can use for loops to get Python work out the times tables for you. Here's how. ut print atte ena Levesereturn, bien the rangeO fonction ‘A. Save aret run the program. You should see the e Nes ls a Serer cre USING LISTS Python aliows you to group lots of pieces of 4 information together by making a Ust. Lists are stored using variables. MAKING A LIST You crate mst ing square brackets, Ui the: SRLS Ut, tm very tet yea want to to anything with one ofthe words trom that tt, you can esa something cab the Index ~the powtion of the em in thet. spealise = ee ‘planer, “snternta”, 9 Tete ran nts Dyn as REG nate) There are lots of mays 1 ip to a st ane a ings wen tre ams DISPLAYING ITEMS FROM A LIST Open a new ie nd crete your it: Crp aaa lamer, camencettey catia) Dro diaplay an itm tor theta, won print) VULUULLLLU LLRs DISPLAYING THE WHOLE LIST an use afor loop to inlay he who at the second ine of your program and aati: diam mace ss seisc(irm) <7} 2-sive ana rune program now, You shold we the Se) (mite cae || = | seine cone fo) sine | REPLACING, DELETING, ADDING you can Tivinarting ti fenteringa new ene. pefere the (or lp. acelis ‘Lsawean run Ui progr The tir ‘Tole an hem, restace te ine yousust added sacelis Points ope Te 20 S.youcan a ptothe cof lat using append, scniie appaaesoenig— * ‘ADDING LISTS TOGETHER Lea als eat togter Ope anew Re and type pecans = (eect, plate, sateen, “antes npecaita = ("apace station”, “mat, “Bleck tole") space it = apace + ypceliee? me Sean ln apocetlats aera ene andran the program Yousnoul te ale that 7 te. A. GAME OF CONSEQUENCES Theres party gare calc consequences” wnere prove make up stores by throwing together rangom charactors, placa an events, ie tia Hero's now wo ereate a Python version eft game ‘Lopen anew ie, gh a name ani save. Then creat a lt ket aA mR Aina pear, oy guns exaieene—| The program wi pcxone of tae at rancor asthe ferale charactor your ry 2. est create att of mate characters sas ra tec Ha arent yr granarnnee, ve mutter exer) Len, creat its forthe other parts of your sory (RN I Pistoia te sapere." in w oy, bette exve.*] "(4 popia attny tach contain "a bch tows" (te et he per tun ste Che", “1 et ek Cpe, eh tne ys ell ats) 7, shat font spunbet then, “abso.” ipanot A toedhog o's aa altigt | anon. cHoiced {yer wot oko awhile loop Co create anew ory each Seman orden Import the random module ard opana white accede” — sme peist(-e was acing, randon choice (beer) sme peint(-me was ering", resdoe.ctoice ear) ) reise inden bss (mans) | ‘me teint he nab raedon-chotcoamaeey) ppeint{-e coonegance wae", radon. chace{consogneen} smeprine(-me vor eb,, eason.chateswatisais)) sm isgatioeee tae to pay sain.) print) Bave an run the program, and see what ries yu pit. you he, you cous play aroun DICTIONARIES tooremicnn ni Uke lists, dictionaries are a way of storing information in Python. you clapay tna tionary now, Bruins wl have mow poner Each entry ina dictionary is paired with a label, called a key. You look up entries using the keys. ALIEN TRANSLATOR (CREATING A DICTIONARY ze oui patton tea tt me ore Tema nie cary rackets Forearm. 7 a Lomatea dctonary tt store supertero aaa ames and powers, open the 3 anal type thi Spb fees gay Ahan erates ta roucan daplay an entry (r superpower {ping tn the ey tne name. 5 you type 299 GelAt (porn -The ripe ape 5 \~ S. To adda new kem to tne cctionary, type th 6 < ary, cher the > presntaie Gr"} + “anon tuners" “ nae ores type are any seine 1 seine = 4, You can alc py the whole iconary | cory Nag ae 2 patina) ss me vers allncieticar: i Laon appestalieoitoamry er) tye con row, you sha ove something Se fee SOR EOEROROR EOE DOD ERED ‘Save ana run the program to ty out SPY MESSAGES Spies use a technique called encryption to scramble the letters in their messages, so no one can understand them without a secret formula ta Unscramble them again, You can use Python to create your own encryption program. CABSAR CIPHER hea Palle AAC -_ Low, create a tank tring. Tia wnere ‘he encrypted message wit be storec wnen you program run. a) TWanenparct oret ara B.to encrypt your reseage, you nted to eee snitch ater inturn. Youcan doth eS | With for loop, sing the inde ofeach lettor to workout wht wil Become. (Cem aterecinirnica tips ocirninone Here'swnat'srappeningin the code above nage youve patente nerd "yt cnerypt anda ay oz 012345 pAsener (x DEBUGEING Tips © Ch yx + Make yore wi ond wm inf cote pews 1 Hale so jou vvble rome ipl th om wy ch See pages £880 or mene ‘Lhe ast tne in your program is notindented. This ‘means it wllrur when the for loop has finer, elsetons aneyptad mvnnge i, enceyteaesten S I B.save and run the program. Than test ity ‘yping|n a werd anda kay. For example, ou ‘ype dog’ and 2, you shou spa tis ‘oar encrypted seseogs i Fa ADDING PUNCTUATION SL.i'you nant your spy messages to include punctuation and eyrnbols, you can ad the ines Nenlignted below, so your for loop locks Ska tis csteantcbaracear o steiagtemserypt st posltlee + alphabet HndicuczentCharecter) son ition = portion + anittanount ee ee ee DECRYPTION b Spies also need to decade messages they recive, Ujumbllga encrypted message known as decryption To crypt rian youve encrypted sing this rogram, ‘younced a decryption ney. This a negatve version of your shift. ‘So your ona ait was 2, your decryption ky wil be -2. “Try fending your encrypted message through the program sing thiskay, Forearm, your encrypted message is"F typ ‘that, witha naw deerypton tayo -2.andyou should gt TURTLE DRAWING Yotican create images or graphics in Python usinga hg module called turtle -a set of ready-made functions 177 ‘designed for drawing shapes and lines. \ WHAT IS A TURTLE? ‘Atri ke a cursor that meres aroun your teree, imavinga ine etna & Turtles ean ra kins shapes and pictures -you yas need 20 _ghe thom tne gh commana DRAWING A SQUARE To uso turtle, you frst ned toimport the furte module. This shor program shows you ow to impor and use to eran a square ALopen are fa'ana.ene Then osc the ‘ure mea, be this: TURTLE STYLES are te aber oo feme tertte gee re @ sauere Hl triongle deat << SPD EPEDDERE EDT! \ TURTLE COLOURS Tee hos) bove wy cot wel bY bes gate afew. mela nome wih ase res, UTA You eon ty ony tae eqvamarine i goldenrod sams cyan st lenan cillon lem HotPiak me dork orchid mmm DorkRoki ts 4 Sot the turtles speed, choosing a number Detwoon 1 ane 10 (10 6 sre) 5. You can gt tho thickness ofthe ine your tur Wilcraw sing a function called pensize. pramiancty Now. tet your tuna unare 106 feracd(3t) Agha) fereics0) Higa) foracé($0) mone Ch ar sw 7 ‘Lsamanininyo You sno oe tis. PIXELS The doce et move oe eat m pmele bod DIFFERENT SHAPES Wiongle cgon Dis sleep mw tecae| st) shops wik yh nde foc i= ranest) = toceare5e) meet ry making yor com apes combing ae (orien cig er hs Deku) oo DRAWING SNOWFLAKES WITH TURTLES Yoxean msn turte drama snownko uss loops an factions to bud» repenting pattern ‘Putting instructions mee a function means you en Feat he ya ig the Purcon, nse ‘thaving to ype everyting aga open a now ear et up you ture the same wy bs bore 2d acoioures nck the turtle window arc (chose turquoise) Sexmen(y-tonalor|razgee') 3.now you're gong LULL Etett etter rece om bs ra 0,0)1 ae torvet33) Ty ‘ovenia acter tmctonto drawa wrote FANTASTIC FUNCTIONS ‘spowe, using aor loop torepeat the Functions are used latin Pjthon. Mare are some handy reminders + Function rarnes are generally flowed by pale Of brackets Yeu ke or eal fincton by Spine ints nae, fllowes by the brackets. Tha a toawn as a function call ‘ 2ython comes with lots of ready-made, but furctions, suchas print and. range. These show up purse + You can acctes evan more unetions by seston candine() Importing modules = braves of ready-made tne modules, Thess show un black, 4 You eka crate your own functors et meet) Using det oe page 49) One eam snowflakearm®,Theseshow up blue when seeeata(y yo fine the, but Lack when yu cal t 3 {heir on non programe. reicing to breakup your code and oreante cary. othe! ackots after the function nama are for ‘parameters varies that you want the ‘You could creat aiarent erowAtakes ty puttrynafterent ‘Values in top 7. Make gure theturre aga up 2360 aagreas, ‘9 he sncafake gos. the way arou0d, youeallafurcton, F you can atthe parameters by putting values rie Use brichets. These values are know arguments. For eamplo, range (0,6) nas tne arguments Oand 6 Tocrestean Barn Someta the brackets are et emoty. A funtion wh ermpty brackets should co the same thing every tma. tks snowflakeArm() cathe reviour page + Same functions. need return a value “marina they frizor workout abt infrmaanBhen pos back 0 your powray an uae Fer wap, rangs(0.6) rtura fot: (01 24:68. the tunetion caltbernrucs the function AND represents the information Cpehsirna. So yotl dni’ need to type anything else. ‘COLOURED SNOWFLAKES: ‘You conse the randoms mele to make 2 mutesiowred snontabe Lopen your snows program and rave wih new rae, then al at he top spe indo 2. Detote tne ie Yat sot he pn colour 40300 ‘a0 te cere colours iseatoe(in Som youroealto eet up a tat of cours an (emer ater tne une where you satin background oar = (pega apa asta: ema “proer, “ocene” | Aten pick mcxtour trom te bt for uct souefaie arr, Tha means adsng an extra ie ‘the fr Loop a te an of your program ‘Sve ae ren the program, You should pot a CREATE A SNOWSTORM ‘You an alo ue the random module tf thi screan with snowtiaken of ateret aes Bare yur clr outta ogrom bo Ae a @. an variant your anewflake.) futon, te ms tomar ra varie te hap) at snowfiakadrm func, forwardnd tacewardt snatt | ae, | m — Jee eee 1 rane aoyee = SUSSSSSASLESSNNDGT ‘sive ang run your code. You sous gbt smal fury of snoatikes {USSSS4 USING COORDINATES: icin oy it onthe even vig ear diate he keardinae ls you lotr you np weight ‘ocr cache lg fertan gala. You cos do ‘ts stating oka Hye ‘enupl) jap pendownt 2 DON’T PRESS THE BUTTON ‘This program creates a button that will display different messages when someone clicks on it, TTINKERING WITH PICTURES. ‘orale abutton that appears onscreen, yer nead 3 ytton made cae thnter ayo ay eter). Thinker ita stot tots htt you create pictures, or graphics, ‘co thasereen. Ras dong for making Graphical User Ireetacer 00 Tg on -— - - - Lopan a new fi and save Then import tkintar: L.went youneestts main tho computer SS Ee ator yack’ the button ito bho thinter “win, ng futon called pack (adadan to pai aac arn a SUSSUSUSSSSSSSS ‘Ladd a varkabia, to beep tack ot tow any tien te baton hasbeen ceed | 48a enenen a funcional te omputer what todo aftr each cle Gheevent (Ge ccna se ya emosune Sit ctictcome = 1 se me bron, contiqureumreeerionny? te, ot. Pena. 1.2) ate attest = 1s mem mrtcn.coatigre(tarewcaht tt tae) oo move butte.) bn your cleo ana lasing tne button Sete adc rcneentinabe Sry ached) I £4 tine toma the whole thing rr thermistor [om moe Ih save ana run your program You shoud gt & button waa gees of monsages Uke th MAKE A MASTERPIECE This program allows you to make your own ‘paintings’ by dragging your mouse-pointer around the screen. PAINTING ON A CANVAS be inter youcan create pictures on a canvas a ian hackctrop wth x and y coordinates to ep track of where u're drawings Lopen andsavea new fia, then import tkinter es thee 2.tes ecu print functions to epian howto ute the program ERE ea Bad doen the E+ moe Stan ad nove your sous ext“) 4 See ee ete ‘Low you eed ts tal the computer terest a ‘arvas when the program nurs indo esteem ‘hier os store, position B.connect your on_clickO anc.on. functions eleks ad drags on the eamas using bindO teeinod. A. net run your program. Then save anc ‘everthing sofa, totest © Youshould be ble pai. Bat only in Bek 10. To part in cotsura, youcar ade a palette of tlickabe squares. To creat and postion these on the cannae, you nee one coorainates BINDING [ai ot se cers et ow you > fk 2 bn you cdo ter on cra -comeor hind!) bo hoc oon event Toth ocaimae il on he come Cbject ch ona hapa] te cone SOSSSSSSSTSSSSSSS TGS ‘ soloarbLaeh(ernt)t 12 Youcan uses tkinter furcton called tag. bind) to inktne act of ecking each squara inthe palate to iS eemtceceen sre PRINT SCREEN ye wr ern ys pining rt Deter bamn bet peter Th opis eepang on your ren Ten Spr on inoge og pogor ond pou Cowtel sv ‘Spot heaped meget tore Noe ‘est Corman Sil + 9 nd pe oe rap ina Preview mth Gaetal You ‘oo eo om ge {save and runtha program to teat. yout ary buga, chack your epeling. punctuation and spacing, (For more eb tps, soe pages. (28:69). Thon try making your or rastorpice, DODGE THE BOMBS Watch out! Hidden bombs lurk beneath a green field in this puzzie game. Can you find all the safe squares without setting off an explosion’ ‘THE GAME Lar Suryou nea pone, the apse urn re TSOUSOSERUERU RESIS SETTED HOW DOES tT WoRK? Tomake the gare CREATING YOUR FIELD “Toraw the fed, you need tose the tkinter modula Youslso nse the random modula. t0 yout te Gombe at rade {Lopen and save a new Coxe wink fe. “Then import the tkinter moa andthe andor modula ajo teintar oo random ‘Newt, you reo tocrmate some varios to Jueap track of whether the parse over tho score (ne rumor oF squares choked) and now mary sauares am Pe clear = pare Sp Le = teore = @ Seu squareneciaut « © LN you din tat coreputar wnat your rogram wit do, (Doing this rt helps with ‘larg, and means you don't have to wary About te anim wich you define things) —— oe py pede tome ars, you uae a gr of mambors:1 fora ‘and © for aaafe square. You can tay out last to store this, W's faster to use a tof rans. another list (roma) containing the ‘4: You need to start with an empty lat. then a Furetian tk The same fur seats = y¢ me soe squacastectenr #—— 5. Now, complete the function. First uso a for 9 ten emp ets ther for oop tarun once fo aséosranding (4,160) <20e—_ | me mm me entice appt js me eve cargeto} om me we squnrentecloar = squrantoctese a beset penta seneee JL TESTING one Livia rmgtonntayoainnces | UR agucc mms OP Srenicaccntrcon mre tout -— - “ jocterom enon: eee ro pase ee eee estanemmed “0o-" | Gaeciecen = obec (0 yom thle ie wher cut play ge Wt eee prar nae soak ees oh tharightnze. ‘Tren sine te furetion. 2 Aspley the contort of the ats. ‘der peinetnigpemetegys mei roti bomtierss | ae inte) Sales A saveanc run the program so far tote ‘da ine to caliyou play. bombdedger Tame weanbeaae | functor, the sav ae run your code. Ts cms Wi become te st ne of yar program, ‘play omer. Te ce SS easton candi §, 100) > 75 - _ —_— -_ PO mom ng tines ttn, tat = — - - -- = GREAT GRIDS, arid dos inter Meow eave id loot Soles Ocsyoree eto id yun coun her gid hetons, ach ‘Yu should see a bir tkintor window popup, ada got Oo and wil appear in he Sal ‘window, You wl alo pet an ror message, I. now you noes to ete computer to ay ott ach ‘which you win tenet step. Agiars tur ng nade the tint wie Jot) ps eat Best, you hove to layout the squares inthe Ferthis, oulwll nee new function, eridO. Gi ee gidend ima sow ty seins te layout. window O eee comm ale fupaton. Start by tang the computer took at ‘ach entry inyour ets, using for loops ands ‘uncon calle enumerate) (See below) me scot gelttoe + rome, coke = cotueonaber) if Pew te to | ul [REACTING TO A MOUSE CLICK computer recogrie a ouse-button cick wth eButeon-> emo EM ceeeneee 8 e : UUSSSUSSSATSSS SSNS INT To Sse ton = coats cain = ct a, DEBUGGING —_ Bw everyaning @ wersing, yu can am oft the print function younaded inst 6 Fe ee etre 21, To fin the purer of bomb, you rood to en, youwant the computer to check the Iael tot inthe square (even fs ust sce), 6 Forth you needa new functon, eget. Start by coaching the square below. sole % ee mF emer {column} = His ee totatnte = tats 4 IT] I Tan cheek tn square above, [B.now, check the game ail gxng 18 ‘check fr a bom ~anc ot te computer what to bit fncs on, ee ir teeta tcotemey = te eee 18, men. to tne computer wnat to ao if te ‘squire esate, Fret, youneed tocneck t hasn't been cickedairency has, you want to make brown and cplay the number a bomb FT eteintateo it tcotam) = 0 Than, cheek the square onthe right <1 ir emeetensyror totes a is ov 2 as cotta > colon] = Is yim can ow ‘oa check te aque ithe top ight core. SL el 5 oat < 1g —_$_{ a E temtieatcoe ote] = stent = otal #1 Fraly chek te nqare fo the botom right corner pe tov 9 at ent 51¢ J a benttincceitestemel = I recites cca DL Now you cheches athe surounaing ‘ouares for vom, you can capa the iota, Zi rokoep track of te score. you need toads ¢ uy Bont each tne you cick safe square AND rece ‘the squaresToClnar varabie By one SS Semen + speercione om as es B.ttyou nd ALL te mate squares tho game ‘de fa hacen tothe coiter to print a ongratuations message and the waning core, Se mesareercions = 01 SP restr tose as sxe8) 24, Te an ine of your program shoud sib {Wis itructis fom step 12. You need eto rake the game run) aoe prism devel tos comet an) te onte eqncet TISDISSSSSS 9990 5. You're fraheat Tha full cod ia shown blow. Saye and run your program to test. (you get ny error meagan, use the debugging checiet nmr alee ‘grime boa. tate ape | l BAT AND BALL ee ence ees mais fc creat ovat For cach eae joucan ot cise pace ‘You can use tkinter to create a simple bat and ball game - the es ard colour by ling the para Gauororr then see how long you.can keep the ball up in the air. = ‘eons j x THE GAME HOW IT WORKS g ry Hews tov he game wllookwtentefinaned Toman tne gue work. yur Progra pees to. I scuiane tte) crt shapes or the a at ta lake So eee Kop the bat and tal moving, Osc whan the ba oui bounce he ep + Stop the game ifthe bal hits the bottom, and oon Tostop the game running oo fae, you can ade 4 setupa pauses using a modula called time intevopae hfs mcs fe ved infront Soro doe Mc lot yon pose WUSVISSSSSSS (CREATING THE CANVAS, BAT AND BALL. {Loon and save a pew fie, import the thinter fanatime modules With ih USING ARROW KEYS 5. rypo this, to sot up a coupe of variates Tho vanabion wi tore information about len arrow hry naa boon presaed, ‘man create afurction to changed varias ian arrow lay a presse. ee FeO poset a B.the compres needs to know what todo when a kaye rleaced. Se MOVING THE BAT ‘T.Thetat can ont seoordinate wil ‘eed. formulate charge the variable, open ‘on which arrow ay has baon pressed bis forthe edges ofthe be. coord) Gee can tel were the tat BL create some vari bt anc use a fu Fiend sothe camp = (eattatt; Getee, ashe, Hameo) « ganoun cabal € ; MOVING SIDEWAYS (ON A CANVAS MavEO Pte cs td ie ipa ices soon Le bat can ony move as ng ast stays on the arya, ft ta te se, car oly go back the ‘ote ay Yeu ean use anf /andl statement to ‘Mop the bat at he left or ight eas. “Pesce ste tet opontc ym nvngr ‘ABOUNCING BALL MOVING ALL OVER A CANVAS. The alls movernts are more varie ‘ean move areund the who eam, Bouncing evaniet | tates Gf the top ard aides. So nothesxand'y cee Nate mun oarcinates wil change - represent ty to arene roe! variates: ‘batPioveX the bale lftrigr. moverants} and ‘baloney (the bal un 5, & For ramp oh stl te gore tebol bea deena op ond 2 Yountaso need ota venation fr ght ofthe at atten» cate te eer eree Sibir © i Seer screamo seston = canantet eae —— sotmasnotten = canraniighe-nee) | "SMS IM Now ereate a finstion o mave the ba tion shawls change tho cavers variates whan the tal bounce To work out whan ty tall wil Roun, use cords t nee Bas Bdge nove bali} Se batceowet, Dalewe weiter, ontop, amttighs, tattocten ~ puvencoorau(baiy 12. nen ane tat te me right acge a the cams, lestould Bounca left mang balMoveN negate) ‘iron the bal its the efedge, shoul bounce Fen (raking “balovex postive). lnentne bai hte the eapat the canoe, shou Vino the function ty movie the bal ‘Soares inore( belt, bal Nove, bal toner) 1S. ithe ball misses the bat and hits the BE bots of cna, the pas cv Messaseanx Check fortis with anew fantion, iter ho el cal mastageteon ales you check, game_aver(, You can ask the 700m ppp nines, leo kro on Sogn Boe layer wants to play again wth pop-up Yovean corbin mestogebon wh krcirs\o male ‘meaaage.A yes" wil make the ame reset specced l dcop bor or meme ipo) Serre aia es ects oe {Buen the bal reachas the bet, yourneed to workout #ithas hi the bat For the, ouneed the etatop” ant tech game over(yy (oailets, batitep, beludghs, baLtactcom) © Exomas.ccords(talt} “me Le bent > carmasseignts Sat = btn meen yee mentee swt ay op] ae ping — ee rent, SSeS step 10. FINISHING THE GAME IB. youchoose otto pay again, you need to ose te thintar window ee en KEEPING SCORE you want to koeo track of haw you're dain. you ean seks. ascore based on Row many times you ht the ba ‘1. To play again, you rend to reset your variables L1o keep score, younead anew core arabia Ase 2D tremor tous gov W180 ‘urease bat. You can dot move. allO tue 1B younso neosts maxes ne wna rest sea: tomause cicia an iy presses. Tha wilreaure ee woes eae oe hier rca: pretest sn bind } Geto Teanaeaty wreno i [ weanean cerns] 4 Fialy, make sure the scare 18. ras ca tbe reset andmain 0p ‘inet totart the gare. emte oie esee coer oe Youre rane Spang ran tha cae total ow lngcan yu iep tne bain a? yur score Inthe Sel windom, Inyour move. ballC) fuetion, dete tis ie ey andote > aan we Gane acne ae farctreplace it wih tis LE sr Lilisakr sand feline > ula ag cateaneeele ee ors the code forthe whole program, th the extn Pighighted tka thal 3. ter tourexGourt and tsp sec rene rarest sky the yur ema) rc ~~ \\ DOWNLOADING PYTHON $78 MANAGING YOUR FILES a if you don"t already have Python on your computer, -_ When you're using this book, or writing your own code, — ye FA you can download it for free. Here's how it works fora Wee eee oe nen ‘recent Windows® computer Crunning Windows® Vista or newer). Lever cneekif your computor atreacy Nas Bityou Garthave it aready, orf 1, SAVING FILES 3. OPENING FILES Python, Go tothe Start menu and etek on ‘youve the wrong veri, Pythons rd, g0 tothe“! menu of Find the fia yeu want are ght-ctck on "hbPrograma’ you rae a program wen =e raable a a free develo fromthe lek ave aw. 358 hor elt Edt with IDLE You canals ae vunneaeoaeu tener Foret See ete ree enfin icing nT to Se te Python con GR) then you have Python Fora ink, gto Uoborre Quckins: avn ASyouvmrite mare cose, gp ay the Python Shel or Code windows, fel eet arco Crenunberne.e uke iret ena. pec Py beprawiena 8, as exrer versions ot ana typen'eytho python wt Palit can thi ke ‘.pynon comes in aeteront versions, ‘town ty dierent numbers after the name Thee ook use version 9,80 ary version the: amber bagring wth a 3 wt wer Python fas wt pace on yo see To chon Save Ae again and cnogee where to neta tor your ma ‘Customize metalation option, which low you a bones ples on yout Fererample, you could sve kn My Decwents sane 4, DELETING FILES inom yeu fanaa progr, 8a pd confi up wit tangs you donne. But doule-ceck your version nubs 0 yd pate aa Ua roe gas verona (ihre ile Sererirntos nee 2. NAMING FILES Python les abs have py after the name, 5. LEAVING YOURSELF NOTES alleach fie seating sere bie to hep You can eave comments in yur cote ypu inet agin. year making changes (Created ty puting # a the tart ofa toe) you can save separate versions by acing a toleave rotes for yours! ~ cranyone ese umber eg mygame. 2.py looking at your programs. Fee exam: SERDSERPOREO DED DRED) syntax errorsare the eas bea speuing mistake, else (retto etd & program. It's totally normal to encounter KNOW YOUR BUCS Thertare three main typos of err youeay ‘rake na program: syntax. runtime and logic Some are cata to sock thin other + Spelieg regcon + dents Wren ane of tres desir. the erogram went run. for amin: your this ec inthe Soa wesw se at an errcr message, ais thei, 98 2 rexirarkihonrg where the rote conve t Coloos ifyos ranthe sae cose as saved program tha Code window yout a popu message ard see rea marn the Coe wind, DEBUGGING In coding, a spelling mistake or missing indent can br am, eotataly ror afew bugs. Here are a few tips for finding and fixing some of the most common ones. QUICK BUG CHECKLIST eaka «= Breckets ond quote morks ode 2 runtime crrorearea pels (varabtet) pom sere ne Gade window a ss message the Sh wor do wat Hie emmnide you.save andrun te eade, you wen’-ge an ‘able ether = because the range wren SUSSSSSSSSSSTSS I flog error might be ees asage, ut you wont gst the whole 6x Sas 3 fxs as -s fees ei CODE AT A GLANCE You can tell. lot about code just from looking at it this ‘ows you how. IF you want to check the meaning of —————— WHICH WINDOW? windows - the Shell window fon uses two main | - Py code window. Here are the differences. i I page shi } any words, there is a glossary on the next page. cone WINDOW | oe — ‘ i aay—$_ } long programs anid aio Thats ie mers nate tal windoa ani aoe ie ff open thao winson ‘animation 4 series of images ‘shawn ane after another to ‘make Rlookas though things ‘are moving. argument in Arthon,avalue that is ven toa function See also parameter: binding in Ayton inten ce of code i a particular ‘objet on ereon, orto eck in Bython a eaction of

You might also like