Coding User-Issue 07, September 2023

You might also like

Download as pdf
Download as pdf
You are on page 1of 207
alas THE SMART THINKING Pi USER NEEDS! C se ie | | The Future Is Code Issue Seven | September 2023 | 100% INDEPENDENT Mastering Ultimate Expert Pi Guide! . . OVER _, See Insider “™ Tips & Tricks “SS On This Epic Coding Device ™ Want to master your PC? Then don't miss our NEW Windows PC & Laptop magazine on sale now! Baa cad ECAR etc Drs a a eerie In this seventh issue we look at the advanced uses of Raspberry Pi and how to expand your experiences with it and learn its expanded uses. Our easy-to-follow tutorials show you how to create some utterly epic projects with your Pi. If it’s retro games you're looking for, our in-depth projects help you build your own vintage gaming console and so much more. Our expansive reviews section covers the very best head turning gadgets and software our team have come across in the last few months and they share their thoughts with you. Welcome to the awesome new issue of Coding User. 8 10 2 4 16 8 Learning Linux Fun Things to Do What to Do in the Terminal Linux Tips and Tricks Command Line Reference A-Z Of Linux Commands 15 Essential Commands 19 Python on the Pi 20 22 24 26 28 30 32 34 Your First C++ Program Structure of a C++ Program Compile and Execute Using Comments Variables Data Types Strings C++ Maths =i G8 ER SEBR 49 NIVSRaeseaus % (C++ Input Output User Interaction Character Literals, Defining Constants File Input Output Pi Projects Ideas + Code Creating a Loading Screen Tracking the ISS with Python Text Animations Retro Coding Using Text Files for Animation Stream Digital TV Desktop Pi Retro Gaming Media Centre BBS Client Weather Station Common Raspberry Pi Problems Contents Reviews Round Up Pivo Pod Lite Devolo WiFI6 Repeaters Twelve South Curve Flex Twelve South HiRise 3 Logitech Signature MK65O FRITZ1Box 7590 AX Tempest 512 Mic Edifier WH950 Headphones Groov-e Karaoke Boombox Groov-e Soundbar 20 JOBY Godzilla Medium Kit Cambridge Audio Melomania Rocketbook Pro ‘STM ChargeTree Go rico USB 4.0 Portable SSD Marshall Emberton Il Bluetooth [Affinity Photo 2 Affinity Publisher 2 Dx PhotoLab 6 DxO ViewPoint ZRRRLSSESRRESLRRSSRABY 104 Next Issue Your Free Issue of Raspberry Pi Learning Tey Se otelah Cel U etereCmN OS works, how the filesystem is built, and how you can list, move, create and delete files and folders. To truly be able to hack and master the Raspberry Pi, you will need to be familiar with the OS and its inner workings. 8 Learning Linux Fun Things to Do in the Terminal TERMINAL FUN Allthese com Linux distributions. fea ‘The first command we're going to use is. installed by default so enter: 5 ‘The command can be run with =1 and when executed splays Steam Locomotive traveling across the screen (hence ‘s) tering: 1s (note the uppercase also works. Fans of Star Wars even get a fixwhen it comes tothe command, you can watch Episode IVA New Hope being played out, albeitin ASCIL To view this spectacle, enter: SU ‘ «followed by: isnot 1ds are Linux-based, so not only can you use them on the Raspberry Pi but also on any of the Debian-based EE IF you've ever fancied having the computerreada random fortune out to you then you're in luck Raspbian requires you to install the Terminal app, Fortune, Fst. Enter: g then simply enter: into the Terminalto see what comes up. ‘The rev commands certainly interesting, and at First what seemsa quite useless addition to the OS can, however, be used to create some seemingly unbreakable passwords, Enter: Ea and then type some text. Then press Enter and everything you typediinis reversed. Press Ctrl+C to exit EE IF you're stuck trying to work out all the possible factors For any particular number, simply enter: followed by the number, For example, Factor 7 doesnt offer ‘much output, whereas factor 60 displays more, EE ‘There'safine line between the rather cool and the really quite weird, Having an ASCII cow repeat text to you could potentially fallinto the attr. Start by installing cowsay: “9 a then ent R In fac, youcan even output the is command through the cow, by entering 5 Ee To further the cow element, there's even a graphical ie.non-Terminal, cow avaliable. install it with a, then when 'sinstalled enter ‘something similar to cowsay, such as: P Fun Things to Do in the Terminal 8 Ean IF you really want to expand the whole cow thing, for whatever reason, then pipe the Fortune command and forthe graphical cow Plus, there's always cowthink. Try through it with ‘equivalent: EE ‘Admittedly, the command ‘toilet’ doesn't inspire much confidence, However it's not as bad ast First sounds. Start by installing it with: : when it's installed, type something along the lines of: a ‘or perhaps ist the contents of the current Folder through with; then Expanding the tollet command, you an actually generate some decent looking graphics through t. For ‘example, try this: feist =£ moni 2 David. Youn center: help, for alist of the command line argumentsto ‘expand further, BB Learning Linux More Fun Things to Do in the Terminal MORE FUN, YAY Since the Terminal session is already open, and your keyboard digits are nicely warmed up, here. Terminal nonsense. ‘Remember the old 2x Spectrum days of computing, when you could type in 10 print "Hell", 20 goto 10, and Hello would st down the screen? Wel in Raspbian you can do the same. Simply enter: ys followed by some text, i. perry isace Itkeeps going untilyou press Ctrl ‘The Matric was one ofthe most vieualy copied Films lever released and there's even a version of the Matrix code available for Linus. install with sna, When t's done enter: and follow the white rabbit, Neo. Unikethe real Matrix though, you can press Ctrl+C to ext e another two pages of EE Having a litle white cat chase your mouse pointer around the desktop may sound like a terble waste of time. Oddly though it isnt. Enter: e-get inst then type: rie to have the cat appear Move your ‘mouse’ around the screen and the cat chases it. Use Ctrt+Cto exit the action. ister | This entry isa litle more serious than the previous. Fork Bomb ia command that continually replicates itself unit has used up all the avallable system resources, eventually ‘causing your computer to crash, You don’t have to try butts interesting nonetheless. Simply enter prepared toreboot ‘and be More Fun Things to Do in the Terminal Stringing several commends and piping them through ‘other commands is what makes scripting such 2 powerful element to an OS. For example, using the while command, together with toilet, can yield some impressive result. Enter: Ee Talking computers were the craze of the ‘80s, To. reve the Fun enter , then: tohave the ‘computer repeat the text inside the quotes to you. Make sure your volume is turned up and try the Following: aE 1 ‘This gets Raspbian toread back the contents ofthe ls command. Bea ‘A roaring ASCII ire isn’t the most useful command to have at your disposal butts Fun. Instllit with: jSe=9Se asta Libas-bin, then wse: aac. Itsnot eacthy ‘warming but you get the idea, To expand the above, enter: uti, then: EE Used as a music demo from the old Amiga and DOS days, the bb command evokes memories of thee and _ahalFinch loppies crammed with all manner of demo seene goodies, ‘You've already installed bb From the previous step so just enter: Follow the onscreen instructions and turn up your volume. EE This entry is in two parts. First you need to get hold of the necessary packages: sudo apt-get install ibcurses- perl When that's done enter: a Followed by: With that itl completed, onto the next part Enter: ri 4 Providing all went wel, enter: ‘and enjoy your very own ASCIF-based aquarium, 8 Learning Linux Linux Tips and Tricks TAKING COMMAND ‘There are countless Linux tips, secrets, hacks and tricks out there. Some are very old originating from Linux's Unix heritage, while ‘others are recent additions to Linux ore, Here are our ten favourite tips and tricks. OPN cnciccicrmsgenoedoter PEMONNPNNNN Sec icdocn se oe Dunnet isa text adventure written by Ron Schnellin 1982, andhidden Then: in Emacs since 1994 Enter the website you want to vist. eee ‘Based on the classic 1982 arcade game, Moon Patrol, Moon Buggy appearedon home ‘computers in 1985 amid much praise. I's cracking Atari game available in the Linux Terminal by entering Gian Snowing in the Terminal console isn't something youcome across every day. you're interested, however enter: Thea: Enjoy L ernnnnnnneisaaazeeemmmemmnmmn! Linux Tips and Tricks (EERIE recto wtih ase consuming REY Sachin he dv of dato connections the onine wold wos the most memory onyourRaspbery made vp of Blletnoard systems. These emate serves simply enter: provided hangouts For users to chat, swap code, play games and more, . 4 Using telnet Linux, we can stilleonnect to some active BBSes Firs, ‘Thissorts the output by system memory use install Telnet wth Then: You wil be connected toa BBS dedicated to the Commodore Amiga There's plenty more, which you can find at www.telnetbbsguide.com, Replace NAMEOFFILE with the name ofthe fileto delete. Se BEY you wantto create an entire directory (or Folder) tree witha single command, ‘This creates a New-Dir with Four sub folders within. onthe Raspberry Pi by using ma2txt: Replace NAMEOFIMAGEFILE withthe actual name of the image File on your system, FORGOTTEN COMMANDS [Eker Femember al the available Linux commands. Thankfuly, you can use apropos tohelp, Simply use iewitha description of the command: Learning Linux J Command Line Quick Reference WiEMecute emetic e MN Meme Sue uct te MCnceteg eee ee eee CSM cu eT aC) ee ec ocu dedi el NE Pee kate eu ca eRe ete crete is designed to help you master Linux quicker. TOP 10 COMMANDS These may not be the most common commands used by everyone but they will certainly Feature Frequently for many users of Linux and the command line ‘The’ed! command sone ofthe commands you wil use the most at the command tine in Linux. tallow youto change your working directory. You useit te move around within the hierarchy of your file system. You can also use chit ‘The'ls'command shows you the files in your current directory. Used with certain options, it lets you see il sizes, when files where created and fle permissions. For example, 1s" shows you the files that are in yourhome directory. ‘The’cp! command is used to make copies offiles and directories, For example, ills makes an ‘exact copy ofthe file whose name you entered and names the copy sub but the First ile wil til exist with ts original name, ‘The ‘pwc command pints the fll pathname of the current working sirectory (par stands For “print working directory’). Note thatthe GNOME terminal als dsplaysthis information inthe title bar o its window. ‘The lear’ command clears your screen f this ispossible.Itlooksin the environment forthe terminal type and then inthe terminfo database to Figure out howto clear the screen. This is ‘equivalent to typing Control when using the bash shell ‘The mv command movesafile toa different location or renamesafile. For example iy {18 {535 renames the original file to sub. si sub =/ Da=IGE6 moves thefile‘sub'to your desktop directory but does nat renameit. You must speciy 2 ‘ew filename torename a file, The ‘chown’ command changes the user andor ‘group ownership ofeach given file. IFonlyan owner (@ username or numeri user 10) given that user smade the owner of each given fil, andthe files! ‘group isnot changed. The’‘chmod! command changes the permissions Conte files listed, Permissions are basedona fairly simple model You can set permissions for user, ‘group and world and you can set whether each can read, write and or execute the file The ‘command removes (deletes) files or directories. The removal process unlinksa filename ina filesystem from data on the storage device and marks that space as usable by ute writes. In ‘other words, removing files increases the amount of available space on your disk Short for°make directory’, ml is used to create directories ona filesystem, ifthe specified directory does notaleady exist For example skal Wark creates a work directory. More than one directory may be specified when calling mkdir. Command Line Quick Reference A-Z of Linux Commands There are literally thousands of Linux commands, so while this is not a complete A-Z, it does Creu cueUS Sen ued as mC esas up using a smaller set of commands over and over again but having an overall knowledge is still very useful HERE 02.2 0419 convertand EEN Sh forint A copyatie ‘mattha given pattem PEER 950) :he eens NNN Prine rcup aeso ser EEE 4 a new user ‘between two files isin ea BEEN Conver afulpthoame ER Conpresor decompress architecture tojustapath amedfie(s) HER Fins cpicetnc NNN Estnstefie space sage within Files) H B artivay precsion aloatorlanguage EER es ond pint onthe standard ou EEE Change worina rectory EEE Cengete z000 coumarin oes HESSEN ge cet creo (BEINN Prin: CRC checksum and Besos HEME Corparetwofes HEE Corouretnosoredties TEER Oy regen Aline rentedtestedtor (edie) HEE S30 fories thatmetchaneended exresson HME 9 ct oreroe votre atl EIEN Conertatstosaces HEE Setsteoresons Ey EEE corneas TEER son tie rani for Lx (EE S221 File(s For tines EER ut putthe Fst partoF filets HR it serandorunids ERIN pies ands attributes HEE 220 inesonscomen ie K TERE 89 29th inebyine thatmatha Fed sting unig HEI oor ore esto Seacforlesthat meet, snotharleeaton Beesred era I HERE She sconmandto NNN Reformat paragraph gnatabtertire fet ____ RY spaycutputone BRE Sitsficioconne NN Weaptetorte sacenatatme ‘eterrined piss soedied wath MRR sistance RE OiiseaFierno ceo! ENN Format cisortnes pure infies pets pp Fiesystem consistency Sesemcons TEER caren iognnane D SEI ie itr contro G scorn ER Display orchange the TEM Offic prt deteatine Find and Replace text. EEE ern0ve jobs From the HE clatter whines prntqueve 16 | AZ of Linux Commands a HEREEMINNN Format and print cata Q FEEEMNNN 0014 isk usogeand limits HEREIN Sean fie systemfor dk usage Cees R HEU sie Change le imestamps Lstprocesses runing on thesystem Trace Route to Host Trandate, squeeze andor delete characters Topologialsort Unmount device Convert spacesto tabs Uniguly Fes ee EE Fecvicdow anager EER Verbose it rectory EMI Cet new folders) EER Meroe to fesinteractvely contents (154-6) HEE 2160s romed EE Ace ebosrdnout pipes) ERS int turmeric sequences | HER Bete d0u2 = program periodically EER 5014 output one TE Detsyforaspectiedtime — ENN) Print byte, word, and soeenatatine * pratbe A HEI Sotto ries HE our fiegstem i EEE 70% kro0n TEE 502 fiir fesse intancesofs HOR Substewserierety I Locte aproarmtie HEE Sethe priorityof DU Pein: 2 chectsumforafile inthe userspath command orob TEIN ctcorcwromeforatic © ENN] rintal usernames DE erberivesandoie I syctonse cataon dk cet gpedin files pipe HRN te cuetser EE 212 commandimmune eae ares wohangups xX HEE Conctenate ond wte P rieshevese HERE 6% iy pasing consruced argument MER iyo useepesvord ppm uicutelst prof ies HERE erg nes oies Fes HEE Ceci ienare HE Teo Active Y portability PEER Pecicectoutputto MN orertnc fest miles MER 2 sng ee prating PEE Evaluate a concitional interrupted HN Pinter cpcbity expression cao EER Measure Program BRN Fe enirnment pesours Use wats foul — = — — = Ero I a ENN 2p lesbetween two Comertuntsfromone machines sealetosnother HR rove ies HEU psccstel active —__ amma sos ares DEERE este ser acount Manager PE Mot) ser account [EEE note ile cory (EER st users curreny Gyno fetes) loygedin 8 Learning Linux J 15 Essential Commands eer Me MT ete eMeCicenetcRess ate CUS Stel ne ect Ne Maa ene eat se ee ecn eed ee Meehan ates Renn UR nue COnen nary You wil often Finthe need tolisthe avalable storage devices oF your Linux system. The bikisone ofthe mast used LUnux commands for ths purpose. Thishandy terminal command wil present you wthatree structure of your storage devices. 2 HERE Senviceisthedefaco commandto invoke systemwide services fromthe termina A powerfulLinuxterminal command for manipulating the system you can leverage ths command for running ay script rectly from the teial window. 3 ER 1h In commandisacever Un struction For creating symbol inks toa specie. Youcan use thisflexble command toproduce mutpeinstancesofasymboicink toafile ordrectory,onyour disk space 4 HEREIIMIE Thicisone of the most used Linux commands bysystem admins, ait allows them to replace a word by another string directly fromthe terminal. Among other Functions, hiss one of the best terminal commands through which you cancustomizethe shell and manipulate environment variables, 5 EB Th Cal commandisone of those fun Linux commands which shows you the curent date at acalendarinan ASC text format. Type this command, with parameters lke month and year, to get pected information right into the terminal. 6 HERE Want to check the history of your terminalcommandsessione? The History command lets you do precisely this, When ‘ypedithout any parameters, this wl print tthe bash histor of your terminal session. 7 TEENS Thisicone ofthe best Linux commands for downloading fs from the ‘web direct from the terminal. itsaso one cofthose handy ltl terminal ommandsthat canbe usedin scripts, and provides userswith the abittyto use the HTT, TTES, and FTP Internet protocols. 8 HEREIN The lotablescommandisa termina tity that etssystem admins contro the incomingand outgoinginternettrafficon _any machine iis among the most used Linux commandsto deine authentictrffcsandfor backing suspicious or untrusted network requests. 9 HR 64 orrathercuRt, avery powerful nebiorktoolfor transfering files vera netverk Tiss one ofthese nx commands designed to work without user interaction ndisofen employed in network teated shel scripts. 10 HEREIN Probably the mostusedLinux oreand, Youve areadyusedi throughout this book, andits one that youllkeep coming back to asyouprogresswith Linux Basically its nore privlegedusersgainaccessto, and modi les that only hightevel users an access. 11 From the Terminaesson, or From the ‘curren usergroup to the ast group. Its ‘aso.sed when youneed to exit froma remote connection inside the Terminal 12 wilesplaythe Fist ten inesof file, extremely useful for when connecting to _aremote stem and trawling through rmutiple Fes 13 HEE The Typecommand wildsplay information regarding any ‘ofthe curtent commands installed in the system. For example wil splay the location of any of the Terminal ‘commands so you know were tolook Forany lost packages. 14 HER Opens the vite estorinthe Terminal. Visatradtional ‘command, which st appearedin 1975 ~over 43 yearsago,andisstitone oF the top, go-to text eitrsfor seasoned system adminsand users ake PD) ‘command, although quite powerful ‘The W command wil dsplay exactly whois loggedinto the stem and what they're doing, Used by system admins to ‘see what’ going on in ther ystems its ‘something youll probably come to use as your Linuxsls improve. Python on the Pi Being able to code is part of making not just the Raspberry Pi, but all the connected devices that can access the Internet, do what you want them to. The REM TNT nctd coding base that comes pre-installed with the latest version of one of the world’s most popular programming languages: Python. 8 Python on the Pi Starting Python for the First Time OEM ee iene cu ane ae ee i oss uu case need to manually install the Python IDLE. This is due to the Pi team removing the core Python Raed coeen ha unicimenikecs lent cor STARTING PYTHON For those using the Pi 4 and new Raspbian drop into a Terminal and enter: acs) apt=get instal) dle, Older versions of Raspbian ‘already have the oficial Python IDLE pre-installed. Wahi dep ded kote PERPNI Forme Str 3a uae) ‘button followed by Programming > Python 3 (IDLE). SUE) ‘After pressing Enter, the next line will display the Thisuilopenthe Python Shel. WindowsandMaciescanfindthe answer Bascal Pytonhastaten the ode’ ed produced the Python 3IDLE Shel rom within the Windows Start button menuand relevant output. via Finder, Se) a eens rset HA Set iBe tie “Lint” for mre intra, The Shells where you can enter code andsee the The Python Shel acts very much ike aaluato since BUSHLAND responsesand output ofcode youve programmed ALND code isbasicalya sees of mathematiainteractons into Python. Thisisa kind of sandbox, where youre abletotry aut withthe system, Integers, which ae the infinite sequence of whole some simple code and proceses. ‘umber an easy beaded, subtracted, multiplied and 0 on, ‘Be EB Shot Gees Spe dows a ie bt fetete ee 92 TTY Starting Python for the First Time a ‘While thats very interesting, t's not particularly SuBPS exciting. Instead, try this: print (*HoL1o everyone!) Just enter itinto the IDLE as you've done inthe previous steps. pe Seppe Sredts” oe “Isc y" for more snferneian, “The Python DLEisa configurable environment. Fyou dont ike the way the colours are represented, then You can always change them via Options > Configure IDLE and clicking ‘onthe Highlighting tab, However, we don't recommend that as you ‘won't be seeing the same as our screenshots. ne youve ji rodeed Sa ‘your first bit of code, The Print command is Fairly ‘self-explanatory, it prints things. Python 3 requires the brackets as elas quote rte morro ouput content tothe cren nie Chae the Helo everyone! bE. >> print("Hello everyone: hello everyone! >>| BETTE 25 tke most programs available regardless ofthe ‘operating system, there are numerous shortcut keys ‘available. We dont have room for them allhere but within the Options > Configure IDLE and under the Keys tab, youcan see lit ofthe current bindings. FontsrTabs | Highlighting | Keys | General | Custom Key sindings ‘Action -Key(s) begnangofane - centeraneart - The Python IDEs a powerulinterface and one Sal that's actually been written in Python using one oF the avlable GU toolkits. Ifyou want to know the maryins nd ous for the Shell, we recommend you take a Few moments to view www. ddocs.python.org/3/library/idle.html, which details many of the IDLE’ Features, IDLE Colour Coding [Feotour [use tor exampies | et fees ne a a ee tees ee | Your First Code Essentially, you've already written your first piece of code with the ‘print( "Hello everyone! function from the previous tutorial. However, let's expand that and look at entering your code Reem R meneame acuta PLAYING WITH PYTHON With most languages, computer or human, isa about remembering and applying the right words tothe right situation. You're not born knowing these words, so youneed to learn them. FEISPE you've cosed Python 3ILE,eopenitin whichever RBNSNBNWNI You can se that instead ofthe number 4, the output ‘operating system version you prefer. nthe Shel, isthe 2+2 you asked to be printed to the screen. The enter the Familiar Following: {quotation marks are defining what'sbeing outputted to the IDLE. print ("Hel10") ‘helt to print the total of2+2 you need to remove the quotes: print (242) PEPE) 0st 2s predicted, the word Helio appearsinthe Shell FRMWAWIIN You can continue as such, printing 2+2, 46442343 and asblue text indicating output from a string. W's Faity so.onto the Shell. An easier ways to use a variable, straightforward and doesn't require too much explanation. Now try: which s something we will coverin more depth late. For now, enter: print ("212") Your First Code Se ‘what you have done here s assign the letters a and b SuBPS ‘two values: 2 and 2, These are now variables, which ‘ane called upon by Python to output, add, subtract, divide and so, ‘on or as tongs their numbers stay the sare. Try this: pent (3) peint (6) PRET Now ietsaddasumame: surnane="Hayward” print (suenano) ‘You now have two variables containing a firstname and surname ‘and you can print them independently. He a shal Cotas pes wwe The output ofthe lst step displays the current values SUES ‘of both a and b individually, as you've asked them to be printed separately. Fyou want to add them up, you can use the Following: Beint (arb) ‘This code simply takes the values ofa and b, adds them together and ‘outputs the result. IF we were to apply the same routine as before, using SE) the + symbol, the name wouldn't appear correctly in the outputin the Shell Tryit: print (nanetsurnane) ‘You need a space between the two, defining them astwo separate values and not something you mathematically play around with. ‘Be £0 Su) Sey tone wien se ae sai ‘You can play around wth different kind of variables BALM anc the Print function, For example you could asign variables for someone's name: nane="David” print (nano) {ie BB Sha aot row b> PERRET |: Python3 you can separate the two variables with 3 space using a comma: ‘BEint (nape, surnane) ‘Alternatively, you can add the space ourselves: print (name “+surnane) “The use ofthe comma is much neater, as you can see. Congratulations, you've ust taken you Fist steps into the wide world of Python, ree ee A me TT erste) > panty 8 Python on the Pi Saving and Executing Your Code SET MTeoR MPa SeSi Sec eA ROI [Reels Ea) ol Maen ael (eee entering longer program listings. In this section you're going to be introduced to the IDLE Em MMe ihioM nell EDITING CODE ‘You wil eventually reach a point where you have to move on from inputting single ines of code into the Shell. Instead, the IDLE Ealitor wil allow you to save and execute your Python code. EEE Sec prtencstandvtentain, INI vou cae itera clon odnghinpin Clk on Fle> New eT wl pero new vido theIDLE ator sits inthe Sel enabling youto wth UnitledasRsname.Tislsthe Python DLE Etc andthe beter understand what's going on wth yourcoe However to Yyoucanenterthecodeneededtoceateyourfutire programs. excite code you need tofist save Press FS andyou get Save...checkboxopen. PERI Thei0LE Edtoris foralintens and purposes + ‘kon the OK bitonn the Sve bxand select Spe tet ector wth Python features color cng destination whereyovl sae alyour Python code andsoon muchinthesime venasSibineoventercodetsyou The destnatoncan bea dedicated fede caledPythonoryoucan would within the Shell, so taking an example From the previous just dump it wherever you like, Remember to keep a tidy drive though, tutor eter tohelpyoucut nthe tre “int ("Hello everyone!” ory he Eo Famet tin Bote edo Sp Saving and Executing Your Code a Enter a name for your code, ‘print hells For example, {and click on the Save button. Once the Python codes. saved it’s executed and the output willbe detailed in the IDLE Shell. In this case, the words Hello everyone’. Lets extend the code and ener Few examples from suse the previous tutorial: = be ‘rane=oavid? surname="ilayward” print (name, surname) print (at) IF you press FS now youl be asked to save the le again, asit's been ‘maxified from before. Tissue st iy aha Pn el Tema bast ein? ate ctranna fecaphietel oeion yee depending on whether you've requested a separate window, but essentially that’s the process. It's the process we will use throughout Sous aber TE Ee oo a IF you click the OX button, the file willbe overwritten with the new code entries, and executed, with the ‘output inthe Shell Its not a problem with just these few ines but you were to edit larger ile, overwriting can become anissue. Instead, use File> Save As from within the Editor to create a backup. IF you open the file location ofthe saved Python code, you can see that endsin py extension. Tisis the default Python filename. Any code you crete willbe whatever py and _any code downloaded from the many intemet Python resource sites willbe py Just ensure thatthe code is written For Python 3. "Now createa new ile. Close the Editorand open a BUD instance le>New Fie from the Shel). Enter the following and save it as hello.py: a="Python" boric” coool!" print(a, bie) ‘You will use this code inthe next tutorial. Tao py. Pre p DecarrertePynon Cosa wy BAD eat fmt fin site wd tle ®B Python on the Pi Executing Code from the Command Line COMMAND THE CODE Using the code we created inthe previous tutorial, the one we named hello py, let's see how you can run code that was made in the GUL at the command tne level Bea Python, in Linux, comes with wo possible ways of Eo Now you're a the command line we can tart Python. executing code Va the command line, One oF the ways For Python 3 you need to enter the command python3 |swith Python 2, whist the other usesthe Python 3 libraries and soon, and press Enter. This wllput you into the command ine version ofthe First though, drop into the command line or Terminal on your ‘hell with the familar three rightacng arrows a the cutsor (>). operating system. EE Just as before, ~ EE From here you're able to enter the code you've looked were using a| SEcEs at previously, suchas: Raspberry P: Windows users “ = will need to click the Start button and search for CMD, then click the Command Line returned search; and macOS Users can get access to their You an see that it works exactly the same, command line by clicking Go> tities > Terminal, Executing Code from the Command Line @ EE Now enter to leave the command line Python session and return you back to the ‘command prompt, Enter the Folder where you saved the code from the previous tutorial and list the available files within; hopefully you should see the hello.py file. Bea From within the same folder as the code you're going tarun enter the Following into the command tne: Thiswill execute the code we created which to remind you's: Bea Naturally, since this is Python 3 code, using the syntax ‘and layout that's unique to Python 3, it only works ‘hen you use the python3 command, Fyoulike, try the same with Python 2 by entering Ean ‘The result of running Python 3 code from the Python 2.command lines quite obvious. Whilst it doesn't ‘error out inary way, due tothe differences between the way Python 3handles the Print command over Python 2, the result isn't as we ‘expected. Using Sublime For the moment, open the helo File. EE ‘Since Sublime Text isn't available for the Raspberry Pi you're going to temporarily leave the Piforthe ‘moment and use Sublime as an example that you don't necessarily need to use the Python DLE. withthe hellopy file open ateritto include the folowing HERE Ceanor Ha Bex Save the hello.py file and drop back to the command line. Now execute the newly saved code with: P ‘The result willbe the original Python s cool statement, together with the added input command asking you or your name, and displaying it inthe command window. Python on the Pi Numbers and Expressions Meee eure n Mua ruPe eeu Wha oe eee reed nara eto PPR oP) e ea eM eel nC Colt cs lator. You can work IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as with most, i not all, programming languages, maths Isthe driving Force behind the code. ‘Open up the GUI version of Python 3, as mentioned ‘you can use ether the Shellor the Editor Forthe time being, you're going to use the Shelljust to warm our maths ‘muscle, which we believe is @ small gland located atthe back of the brain (or not). (eer sot) en tines Am Seon tts hewaec ‘eran an nalts Sicintoyoadastnvon eas few, for example: PE See ae a ise Seenresahe eres REI 0 the shell enter the folowing: 242 5¢396434553245 (99867344427344084221 You an see that Python can handle some quite large numbers. FRPP Youve no doubt noticed, division produces a decimal ‘number. In Python these ae called loats or Floating point arithmetic. However, fyouneed an integer as opposed toa decimal answer, then you can use a double slash: ve 61/2 {ndso0on. Numbers and Expressions a Yeransioueancpeionseterennde EARP Tiwi dened certain auerS left over From division. For example: 10/3 aa into binary and adding the prefix 0b to the front. IF ‘wil display 3333333333, which is of course 3.3-recuring. {you want to remove the Ob prefix, then you can use: IFyou now enter: 1083 format (3, *b) ‘Thiswill display 1, which s the remainder let ever From dividing 10 The Format command converts a valu, the number 3, toa formatted by3. representation as controlled by the format specification, the’ part. ‘S= E oe) Gey Gee ae BO [fae aatienimes ee Be ee “eri! rats” thse fr ware teen, ‘Next up we have the power operator, or ‘exponentiation ifyou want to be technical To work ‘out the power of something you can se a double multiplication symbol or double-star on the keyboard: ae 1010 Essentially i's 2x2x2 but we're sure you already know the basics behind maths operators. This show you would work tout in Python. fa ‘ABoolean Expression isa logical statement that wil ‘either be true or false, We can use these to compare data and test to see ifit's equal to less than or greater than. Try thisin ‘aNew File: peine(2, print(2, print (3, print (4, print (5, print (6, a Numbers and expressions don’stop there Python PERE /I — ERM rrscssarreincomeanerces Pelt SST numbers, absolute values, complex numbers and a host of 5 . L________J neni anoeatonrte tt RPE pion maces example, to convert a number to binary, use: of True or False statements, depending on the result oe of the two defining values: 6 and 7. It's an extension of what you've Inked onden pron pf poms Python on the Pi Using Comments When writing your code, the flow, what each variable does, how the overall program will operate and so on is all inside your head. Another programmer could follow the code line by Tel teem a een eee iret ele #COMMENTS! Programmers use a method of keeping their code readable by commenting on certain sections. Fa variable is used, the programmer ‘comments on what it's supposed to do, for example. I'sjust good practise. ‘Start by creating a new instance of the IDLE Editor Resave the code and execute it. You can see that the Seri (File > New File) and create a simple variable and print SUE) ‘output in the IDLE Shells still the same as before, ‘command: despite the extra lines being added. Simply put, the hash symbol (#) m0 denotsa ine of text the prosrmmer can insert inform ther, and rine (om vanaToC arises) ater of wha’ going on without the use being aware. Savethefleand execute te coe. Python 3.42 Sel Comments py -/homno/p/Documen /Python Codey fe Edt Format sun gotone wrdows Heo 0 IAt(-The value of A 18.7. a) PEPEIEYIY Resning the code willretumn thetine: The value oF Ais, PRUMRWAWIY Lets assume thatthe variable A that we've created is ‘0into the IDLE shell window, which s what we the number of vesin a game. Every time the player expected. Now, add some ofthe types of commentsyou'd normally dies, the value is decreased by 1. The programmer could insert a see within code: routine along the tines of: 4 Set the start value of A to 10 sal print ("You've Just lost a 1ife!”) # Print the current value of A print ("You now have", a, “Lives left!) print ("the value of A is,", a) W Print she current value of Print the current value of & Prine(-The value af A 4s.". a) Jbrinte"the value of A is-~s a) a) / ost a titer") q Set the start value of A to 10 10 Brinte-You've gust Print(-You now have", 3, “Lives I Using Comments Se hie we iow tet the variables ves, and hate g175 player has just lost one, a casual viewer or someone checking the code may not know. magne Fra moment that the code ‘is twenty thousand lines long, instead of just our seven, You can see fou handy comment ae Ine comments are comments that follw ection ma of code. Take our examples From above, instead oF inserting the code ona separate ne we could use: sel0 # Set the start value of A to 10 Prine ("the valve of Als," a) # Print the current value of aval # Player lost a Lite! Prine ("You've just lost a £68") Print ("You now have, a, “ives left!) # Inform ae ASE] Essentially the new code together with comments SUEHS ‘could look like: {Set the start value of A to 20 a0 + print) the current’ value ora print (The value of A is,", a) ¥ Player lost a life! wel # Inform player, and display current value of & (ives) print ("You've just lost’a/2ife!”) print ("You now have", a, “lives left!”) ‘The comment, the hash symbol, can also be used to ‘comment out sections of code you don't want tobe ‘executed i your program. For instance, Fyou wanted to remove the first print statement, ou would use: # print ("the valus of A is,"; a) £ Sntore player. and display cont value of & (Lives) we just lost 9 Tite!) Youcan ue conmensin different ways For example, UEP ‘Block Comments are a large section of text that detaiswhat'sgoingoninthe code, sichasteling the code reader what variables youre planning on ung: mais is the best gane ever, and has been developed by a crack aqind of Python experts {sho haven't slept or mashed in weeks. Despite being very snolly, tho code at Least works xeally well. ‘Youasouse thre single quotes tocomment outa Susy Block Comment or multi-line section of comments. ace them before and after the areas you want to comment for them tower ‘This As the best gane ever, and has been developed by a crack aquad of Python experte sho haven't slept oF washed in weeks. Despite being very seelly, the code at least works really well. Python on the Pi Working with Variables ecient Sis Rae Ec gai EOC mnie nu RUC ere Mme er coeur) assigns certain values to a variable. VARIOUS VARIABLES You'lbe working with the Python 3 IDLE Shell inthis tutorial. Ifyou haver't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. Insome programming languages you're required to use a dolla sgn to denote astrng, whichis variable made ‘up of multiple characters, suchas a name of a person In Python ths isnt necessary. For example in the Shell enter; name="David Hayward” (or use your own name, unless you're also called David Hayward). Youveseen previously that vaiblescanbe sue?) concatenated using the plus symbol between the variable names. In our example we can use: print (name +“: "+ ‘Lse). The mil part between the quotations alows sto adda Colon anda space as variables re connected without spaces, soe need ade them manual. You cn check the type of variable in use by suse issuing the type () command, placing the name of the ‘variable inside the brackets. n our example, this would be: ‘Eye! (name).Adda new string variable: ritie="Descened fron Vikings". SSo"eiees"ocscenees tram vikings ‘aoanboonin wan male walt ra came emebosvane nde seinisnnscareunnee sca ome oes Kee ee eran ie eae wh eae veo Tipe “License(D* for more infornation. "Brave "oanie iapnord= Soo theta oescendes from vikings” S53 fein craneso ts See S33 Gnarbcter-aana ost So Sine Ceharseter) Bees Hapesra Bescended fron Vikings SSeaecte bos type tage) ate Working with Variables 6 However,you cart combine both strings and integer a1 ‘type variables in the same command, as you would a set ‘of similar variables. You needto either tum one into the other or vice versa. When youdo try to combine both you get an error messager: peint (nane + age) ‘This presents abit of problem when you want to ‘work with a number that’s been inputted by the user, _a.age + 10 won't work due to being a string variable and an integer. Instead, you need to enter: int (age) + 30 ‘This wil TypeCastthe age string into an integer that can be ‘worked with. Thisisa process known asTypeCasting, The Python Baa print (character +“ is “+ ste(age) +" years old." oryoucan use: print (character, “ist age, "years old.) Notice again tat inthe last example, you don’t need the spaces between the wordsin quotes asthe commas treat each argument to Print separately >>> print (nane + age) Traceoack (wast recent call last) File scpyshellsta>. Line tin moduler print’ (nave * age) TypeError:\Can't convert “int” object to str amplicitly, 3B prant (character + = an'* s\str(age) ©." years old.")| Bavdd Hayward: Descended fron Vikings ie 14 years eld. 33> prane (character. "is". age, “yesrs old.) Savill Haywarar Descended from Vikings ts 44 years Eo “Another example of TypeCastng i when you ask For input from the user, such as aname. for example enter: age= input ("How old are you? *) ‘Alldata store from the input command is stored asa string variable. frytton F-43 (oetault, oct 1 FT TH (eee 43:4) en tana hcanae()" for nore internation, eciage SEF oy Tessa peasant a wihfsongpsnanaierenrternnoes Outhnes econ Feean ee aie Mot SESE npr nr nad ve Hen matics Python 3.4.2 (aetoult, Get 19 2014, 15 (ace 4.9.1} on lin Type Scopyrsghes“eresses" or “License” for fea ‘When combining integers an floats Python usually converts the integer toa Float but should the reverse ‘ever be applied it's worth remembering that Python doesnt return the exact value. When converting afloat toan integer, Python wil ‘alyays round down tothe nearestinteger, called truncating; in our ‘ase instead of 1999 t becomes 19. Python on the Pi User Input Wes arse dee om ee UR neers BeBe AE eed Teme eee eee h iuckn (oct eee hicsits eo ae eteRe eo CoRR Reo g USER FRIENDLY ‘The type of input you want From the user will depend greatly onthe type of program you're coding. For example, a game may ack fora characters name, whereas a database can ask for personal detals. If it’ not already, open the Python 3IDLE Shel and sua? start @ New File in the Editor. Let's begin with something realy simple, enter print ("Hello") firstnano=input ("what is your frst name? “) peint (*Thanks.") ‘Surname=input ("And what 1s your surname? “) Now that we have the vers name stored ina coupe SUEHE) of variables we can call them up whenever we want: print (‘Welcone", firsinane, surnane, ". 1 hope you're well today." PEPE) seve and execute the code, and as you already no New Fil, and beginwith the friendly conformation applies to the rule: input variable: word=input ("Please enter a four-letter word: “) word=input ("Please enter four-letter word: *) word_Length=Len word) Af word length == 4: print (word, “is a four-letter word. well done.) ‘The double equal sign (==) means check something is equal to something ese. PY "ow we an create a newvarabe,thenusethelen MWAINI The colonat the end of tells Python that this function and pass the word variable through to get statementistrue do everything after the colon that’s the total number of leters the userhasjust entered: indented. Next, move the cursor back tothe begining ofthe Editor: wordeinput ("Please enter 3 four-letter word: *) word=input ("Please enter @ four-letter word: ") word _length=1en word) word_length=Len word) if word length == 4: print (word, "is a four-letter word. Well done.) else: print (word, "is not a four-letter word.”") Eee Press 5 and save the code to execute it. Enter a fourletter wordin the Shell to begin with, youshould have the returned message that t's the words Four letters. Now press F5.again and rerun the program but this time enter afivedetter word. nota Fourletter word ‘The Shell wil splay that [ Conditions and Loops S PTI) ow expand the code to include another conditions. Eventually, it could become quite complex. We've ‘added a condition for three etter words word-inpat ("Please enter @ four-letter word: word _Length-len word) Af word_length == print (word, “is a four-letter word. Well done.”) elif word length — print (word, print (word, “is a theee-letter word. Try again, wis not a four-letter word.*) ee eee eee eee ec ee ee ee ee Peete teeter nie onl er ay Se ee oe tats indented ile gets erred coment eee Cee ere Nate Peet eee er eos ree ert over arange of data, usually alist stored a variable inside square brackets. For exam eee te ret eo fees 3 and last numbers us MB Python on the Pi Python Modules MASTERING MODULES. Think of modules as an extension that's imported into your Python code to enhance and extendits capabitties. There are countless modules available and as we've seen, you can even make your own. Ee ‘Although good, the builtin Functions within Python are limited, The use of modules, however, allows usto ‘make more sophisticated programs. As you are awa Python scripts that are imported, such as import math modules are Eee ‘Some modules, especially on the Raspberry Pl, are included by default, the Math module being a prime ‘example. Sadly, other madules arent always avalable A good ‘example on non platforms isthe Pygame module, which contains ‘many functions to help create games. Try-import pygame EE ‘The resultisan error in the IDLE Shell asthe Pygame ‘module isn recognised or installed in Python. To installa module we can use PIP Pip installs Packages). Close down the IDLE Shell and drop into 8 command prompt or Terminal session. Atan tlevated admin command prompt, enter ister | ‘The PIP installation requires an elevated status due it installing components at different locations, Windows users can search For CMO via the Start button and rightclick the result then click Run as Administrator. Linuxand Mac users can use the Sudo ‘command, with sudo pip instal package. Python Modules est meno eed a eum encanto robens ifn element Pannen eaneenon anes onsen ote naneesnoa bonoaramo "Multiple modules can be imported within your code, STEPS ‘To extend our example, use: import random import math for 1 tn range(5)+ peint (random. xandint (1, 25)) print (math.pt) Br Fie ese Namber david Document? ythor/Rod Wi Format_Run Options _Wingow Help = 2 an range(s)+ [Print (random, zanaint (4, 26)) pein: mach.pt) The modules contain the extra code neededto SUEHS achieve a certain result within your own code, as we've previously experimented vith For example: import random Bringsin the code fromthe random number generator module. You can then use this modulo create something he een Print (andon-randint (1, 25)) TB Uete Fic Edt Fost Run Options Window Help 4 in range(i0)# eine (zandom,zanaine (1, 28)) ‘The result isa string of random numbers followed by Deane Sausfon tei a senmanwaot nae wace soetalcranicoos _a module by using the from and import commands, such as: +camciatipe a Brot CAeae/deid/ Document tho Opscne Window Hele Format Run a sn range(si Print (ranaan= (2, Tiiach whens oneal ilint Tpamrnenfon’ tot acrgurotnd with the code to display more or less, and From a great or lesser range. forens rs This helps create @ more streamlined approach to STEP 10 programming. You can also use import module", wich wllipor eveything defined wthinthe named mode, However soften reardedase waste of esourcesbutk works ronthless Fly, moddescanbeimprted eases. inport math as’ paintinpl} Feo adding comments lpsto tal ters wha sng on [a Rng Number py ~ C:/Ucer/david/Documents/Python/Rnd Numberpy Fle Eat Format Run Options Window Help peant (mera) Python Errors TeeeM nee Cente Reese ur rem lgen Mra declares it's not able to continue due to something being missed out, wrong or simply TUNES Clcumuee eam coa rte ae uiuies DEBUGGING Errorsin code are called bugs and are perfectly normal. They cn often be easily rectified witha little patience. The important thing isto keep looking, experimenting and testing. Eventually your code willbe bug ree. BEY ose srtasfiidasthe witten word,nomatterhow FESSSENWINK Thankfuly Python shelpfl when t comes to ‘900d the programming language is. Python is isplaying error messages. When you receive an error, certainly easier than most languages but evenitispronetosome __inred text from the IDLE Shell it wil deine the error sel along with ‘annoying bugs. The most common are typos by the user and whilst the line number where the error has occurred, Whitt n the IDLE €e25y to Findin simple dozemine code, imagine having to debug Editor this is alittle daunting For lots of code; text editors help by ‘multithousand line code. including tine numbering. a ee Se ee » wv &. Tmasaed S90 cotconenteontoenpaac SR aR ROT ORE SUH mentioned. The typos are often at the command levet: suet) errors you'll come across asa programmer. Even if the neopiatep ical ner alga cancemdat ag oan when youhave numerous variables allof which havelengthynames. often occurs when Python 2 syntaxes are applied. The most annoying The best advices to simply go through the code and check your spelling. _of theses the print function. In Python 3 we use print("words”), Whereas Python2 uses print “words”, Then 3A? Caetoule. ter 8 PON (ee 4.8") on Type empyrig's seregita- or “cans for synebcaeror’ dnvalie syrcax enetapeles) : ebro repre’ ox oat defined Python Errors a Pesky brackets are also a nuisance in progremming SUBS errors, especially when you have something like: print (balanced cheek input ())) Remember tat for every {there mustbe an equal number of. mere ays det tatances checkl ant: ee ae harecter = Uisttdatad 1 trate crac > r {character sn reference tay is Stack oppenatenoracter) Ut character sn reference values) and Lentstack) > 0 E chars stack pop) te iP reference get (ehar) = enaracter: cts, 1 lentstack) = 6 “An excellent wayto checkyour code step-by step BUSI 510 use rython Tutors Vsvalse web poe, foundat wanupythontutoccom/vsuaiz hemlsmode=edi. Spl pase your ‘odeinto the ecto and clckthe VisualeExection button oun he ‘elie byline Ths helps to ar bugs and any misunderstandings. There are thousands of nine Python sources, code Ser ‘snippets and lengthy discussions across forums on ho best to achieve something Whist 9 percent oF good code, dont always be ured int copying and pasting random code into your tetor More aten than not eon workand the worst part that Youhavert art anything. ‘ae map ort nr en ng en Ee Indents are a nasty part of Python programming that a lot of beginners Fall foul of Recal the IFloop from the CConcitions and Loops section, where the colon means everything indented folowing the statementisto be executed as long asit’s true? Missing the indent, or having too much of indent, wllcome back with an error. Planning makes for good code. Whilst alittle ld school it'sa good habit to plan what your code wl do before siting down to type tout List the variables that wil be used ‘and the modules too; then write outa script For any user interaction ‘oroutputs. fea Purely out of interes, the word debugging in ‘computing terms comes from Admiral Grace Hoppe, ‘who back inthe “4s was working on a monolithic Harvard Mark ‘electromechanical computer. According to legend Hopper founda math stuck na relay, thus stopping the system from working, Removalof the math was hence called debugging, Python Graphics While dealing with text on the screen, either as a game or in a program, is great, there will come a time when a bit of graphical representation wouldn't go amiss. Python 3 has numerous ways in which to include graphics and they're surprisingly powerful too. GOING GRAPHICAL You can éraw simple graphics ines, squeesandso on or you can use ne ofthe many Python modules available to bring out some spectacular effets, BITE) Oc ofthe best raphicalmodulesto begintesming BAIN The command turtecrce(0) is what drawsthe cle Python graphics Turtle. The Turtle moles asthe nthe eren, with 50 being the size. You an pay name suggests, based on the turtlerebots used in many schools, that around with the sizes iFyou lice, oing upto 100,150 and beyond; you can be programmed to draw something on alarge piece of paperon can drawanaarc by entering: rurtle circle (50, 160), where the the floor. The Turtle module canbe imported with: import turtle. size s $0, butyou'e telling Python to only draw 180° oF the circle. BREET tbe by drawing a simple circle StartaNewFle, MAVAUNI the ast part ofthe cce code telis Python to keep the then enter the following code: window where the drawing is taking place to remain import turtle ‘open, sothe user can click to closet: Now, e's make a square: turtle.circie(50) inport turtle turtle. getscreen ()._root-mainloop() print (“Drawing al square.) ‘As usual press F5to save the code and executeit.Anewwindowwill for t in eange(4): ‘pow open up and the ‘Turte' wil drawa ce turtle. forward(100) turtle. left (90) turtle. getscreen ()._rost-mainlosp() ‘You ansee that we've inserted a loop to draw the sides ofthe square. PRPSTEIE Youcan add anew ine to the square code toade some colour: turtle.color ("Red") ‘Then you can even change the character to an actual turtle by entering turtle. shape (Mturt le”) ‘You canalso use the command tix ie.begin_fil(),and turtles ‘ena 11 () toil the square withthe chosen colours red outline, yellow iin this case. You can see that the Turtle module can draw out some. pretty good shapes and become little more complex asyoubegin to master the way t works Enter this exemple: from turtle inport * color (*red', *yellow") begin 112() while True Forward(200) Left (170) Lf abs(pos()) <1 break ena. () one () Isa different method, but very effective, “Another way in which youcan display graphics is by using the Pygame module. There are numerous ways inwhich pygame can help you output graphics to the screen but for now let's look at displaying a predefined image. Start by opening a browser and finding an image, then save eto the Folder where you save your Python code. Python Graphics a Eee ES ces sehe cade by mooring te Poame import pygane ygoste ini sing ~ pygeme.image..oad(*RPL. png”) white = (255, 255, 255) w= 900 b= 450 screen = pygane.display. set_node((m, )) screen-fill{ (white) screen-fill | (white) } screen.blit (img, (0,0)) pygane.display.tiip() while True: for event in pygane.event .get () pygane.QUIT: Af event.type ygane. quit () Ee i Farm Bn pore widow (25s, 255, 255) eunnconstey) lit ing; (0.0)9 Sisplay hip) erga. event. get ELSE ie mevoes sep youlmoores rca ited the pygame engine and askedit to import our saved Raspberty Plogoimage, saved as RPipng. Next you defined the background colour of the window to display the image and the ‘window size as per the actual image dimensions Finally you have a loop to close the window, {eee pe ain se tec») Ea Press 5 to save and execute the code and your image willbe displayed in a new window. Have a play around ‘with the colours sizes and s0.0n and take time to look up the many Functions within the Pygame module too. 8 Python on the Pi Glossary of Terms Aiea eae Aa Tenement hee Ue Oa ru Ty for your own sanity, is a handy glossary to help you keep on top of what's being said when Pike eee uck Channel cman} Argument The detale xa information used by Python to perform more Cetaed commands. Cn also be usedn he commend promt to ‘specify a certain runtime event. Block Used to describe a section or sections of code that are ‘grouped together Break ‘Acommand that can be used to exit a fr or while loop. For example, if akey is pressed to quit the program, Break wil ext the loop, Class ‘A dlass provides @ means of bunding data and functionality together. They ae used to encapsulate variables and function into a single ety Comments ‘comment is a section of al wodd wording nseted by the programmer to help document what's going on in the code. They ‘can be single line or multtine and are defined by a# or” Debian ‘A Linuxbased distro or distribution that forms the Debian Project. This environment offers the user a friendly and stable GUI to Interact with along with Terminal commands and other forms of system level administration. Def Used to define a function or method in Python. Dictionaries A dictionary in Pythons a data structure that consists of key and velue pairs. Distro ‘Also Distbution an operating system that uses the Linux Kernel sits core but offers something cifferentinits presentation o the enduse. Editor ‘An individual program, or apart of the graphical version of Python, that enables the user fo enter code ready for execution Exceptions Used as a means of breaking from the normal flow of acode blockin order to handle ny potential erors or exceptional conditions within the program, Expression Essential Python code tha produces value of someting Float ‘An immutable floating point number used in Python Function Used in Python to define a sequence of statements that can be called or referenced at any time by the programmer. GitHub ‘A web-based version control and collaboration portal designed for ‘software developers to better manage source code, Global Variable ‘A variable that is useable anywhere inthe program. Graphics The use of visual iteration wih a rogram gemeor operating ‘te. Designed io ake tear forthe oer fo ranape the progam in question GUI Graphical User Interface. The interface which most modern ‘operating systems use to enable the user to interact withthe core programming ofthe system. A friendly, easy to use graphical desktop envionment High-Level Language [Aprorarming language thas destned tobe eas for peopetoread IDLE Stands for Integrated Development Envonmentor Integrate Development and Learning Envronment Immutable ‘Something that cannot be changed ater its created Import Used in Python to include modules together wth ll the sccompanying code, functions and arabes they contain. Indentation Python uses indentation to delimit blocks of code. The indents are four spaces apart, and are often created automatically after a colon is used in the code, Integer ‘A number data type that must be a whole number and not ‘decimal. Interactive Shell ‘The Python Shell, which is displayed whenever you launch the ‘graphical version of Python Kernel ‘The core of an operating system, which handles data processing, ‘memory allocation, input and output, and processes information ‘between the hardware and programs Linux ‘An open source operating system that’s modelled on UNIX Developed in 1991 by Finnish student Linus Torvalds Lists ‘A ython data type that contains collections of values, which can bbe of any ype and can readily be modified Local Variable ‘A variable that's defined inside e function and is only useable inside that function. Loop ‘piece of code that repeats itself until a certain condition is met. Loops can encase the entire code or ust sections of it Module ‘A Python file that contains various functions that can be used ‘within another program to further extend the effectiveness of the code, Operating System ‘A005. The roar that’s faded into the computer after the iil boot sequence has completed, The OS manages all the ‘ther progam gapheal ver nterface (GUD input nd output ad phyeical hardware erections wih the user. Output Data thats sent rom the program toa screen, printer or other external peripheral PIP Pip Installs Packages. A package management system used to install and manage modules and other software written in Python. Print ‘Afuction ved displ the ouput of something tthe sen, Prompt The element of Python, or the Command Lin, whee the user centers the commands. n Python is represented as >>> inthe interactive shel, Pygame {Python mule thats designed fr wring games, Rincides ‘raph and sound Wares and was ft developed in Sciober 2000 Python ‘An awesome programming lnguoge that’ cosy to learn and use, lt till being powerful enought enjoy. Random ‘APython module that implements a pseudorandom character ‘generator using the Mersenne Twister PNG. Range ‘function tht used toretum alist of integers, defied by the arguments passed trough. Root ‘The bottom level user account used by the system itself. Root is the overall system administrator and can go anywhere, and do anything, on the eyster, Sets Sets are a collection of unordered but unique data types. Strings ‘Strings can store characters that can be modified. The contents of a string ae alphenumerical and canbe enclosed by ether single ‘or double quote marks. Terminal ‘Also Console or Shel The command line interface tothe ‘operating system, namely Linux, but aso availabe in mac0S. From there you can execute code and navigate the filesystem Tkinter ‘Ayton module designed to interact with the graphical ‘environment, specifically the th-GUI (Toot Kit Graphical User Interface). Try ‘Atty block allows exceptions tobe raised, so any errors can be ‘caught and handled according to the programmer’ instructions. Tuples ‘An immutable Python data type that contains an ordered set of ‘ether eters or umber. UNIX ‘A multitasking, multiuser operating system designed in the 70s atthe Bel Labs Research Centre, Written in Gand assembly language Variables ‘A data iter that has been assigned a storage location in the ‘computer's memory. x ‘Also X11 or X-windows. The graphical desktop used in Linux: based systems, combining visual enhancements and tools to manage the cote operating system. Zen of Python ‘When you enter: inport this imo the IDLE, the Zen of Python is displayed Glossary of Terms a Want to master your iPhone? Then don't miss our NEW iPhone & iOS magazine on sale now! IPNONEWsER Is This The @E "| aT an Td Le t4 Okra Sieecad ec ee Sak te 1 A teen js Have ec e Spey Ces] Pi Projects: Ideas and Code The Raspberry Pi is all about projects. For instance we've seen the Pi attached to a satellite, taking high-resolution images of the Earth while in orbit. Scientists have also used a Pi to monitor habitats in some of the most extreme places on the planet and enthusiasts the world over have used a Raspberry Pi as the driving force of their unique projects. : Ideas and Code Creating a Loading Screen pret nOeCCE MN Omura er ueneds Makers cael er eee Mee ering ek am ees ee main part of your code. me) Pe ers ees eer often used to display the Cereus ee oa image would load itselF in, usually one-tine-at Seige ea ee) raster barsdanced pee eee eee Loading screens were apart oF Coe eeu a Cee eae er ee Featured animations, or a countdown for time remaining as the ‘game loads, wile others even went so far as to include some eae era tid ee ea eke ccna ccs Cen eeaeestee While these days loading screens may no longer be with us, in terms of modern gaming we can stillinciude them in our own eens ete eee ec Coes lea aNcy Creating a loading screen in Python is remarkably easy. Youhave Pee ee eee care clisplay an image, followed by a bref pause, before starting your main code, or you could opt for aconsole-based ASCI art version that loads one-ine-atatime, Lets look atthe latter and see how oe First you'll need some ASCII art, you can look up plenty of ee a ty transform any images you have to ASCI. When you have your ASCII eee eee eee es Se etna Peay THE CODE Launch Python and enter the Following cade toa New Fil: “The code is quite simple:import the OS and Time modules and then create aPython Function called loading_ screen with a (zeconds) Ce eae eo Cees Pere ee eters pert eee eee ag ‘element willstrp the newline from the text document, without t Se eae Leen et tic See ois peti peeree eka rena anit meee Pi and macOs) and all the Function, together with the output numberof seconds to wait foreach lin tobe written to the Pane ert) Save the code as screens py, drop into a Command Prompt or Peres cere eee Celhs Cee eee ae EL) Pome ed el eee Ty Ne ene some characters, and a percentage ofthe program loaded. While Rie ee eo ea beinteresting. Create a New Filein Python and enter the following code: coca import time eee) pose enter Ceo rst) oes Crest) peeanca Peery Seer rer ae at es Ce ee ee eet eo) Eenacal eee Cree ee oe coca ‘ Preece - Perens Pee er ee? “The code works inmuch the same way asthe previous except, Cee et od See ec eee percentage counter; clearing the screen every second and displaying SO a SS De eet cra) coord Peet reso COMBINING THE TWO Teena ee eer ee begin witha Loading... progress bar, followed by the loading screen. After that, you can include your own code and continue Sent een eet ae) ESCaca Peet el ets eee eres erst es Petonca eee fora) cee nds) Poet eueerT ets eens eC deo) ere onr ead Perera] eee eens ena towhere the text Fa | Say ~ 4 See eee areeainte the ISS with Python ota rau Weal un eR Uae ele Semcon WLM CU LOT pS) 1e ‘Station tops the bill. This incredible collaboration between nations sees vital experiments carried Vee oleae keel ge TOBOLDLY GO... _ Iideed, the §Sis something most of us consider asa worthy F See aCe 5 ‘among other agendes, uses a wealth of Python code onboard the eS Reese ener cs in-between lnk to translate code from onelanguage eee ory as CE eect) ee eel ues oer Cee Peete regarding the code potest nts poet iy Pree tg Rees display the number Poeun es ceed ees ery Five seconds, while ered latitude and longitude, : eee gi eee) oer een . re ey 4 es ae ae as sceerisatertdocimentwindsw | Secret Pct epee eo a een eS Cee ae eee ey peer err te eaerretneeren ama A rieha selerans ANDY 7D ee eet ae aa pater ssc erred Peay Tracking the ISS with Python Bil aC yale) ere hy) aed ISS, touse asan icon that willbe updated aecording tothe postion Pa reereene enter rt Cee \Worid Map willhelp you outhere.Lookforone that's reasonably large the one we used forthis example Was 1280700, and one that has the names ofthe counties you're using ths with young oe Ree ee eee Tepresentation ofthe location ofthe ISS, we need the image to Eee eet ee ead ‘map, butalso prominent enough to see when the map is loaded. Are Suen eree rhe eee re ead Pert eee ee ea erent) eS eee ee eee THE CODE Se ee eet eet eer (Application Programming Interface) to retrieve realtime data per eer eae ees Dee re eres programmer can pullout and interact within their own code. In Pe cetera ert ety that's stored ina JSON (JavaScript Object Notation) format —an accessible and easy to use datainterchange interface. et ‘Aswe're going tobe using Turtle, a component oftkinter, the ‘downloaded images willneed tobe convertedto GI, since thisis the ‘default and recomended image format. You caneasily look up a Cera ee a eee ‘works On bot the Raspberry Pianté3 Windows PC, wil suffice. Simply loadthe image upinyour image ecitor app and choose Save As, call, Mie mapandiss respectively, and cick GiF asthe image format. Cn eee el ce Sete Cae aces Feet eee neat St eo Rea teers latitude and longitude based on their IP reer) pe ane ces eee nee sane eee es cree ee eee td Peer entree ey Perens ee ee pence ent cnet port eens)

You might also like