You are on page 1of 197
rc OO heen a Gun ed THE COMPLETE Coding MANUAL Master coding and unlock your rons potential Discover more of our complete manuals on Readly today... The Complete Ubuntu Manual The Complete Building Your Own PC The Complete Cloud Computing mn Manual Manual Tonge otoshop, Elements Manual ss Meyer ae LW) i Canon Galaxy Niko , Manual a '@ BDM’s Manual Series THE COMPLETE Coqins Everything you need to start learning how to code... Code exists everywhere you look. From your smartphone to your smart TV, from your fridge freezer to your washing machine and from your car to road traffic signs, everything you interact with in this modern after) world has been coded at some level by people who, like you MANS actict perhaps, started by learning the basics. However, the coding world can be an incredibly confusing Nbsrapuabatualy place to start exploring. Which programming language do (IES a ric Oc fsa 0 you learn? Which version of the language to start learning? ‘What do you need to enter code? How does it work? Where do you start? It’s little wonder many people give up before they even begin entering their First lines of code. pened The Complete Coding Manual aims to help by guiding you through the ‘quagmire of technical lingo, version numbers, tools and platforms. We will help you discover how to start coding, what to use, how to structure your coding ‘and how to become a programmer. Initially, learning to code is challenging, but we're here to help you get going. In the pages of this book, you will discover how to get through those first steps in the world of coding. There are tutorials, ‘on the basic Foundations of Python, C+, Linux scripting and even using FUZE BASIC on the Raspberry ‘Once you've leamed the basics there's an entire universe of creativity and project ideas to discover, the only limit is your knowledge so let's get you coding. en ee index Choosing a Programming Language 10 _Learning to Code - Study Tips 42 Coding Tools and Resources Being a Programmer Inthis eee re ed Rat fetter those first peers peed coat Cree} hy Python? Equipment You Will Need 22. Getting to Know Python 24 How to Set Up Python in Windows 26 How to Set Up Python on a Mac 28 How to Set Up Python in Linux e 36 8 0 gears 2 ‘Your First Code Saving and Executing Your Code Executing Code from the Command Line ‘Numbers and Expressions Using Comments Working with Variables User Input Creating Functions Conditions and Loops Python Modules Python Errors Combining What You Know So Fa 60 Lists 62 Tuples 64 Dictionaries {66 Splitting and Joining Starting Python for the Fist Time n 7A Writing to Files 7% Exceptions Opening Files 78 Python Graphics 80 Combining What You Know So Far Calendar Module 05 Module Random Module ‘Tkinter Module Pygame Module Create Your Own Modules LO eeerieceee) 1144 For Loop Cee es 146 Do... While Loop ‘ug if Statement 150 If. Else Statement 8/8/s/e|s|2 98 )Say Hello to C++ Why Cr+? 102 Equipment You Will Need 104 How to Set Up C+ in Windows 106 How to Set Up C++ on a Mac fi 108 How to Set Up C+ in Linux ‘10 Other C++ IDES to install reer CST Peenats red with FUZE BASIC 1160 Coding with FUZE BASIC - Part 1 162. Coding with FUZE BASIC - Part 2 164 Coding with FUZE BASIC - Part 3 166 Using a Robot Arm with FUZE BASIC 168 FUZE BASIC Examples - Part 1 FUZE BASIC Examples - Part 2 Ur aee ae ey Your Fist Ce Program 122 Variables Structure ofa C+ 124 Data Types Program 126 Strings Compile and Execute 49 C+ Maths Using Comments Gee us environment for eee) A eotsT Reectcctey Grover Porras eel ‘74 Getting Ready to Code in Linux 176 Creating Bash Scripts - Part ‘78 Creating Bash Scripts Part 2 180 Creating Bash Scripts - Part 3 182. Creating Bash Scripts - Part 4 186 Creating Bash Scripts - Parts 186 Common Coding Mistakes 188 Python Beginner's Mistakes 190 C+ Beginner's Mistakes Feciiere Net sierne 132 User Interaction 136 Defining Constants 734 Character Literals 138 File Input/Output. eiey ec Retieenatcn Serpette Coding and Programming Learning to Code - Study Tips Programming is one of the most valuable skills you can pick up these days, particularly la Ree ke ee hehe ea cole ee Roll meee (ee ho keg tle} something cool too. When you're new to coding, it can be hard to know where to start and it's easy to get sucked down paths that could waste a whole lot of your time and money. If you're just getting started on your coding journey, here are some tips to set you offin the right direction. erm nacs Teneo sa) may sound obvious but $ _ ¥ Take some time to look atthe things coding languages are sed for; so iF you choosing the 3 areinterested in web design, look how Javascript is being used onthe sites right coding or : you use every day; if you are in to mobile apps, look into Java or Swift and see programminglanguageto 3 _E how they make apps work. lt can also be useful and encouraging to check cut Stat eaming important £ what qualified coders can expect to get paid by looking at lcal job ites. We iFyouwant the creative } _E arenot saying that if you learn to code Python you are mediately going to processto be successful F ‘youneed lean to code Fora specificreaton, Finding ajob for example, then you abviously heed to learn the language that’s relevant IF ‘yousimply wantto learn coding, then picking alanguage ike Python, that isboth powerful and relatively easy toleam, can make success more likely, be offered a £70,000 ayear job butitcan help spur you onto study harder PUT THEORY INTO PRACTICE IF you are completely new to coding, learning any programming language can seem ikea huge task Getting completely bogged ‘down n pages and pages of code examples and explanations isnotlikelyto make the learning process much Fun, In our ‘experience itis often betterto learn through practice orto choose a task you want to perform with code, and then work backwardsto learn how to complete that task. By learning small chunks and repeating what you have already earned at differing intervals is called Spaced Repetition. (_ Learning to Code study Tes QS STUDY IN DIFFERENT WAYS Sometimes, though admittedly not always it'sa good idea to get a more rounded view oF computer science befare you cig down into more Say Hello to Python Why Python? See areas er uM eae ter ee see aku Bo Pee een eeu Reece eso Crd d at tt are designed For scientific work, others For mobile platforms and such. So why choose Praeartiase nics) PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have tolled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. ‘These pioneers of programming carved thelr way into 3 new Frontier, forging small routines that enabled the letter to scroll ‘acrossthe screen. may not sound terribly exciting to a generation that's used to ultrahigh definition graphics and open werld, muiti- player online gaming. However, ortysomething years ago it was binginaly brian. Naturally these bedroom coders helped form the Foundations For ‘every piece of digital technology we use today. Some went onto become chief developers for top software companies, whereas others pushed the avaiable hardware tits limits and founded the billon pound gaming empire that continually amazes us. Co Na Dont Ba be tet oe Regardless of whether you use an Android device, iOS device, PC, "Mac, Linux, Smart TY, ames console, MP3 player, GPS devce builtin toa car, settop box or athousand other connected and ‘smart appliances, behind them allis programming, ‘Allthose aforementioned digtal devices need instructions to tell, them what todo, and allow them tobe interacted with These instructions Form the programming core ofthe device and that core can be butt using a variety of programming languages. The languagesin use today difer depending onthe situation, the platform, the device's use and how the device wilinteract with its LO ox vi vecntoev @| S| SSC >TO certsccmitasoteocunt stieurger »= 0) Pefresipoutcursor): certTuchataoreracen i j iin Hi poi arog scitontronue) weld, acrayeerL-paine(oras ¥) { eee enn i mea Se! colum.cetcomt) « 9) >= 0) ins j.< colum,cotcnmt()s io) { ‘regen Getrabwa deh) ir environment or users. Operating systems, suchas Windows, macOS ‘andsuch are usually a combination of C++, Cl, assembly and some Form of visuabased language. Games generally use C++ whist web pages can use a plethora of avaliable languages such as HTML, Java, Python and soon, More general purpose pragrammingls used to create programs, apps, software or whatever ese you want to call them. Theyre widely used across all hardware platforms and suit virtually every conceivable application. Some operate faster than others and some ‘are easier to lear and use than others. Pythonis one such general purpose language. Python is whats known as @ High-Level Language, in that it ‘talks to the hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, laps and countless more interactions. Whilst it's notas streamlined as a Low-Level Language, which can deal directly wth memory addresses, call stacks and registers, its benefit is that it's universally accessible ‘and easy to lea, TFT: r Tnvele. java, finport Tanig.reflect.*; Jelass_tnvoke { public static void min string () args ) { "kes = class.forname( args(0) tthog‘g =Scrgeethodt atid, now class ject Pet = m-inyoke( mu11, 11 25 SySten.out printint Tnvoked stattg method: * + args(i leu ees ee F Cruel ee argslometites: © ¢ ree 9: card Sasstoctnabeepejen 3 I ehake Herntaee Scans Fond the clase UcchChesutinetnodeCeeption e2 5° ¢ IT chat Method soeen't crise Great" ilepnseenstecertion 32, 3 een : 6) Gatch ( mocactowtargweaiceotion » H'sn Sccapeion seurrea eae tovokng that fecha eee ® i yee thod chron an: 7 +f. gecrargetExcepetonc “)°3; avaisa powerful language that’s used in web pages, set-top boxes, ‘Tvsandeven cars. wubampubiatonscam ¢ Why Python? em” Python was created over twenty si years ago and has evolved to became an ideal besinnerslanguage for earning how to program a computer's perfect forthe hobbyist, enthusiast, student, teacher and those who simply ned ta create thelr own uniqueinteraction between either themselves ora piece of externa hardware and the computer sel. Python isFree to downoad, stall and use ands avalable for Linux, Windows, macOS, MS-DOS, 05/2, OS, IBM series machines, and even RISC OS. thas been vated one ofthe top five programming languages in the world ands continually evolving ahead ofthe hardware and Internet development curve So to answer the question: why pthor? Simply put i's Free, easy to learn, exceptionally powerful, universaly accepted, effective and 2 superb learning and educational tool BASIC was once the starter language that early ‘sbithome computer users learned. Python sa more modem take on BASIC, i's easy to learn ‘and makes For an ideal beginners programming language. reconstecotn ns EP Say Hello to Python ) Equipment You Will Need teem Creme nn enas Cl don't need an incredibly powerful computer and any software that's required is Lice le) WHAT WE'RE USING “Thankfully, Python is a multiplatform programming language avaiable for Windows, macOS, Linux, Raspberry Pi and more. IF you have one of those systems, then you can easily start using Python, COMPUTER Obviously youre going to need a computer inorder to learn how to program in Python and to test your code. You can use Windaws (From XP onward) on either a32 or 64-bit processor an Apple Macor Linuxinstalled PC. (_] AN IDE ‘Ani (rtegroed Developer Environment isused to enterand execute Python cove, enables youto spec your procram code andthe velues thin the code, Wells offering avonced features Mere are many diferent OES avlatle sod the one tht wort for you and ghesthe bes resus PYTHON SOFTWARE. ‘macOS and Linuxalready come with Python preinstalled as part ofthe operating system, as does the Raspberry Pi. However, you need to ensure that youre running the latest version of Python. Windows users need to download andinstll Python, which well cover shorty, |_| TEXT EDITOR ‘whilst tex editor isan ideal enronment to enter code int,’ not an absolute necessity, Youcan enter and execute code directy from the IDLE but atext eto, ‘suchas Sublime Text or Notepad, offers more advanced features and colour coding ‘when entering code, INTERNET ACCESS Python is an ever evolving environment and as such new versions often introduce new concepts or change existing commands and code structure to make amore efficient language. Having acces tothe Internet wil keep you uptovdate, help you ‘cut when you get stuck and give access to Pythor'simmense number of modules. TIME AND PATIENCE Despite what other books may lead youto believe, you won'tbecome a programmer in 24hours. Learning to code in Python takes time, and patience. You maybecome ‘stuckat times and other times the code wl lw tke water, Understand youre learning Something ently new, and you wil get these. ( Equipment You will Need THE RASPBERRY PI Why use a Raspberry Pi? The Raspberry Pi satiny computer that's very cheap to purchase but offers the user a Fantastic learning platform. I's main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras. Peas aal ‘The Raspberry Pi 2s the latest version, incorporating a mare powerful CPU, more memory, WiFiand Bluetooth support Yu can pick up aP For around €32 or asa part of kt For £50, depending onthe kityoue interested in FUZE PROJECT The FUZE'sa earning environment bul onthe latest madel ‘ofthe Raspberry Pi. You can purchase the workstations that ‘come with an electronic kt nd even 3 robot arm For you to buld and program. You can find more infermation on FUZE at wuw fuze.co.uk ‘We have several great Raspberry Pitites avaiable via www, Lbdmpublications.com, Our Pibooks cover how to buy your Ba RASPBIAN first Raspberry Pi, setituponduse ==, ee i Reet eee aetse eee Unuxdltbton hat comes wee 8 Ra * acinpleto we puclage tssveaminesortrePioncisan : | braectexmaes | Pj " : cea Brdies Det ideal platform for hardware and software projects Pytho aniaidesooet | Tricks) Hay programing and evens desktop computer, Oe scat slACKS & Fixes a : Pitoo wu bdpuiaionscom thecomplete coding manual Ql] EP Say Hello to Python ) Getting to Know Python ne Recetas rd Seno rine cme tcmieleutee anak nen ty to understand. WHAT IS PROGRAMMING? Ithelps to understand what a programming language is before you try to learn one, and Python is no different. Let's take 2 look at how Python came about and how it relates to other languages. ‘programming language isalistof instructions that ‘computer follows. These PROGRAMMING RECIPES Programsare tke recipes for computers. Fecipe to bake a cake could go like this: Put 200 gre out 100 grams ofselfasing fourin a bow ‘Add 100 grams of butter tothe bowl, legac aE) ‘Add 100 mililitres of milk ‘or playing a music File, or eae fo el au Se... — seu averd ten isa programming language CODE coeavedn@elie seis: Aotlkesrecbeaproancoviisof stun hte flow byob svete order Apron ot abe sale hun ets een ecanea tora EW ne tort = Oh Netherlands asa successor to a ‘the ABC language. butters 38) ears FS samenecmny opEaeres Peer ar i faberal on PROGRAM COMMANDS ‘You might not understand some of the Python commands, ke bowl append and cake.cook(bow! “The Frsis alist, the second an object; welllook at both inthis book The main thing to know i that’s easy to read commands in Python. Once you learn what the commands do, it’s easy to Figure outhow a program works. HIGH-LEVEL LANGUAGES Computer languages that are easy to read are known as high evel This because they fly high above the hardware (also referred toas ‘the metal Languages tht “ly close tothe meta, lke Assembly, are known a5 “low-level. Lowevel languages commands read abit like ths: msg db ,@xa len equ $= msg PYTHON 3 VS PYTHON 2 Getting to Know Python ZEN OF PYTHON Python letsyou access all the power of acomputerina language | that humans can understand. Behind al this an ethos called “The Zen oF Python” Thisisa collection of 20 software principles that influences the design ofthe language. Princilesinclude “Beavtful is better than ugly” and “Simple s better than complex." Type ‘import: this into Python andit wil splay all the principles. ee eee eager ae ge ert Cree ies PYTHON TTS CI es Peer are etree Rares Lente PRERPREEER 5 2009 Python 3 area with several new eee ‘These features CO TGs oi ) Say Hello to Python ) How to Set Up Python in Windows Windows users can easily install the latest version of Python via the main Python PCE aN ease eee yout aC eum eaan i over es platform of choice for building their code, it's still an ideal starting point For beginners. INSTALLING PYTHON 3.X Microsoft Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. ‘Thankfully, i's an easy process to follow. Suivopengeurebbronartommorion EREREG cong he canton sowsouio Sie" ‘org/downloads/. Look For the button detailing Sa ‘specify certain parameters, and whilst you may. the donloadntor Python 2 Teltetverstontthetme ot staywththectats ts goed habit adopts omatmes ot vwiing3.0bicas thon stequenyupdatedsmaybea wih ython kfl) rae an ide unwanted ada ferent version For you. Features. On the First screen available, ensureall boxes are ticked and click the Next button, J optional Features puth wind BSPESED ick :he download button for version 3x, and ERED 1 next page of options include some interesting save the fle to your Downloads folder. When the additions to Python. Ensure the Associate file with Fleis dovnioaded, doublecckthe executable and the Pytion Python, Create Shortcuts, Add Python to Environment Variables, installation wizard wil launch, From here you have twochoices: _Precompile Standard Library and Install for AllUsers options are Install Now and Customise installation, We recamenené opting for ticked. These make using Python later much easier. Click instal when the Customise instalation link you're ready to continue, [YY tnstatt Python 3.7.0 (32-bit ‘Advanced Options == | |e wind ‘Claas Pinon 37 0 PATH one windows ook Cit eee How to Set Up Python in Windows x woconf withthe {ling onthe OLE Python 37 226k wl Sua Windows authentication notification, Simply click Sue launch the Python Shell, where you can begin Yesand Python begnto sta Once he nstalation complete the final Python wizard p notes, and fll sr Python programmingjourney, Don't worry if your version is wer 35 1ong 2s ’s Python 3x our code works inside you terials Python 3 interface. Setup was successful "= a @ puthon windows ESTEE Gefore you close the instal w however, t's best to lick on a window Ifyou now clickon the windows Start button agai nk next to the Siz) and this time type: OMD, you'll be presented with th shield detailed Deable Path Length Limit. Thiswillallow Python Command Prompt lnk, Click t ta get tothe Windows commandline ta bypass the Windows 260 character limitation, enabling you to __envifonment. To enter Pythan within the command line, you neee execute Python programsstaredin deep folders arrangements. to type: python and press Enter cick es to authenticate the proces; then you can Clo installation windo ose alia =— ~~ | BARE resin sorewoy stn sheliouoeenedin Windows 10 users can no Step 8 note the three left facing arrows (22>).Whistl’sa perfectly Findthe installed Python 4 Ep Fine environment, ts not too user friendly, so leave the command 3.c within the Star button line for naw. Enter: ex to leave and close the Command Recently Added section. on Prompt win he isin, Python 3 Po (G2-bi wil aunen che _ = command |ine version of Python when licked (mo conthat ina moment}. To nthe IDLE, type IDLE into Windows stan EP Say Hello to Python ) How to Set Up Python on a Mac TOA EME natn RTT te Ca Meera nee CM ena ete gel che cet oer ata Pace cia een) INSTALLING PYTHON ‘Apple's operating system comes with Python installed, so you don’t need to install it separately. However, Apple doesn't ‘update Python very often and you're probably running an older version. So it makes sense to check and update First. (Open anew Terminal window by licking Co Click onthe latest version of Python 3: nur UE viiiies ren doublectietheterminalicon. Now — aa case iss the downoad button or Python 3.52. wersion Youshauidsee Python 25.1" and THs wilautomatcally download the atest version af Python and evenlater if Applehasupdeted te OS and Pythoninstalton. __ depending on how you've got your Mac configured, automaticaly Either way, it's Betta check or the latest version. stats the instalation wear Bi Cpenssfandheadowronwwoyborco/ — ERREPB wintheryon rslaton was ope dk on Sieve downloads. Just as with the Windows set up Si) the Continue button to begin the installation. it's procedureonthe previous pages you canseetwo yelow download worthtaking amomentt read though the important formation buttons: one for Python 3.6.2, and the other For Python 27.13. section incase it references something that apples to your version Note that version numbersmay be different dueto the frequent of macOS. When ready click Continue again. releases of Python. (How to Set Up Python on a Mac em” PIM the next secon deta the Software License Agreement, and whist not particularly intresting ta most folks t's probably worth a read, When you'e ready, lick on the Continue button once again, BPR Fray you be oresented wth the aroun of STEELS ‘space Python will take up on your system and an inal bution whch you need to cick to tar the ata ntti oF Python 3xon toyour Mac. You may need to enter your password to authensicate the installation process. ‘command: python ==version, you can see the new version's rrowlistee, To enter the commandline version oF Python, you need toenter python3. Toext, i's exttO. ‘You need to serch in Find For the Python OLE; sue when you've Found it, click it to launch and it shouldlooksimilarto that ofthe Windows IDLE version shown on the previous page. The ony difference being the Mac detected hardware platform's running on ese Piensa aa PECL age nee tite See) Cane] oe dren Joe emi ah or ee fe rao The instalation shoulda too lng the older Sup ‘Mac Mini we used in this section is @ little slower than more modern Mac rine nd ony tok rund ary seconds for the Installation Successful prompt to be displayed. (Older Mac versions mayhave trouble withthe Suit ‘newer versions of Python, in which case you will need to revert to aprevousPthon 3xbul slong as youre ng Python 2x, the code inthis book wl work For you Python 3-1-2 (4312:79360K, Mar 24 2010, 0133118) [eee 4.0:1"{appie ine. build 5¢93)] on’ darwin Sopyrignt’, ‘eredite’ of ‘Ligense(}” for mo EvVineorestisas Shi a diy) Say Hello to Python How to Set Up Python in Linux PYTHON PENGUIN Linuxis such a versatile operating system that it's often difficult to nail down just one way of doing something. Different distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial. Fiat you need toascertein which version of Pytha me Lnuxdstroswil automaticaly undate UD current rstaledinyour Linuxsystem; ase Rada erenstaliton of Python to the latest versions mentioned, we're gong ta be using Linx Mint 1.1 Forthis section. whenever the systems updated. ached ‘As wth macOs, drop into a Terminal pressing CUT and upgrade with Fist doa system update 5 sudo apt-get update && sudo opt-get upgrade “nade david mint sesame ay ur password and let the system do any updates. hese ytton=versionino eer EERE Orch se anda 0 Sieve ‘screen. You should have the output relating to Su may need to answer 'Y' to authorise any upgrades, version 2xofythoninthedlplay Ourveson ssyoucan see enter python3)=-werston to seeiFFython xs upeated or even below, is Python 2.712. installed. nthe case of Linux Mint, the version 3.5.2, which fine for our purposes ave Python davidedavid-mint Fle Edt View Search Terminal Help How to Set Up Python in Linux eg However ifyou want the latest stable version, you BED Within the Python folder, enter: BLEED i coed 0 c Python from source Start by oud mcomnseeet entering these commands into the Termin Tanne sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev Libncursesn5-dev libssl-dev Libsqlite3-dev tk-dev Libadom-dev Libc6-dev Libbz2-dev This coulda litle while depending onthe speed of your compute Once finished, enter python3.6 ==Version to check the installed atest version, ‘Open up your Linux web browser and goto For the GUIIDLE. youneed to enter the Following BLEED the ino dovrioad peg: wwnpthon ora ED rinand ini the Terminal downloads. lide on the Download Python 3.62 (or whichever version i's on when you look to download the source Python STIR 362.02 ‘he IDLE can then be started with the command: LdLe3. Note that IDLE uns a diferent version fom the one you installed from source. @ python Download thet ee Inthe Terminal gothe Downloads ode by BEG cess ee raterese anise suey ‘entering: €d Downlloads/, Then unzip the Su tool to help you install more modules and extras. contents ofthe downloaded Python sourcecode wth EOF I=KVE) Eater: sudavapt-get install pythond-pip Python-3.6.2.-tar.x2. Now enter the newly unvipped Felder berg 4 PIPis then installed; check forthe latest ups with pip3 install --upgrade pip hen complete, close the Terminal and Python 3:cwillbe available via the Programming section inyour dstro's men vewcmgubeatons com ‘The Complete Cong Manual Getting Started with Python RS Saco of Python installed, you can begin to et Eg Bekman and we're here to help you write your first piece of code, save it and run it in ees a Ree eee) expressions, conditions and loops, user input and the types of errors you undoubtedly come across in your time with Python. Let's start and discover Pred sees ye} 36 Saving and Executing Your Code 38 Executing Code from the Command Line Numbers and Expressions Pe Teomucns? Working with Variables eas eae get SeRERS or enea EM ed eared ining What You Ki ) Getting Started with Python Starting Python For the First Time een och er cuiaeitaoaictars platform. The latest version of Raspbian comes preinstalled with Python 3; so as long as BYTE EW ee REBEL cole ROLLS STARTING PYTHON We won't go into the details of getting the Raspberry Pi up and running, there's plenty of material already available on that subject. However once you're ready, Fire up your Pi and get ready For coding winter deen sedcionte EERE rorcanl.nte sete 2 SUED icc sutonfolowec by Srogrmining> Python 3 ene wi slay the ALE Tis openthe Python 3She Windows and MECUSers <2) aver g pac seem terthe nent neil spay he find the Python 3 IDLE Shell From within the Windows Start button we sally Byron nes ns proces ‘menu and vi Finder Felevant output Tesielawteesoucnenscotandaeine EAA Teyonsnalacsveymentien cet Sieve ‘responses and output of code you've programmed Sus since code is basically a series of mathematical intaPython Thisisakindof sandbox whereyovreabletotyauk interactions with thesystem.eeges, wich are the vite some simple code and processes. sequence of whole numbers can easiy be added, subtracted, ‘multilied and soon, Starting Python for the First Time Gal PIR wile that's very interesting, is not particularly ‘exciting, Instead try this print¢“Hetlo everyone!”) ‘sper the code we entered in Sublime in the Insaling Test Editor section ofthis book, Fe i yoniisbo cine cnenner clicking on the Highlighting tab, However, we dorit recommend that as youwon'be seeing the same as our screenshots This alle mre since youve st arodvced sere your first bit oF code. The Print command is Fairly seleplanatoitrints things Python 3 requires the badktsas wel as quote marlsin order to output conten tothe screen its case the Hello everyone it p>> print("Hello everyon a everyone! dust the mst programs valle, rears of the STEP 9 ‘operating system, there are numerous shortcut keysavalale. We dort have rors for them al here but withthe Options > Configure IDLE and under the Keys tab, you can see alist of the current bindings. ‘You mayhave noticed the colour coding within Sup the Python IDLE. The colours represent differen elements of Python code. They are: Black Data and Variables Green-Strings Purple Functions Orange — Commands ‘lue—User Functions Dark Red Comments ght Red—Error Messages IDLE Colour Coding [_-eotour [seer] exams | ‘The Python IDLE isa power interface, nd one Suit ‘that’s actually been written in Python using one of he avalable CU tole you wat to know the many isan ctor the Sel we recommend you ae few moments oview vr. docs python org//iraryfdle Nm, which detalls many ofthe IDLE Features ‘The Complete Cong Manual Your First Code Sen Ma mde en Gn Cena emirate tel tr ead eon ene eal cles Se ne eu CMe eet ete omctoea cubes PLAYING WITH PYTHON ‘With most languages, computer or human, it’s all about remembering and applying the right words to the right situation, ‘You're not born knowing these words, so you need to learn them. ifyouive dosed Pthon 3I01E,reapenitin Youcanseethatisteadof the umber the Sue whichever operating system version you prefer. In EE ‘output is the 2+2 you asked to be printed to the the Shel enter the Farr flowing screen The quotation atk ar defhing whats beng outputted tothe DLE Shell to print the tatal of 2+2 you need to remove the quotes: primtc*Hetto”) print (212) Justas predicted the word Helo pears in BRED recreates Siere the Shell as blve text, indicating output from a Suz ‘and so on to the Shell, An easier way isto use a String It’s Fart straightforward and doesrferequire too much vatiable, whichis something we will cover in mere depth later. For ‘explanation, Now try: row, enter primtce2i2") me (Your First Code Gal canter ah ect carere SEP and b two values: 2 and 2. These are now variables, SHEE _and so on for as tong as their numbers stay the same, Try this: . You now have two variables containing Firstname and a surname and you can print them independently, Teouncolvelstsencoastvecsrert | EERAAB \wewcretozpohesanerosine2s before, SMePe values of both a and b individually, as you've asked uae) using the + symbol, the name wouldn't appear them tobe printed separately. Fyeu anttoadathem up.youcan_correlyintheutput in the Shel. Ty use the allowing primtCnanessurnane) a You need aspace between the two, defining them as two separate This code simply takesthe values of aand b,addsthem together values and not something you mathematically play around with. and outputs the resut. Youcnpayarondwandsteetincrervitie EMRE ton oucansepte the over Suary and the Print Function. For example, you could Suerdo with a space using a comma: ‘ssh varables for sommes are : = print(nane, surname) — ‘Alternatively, you an ad the space ourselves: print(nane+” “+surname) ‘The use ofthe comma is much neater, a you can see. Congratulations, you've ust taken your firststeps into the wide world of Python, santa reconstecote ns ) Getting Started Python) Saving and Executing Your Code While working in the IDLE Shell is perfectly Fine for small code snippets, it's not Coser ema cune nan ecu ea ales un ely introduced to the IDLE Editor, where you will be working from now on EDITING CODE ‘You will eventually reach a point where you have to move on From inputting single lines of code into the Shell. Instead, the IDLE Eelitor will allow you to save and execute your Python code, Fist open the Python DLE Shel and when kup, You canseethat these colour coding sin place ua lick on File > New File, This will open a new window ue inthe IDLE Editor as its in the Shell, enabling you withUntidedasits nme. Tisisthe Python IDLE Eto endithink._tobete understand hats ong on wth your cde However yuan enter the code neededto create yourfuture programs. execute the code you need to First save it, Press FS andyou get @ Save..Check box open. Te DiEestorsforatimensandounsse.2 RTE clckonteOxtutorin Sve boxand select Sieve ‘simple text editor with Python features, colour Si) destination where you'll save all your Python code. coding and so on; much nthe same vein as Sublime, You enter The destination can bea dedicated Folder called Python or you code 35 you would within the Shel sotaking an example fromthe _canjust dump it wherever you lke, Remember to keep atidy drive previous tutorial enter though, tohelp you autin the future. print¢*Hetlo everyone!" ese pa Saving and Executing Your Code Gal Enter name or your cade, hele'for SIE ‘example, and click on the Save button. Once the Ayton code s save rs exected andthe output wile cetedin the DLEShel nts cae, the words Hello eveyone Tnsthorbevsmay cor gion ct you open he fie lcatoncf te saved Python Siery code, you can see that it ends in a py extension, ‘hts the default Pithonfe name Any code you ees willbe \whatevepy andy code dounlosdd rom the mary erat Fon ecorce tes willbe py list ence tha te codes wrkten foxPython wnbampubtiationscom Letsextend the code ad enter a few examales from the previous tutorial: uz bez nane="David” surnanes"Hayward” rint(nane, surname) print Carb) Ifyou ress F now you'll be asked to save the file, again ast’ been ‘macified From before Ee Ifyou dick the OK button, the le willbe ‘overwritten with the new code enties, and executed, with the outout inthe Shel I's nota problem with just these few tines but if you were to edt larger file, overwriting can become an issue. Instead, use File> Save As rom within the Editor tocreatea backup. Now create anew fle Cos the Er, nd open Suit ‘anew instance (File > New File From the Shell), Enter the following and saveit as hello.py: ‘a-"Python” boris” "cool!" print(a, bye) You wil use this cade in the next tutorial. “Me Compt Cong Manual Getting Started with Python Executing Code from the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py let's see how you can run code that was made inthe GUI at the command line level your operating system, Saeed he Sta 0-2 search For CMO, then click printcay Commang Line returned You can see thatit works exactly the same and macO users can get a to ther command ine by clicking "Now enter: ext to eave the command i SED oo. and cetumnyoubock tothe comm: Bromo. Enter the folder where you saed the code From previous tutorial and list the avalable files within; hopeFuly you Should see the helopy le thon hin te same Folder asthe cod ng to run, enter the Following nto the python3 hello.py his will execute the cod hich to remindyou is "Python? boris” cool!" printca, b, ©) Executing Code from the Command Line Python coe om the The est of run 3 code ro SHED Python 2 command line is quite obvious. Whilst it stin any way, cue to the differences between the way Python 3 handles the Print command over Python 2, the result isnt as we expected. Using Sublime for the moment, open the helo py fe. Since Subline Text st avalable forthe Raspbery BALE yore rato temporary lave the Pforthe Imomentonduse Simeas cn exardethat you der ecossoy ‘eed to use the Python IDLE. With the hello gy Fle apen, alter itto Indude the Following name=input(hat is your name? “) printC*Hello,”, name) tual sncethss Python 3 code, uingthe Siu ‘syntax and layout that’s unique to Python 3, it only. works when you ue the python3 command. f you tke, ry the same with Python 2 by entering python hetlo:py Savethe hlly fie ond drop back to the Sue ‘command line, Now execute the newly saved code wth python3 hello. py The result wll be the cxginal Python is cool statement, together with te added input command asking you for your name, and ‘splaying it in the command window =D Getting Started wi Python) Numbers and Expressions Ween ecient crue emer ru Mra eas tea ei Meee Leet cohol TROL Sno Lala oman ae RN Cea NR ol LC IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, Maths is the driving Force behind the code. ‘pen upthe Gversion of Python 3,5 mentioned You canuse athe usa Mathematical operations Sue ‘you can use either the Shell or the Editor. For the EE divide, multiply, brackets and so an. Practise with a time being, you're going to use the Shelljusttowarm our Maths few, for example: muscle which we believe isa small gland located atthe backof the yp brain (or not. 2 26283 as2ysc3r4) ce? BED ore rcciscrseaces = cna rber myentce oas crfeningponk ote Hone Poured nests SSSSEMBSIZAS opposed toa decimal answer, then you can use a double slash: Segeret oaeuasizt eiensenrphnantindesonegitelryennien Mil Ften ED ses tamat series volume 17 (Numbers and Expressions Gal You can also use an operation to see the remainder leftover from division For example: 19/3 Wil display 3333333333, whichis ofcourse 33 recurring. Fyou now enter: 103 ‘This wil splay 1, whichis the remainder leftover fram dhiding rointo3. ‘Tis willbe deplayed as OI converting the SHEE integer into binary and adding the prefix Ob to the Front. Fyou want to remove the Ob prefix, then you can se Formats; *b?) “The Format command converts value, the number 3, oa Formatted presentation a5 controlled by the Format specication, the’ part Next up we have the power operator, oF ‘exponentiation if you want tobe techrical To work cut the power of something you cn usea double multiplication symbol or dauble-tar onthe keyboare: Essentially ts 22x2 but we're sure youalteady know the basis behind Maths operators Thisis hw you would work tout in Pthon [Numbers and expressions dont stop there. Python has numerous builtin functions to work out sets cof numbers, absolute values, complex numbers and ahost of ‘mathematical expressions and Pythagorean tongue-twisters. For example, to convert a number to binary, use: bina) wnbampubtiationscom FID 2 s0clean xpresionisa losical statement that wil tither be trv o false. We can use these to compare data an test to see F's equalto, less than or greater than. Tythis InaNew File: a=6 b=? print(Ly a= 6) print@2, a = 7) print(3, a = 6 and b = 7) print(4, a == 7 and b = 7) print(S, not a= 7 ond b == 7) print(6, a= 7 or b = 7) print(7, a= 7 or b = 6) rint(B, not (a == 7 and b == 6)) print(9, not a == 7 ond b == 6) Execute the cade from Step9, andyoucan see a sees of True or Fase statements, depending on the resut ofthe two defining values: 6 and 7. I's an extension oF what youve looked at and an important part of programming. Bea “Me Compt Cong Manual ) Getting Started Python) Using Comments Wier cece cere iceuk | Pere eae ier setae eae cecmmmeest la nated line by line but over time, it can become difficult to read. #COMMENTS! Programmers use a method of keeping their code readable by commenting on certain sections. Ifa variable is used, the programmer comments on what i's supposed to do, For example. It's just good practise. Stantby creating a newinstance ofthe DLE Editor fesave the code andevecte lt Youcan see tha the Sue (File > New File) and create a simple variable and EE ‘output in the IDLE Shell is still the same as before, print command spite the exta tinesbeing added. Simply put, the hash symbol (#) jaa >> Brine crane + Beant (rome * age) typetrror: Can't convert “int object to ste implicitly SBE rine characters Sse" + rtr(age) 2." years ola." Sel iapara Sescended fron Vakinge te i years old ola.2) These of Typecastingsakoimportant when uae) dealing with Floating point arithmetic; remember: numbers tht have adcmal pint inher For eampe, enter shirt=19.99 ‘Now enter typaCShiint) and youl se that Python has allocated the number asa float’, because the value contains a decimal pint. Soe Specantres Another example of ypeCasting when you Suary _ask For input from the user, such as @ name, for vamp ener ‘oge= input C*How old ore you?) ‘Alldta stored from the Input commandisstored as 2 string variable. oe age roa Cn wnbampubtiationscom When combining integers and lots Python Suit usually converts the integer to a float, but should the reverse ever be apps worth emebering that Python does return the eactvale, When conve'ting 2 Roattoan integer, ythan il ays rund down tothe nearest integer, Caled ncatng nour cate tendo 1.99 becomes 19, iin 548 ee. Ok ae, TTY ype create” or “case” for nae infomation. “Me Compt Cong Manual =D Getting Started Python) User Input Ween aera nC naeiecuscd eT MMU eT cdetereseM NMC a Cee en ren an cade og USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding. For example, @ game may _ask for a character's name, whereas a database can ask for personal details. iis notaleady, open the Python 310 Sel Now that we have the use’ name stored Sue and start a New File in the Editor. Let’s begin with EE ina couple of variables we can call them up Something really simple, enter: whenever we want: printc*Hetto”) printC*Welcone”, firstname, surnane, “. T hope: firstnane=inputC'What is your first mane? *) ‘you're well today.”) print¢*Thanks.") Surnate=inputC*And what is your surmane? *) Sreawercate tease acasoustessiro ETERS fun hecoce ndyoucnseasig ss the Siare doubt suspected, in the IDLE Shell the program will Suz ull stop after the surname follows a blank space. skforyorFist name storing earth varabefisiname,falloned Tosiminate that we cnades plu sign stead of the comme by your surname; also stored in its own variable (surname). in the code: printC*Melcone”, firstrane, surnames. T hope you're well today”) C User Input. Gal SIE tthe input command, For example, you can ask the usertheirname, andhave the input inthe line below: print(*Hello. Whats your nane?”) rramesinput©) You dar'talways have te include quoted text within what youve createdhere is acondtion, which we SHEE will cover soon. In short, we're using the input from theuser and measuring tag a condition So, the ser enters David astheiename, the guard wil alo them to pass ntinered Ee, they enters name other than Davi, the guard calenges themtoatiahe Lserinput py -shome/pi/Documents/Python Code/us fie Est gmat fn gptions windows Help PrINtCHelle, What's your nan hanesnput©) 7 ‘The code From the previous step is often regarded asbeinga litle neater than having @ lengthy ‘amount of text inthe input command, butl'snot arule that's set in stone, so do as you tke in these situations. Expanding on the code, wy this print(*HaLt! Who goes there?) rane=input() 1+ 5 fart tt re eapenengeerneestsem # Code’ to calculate rate and distance printC"Input @ rate ond a distance”) rate = floatCinput("Rate: ")) ear, or TD tesa goodstartto a text adventure game perhaps? Sup Now you can expand onit and use the raw input from the user to Flesh out the game a lle: if namess"David": print "welcome, good sir. You may pass.”) else: printC*I know you not. Prepare for battle!") wnbampubtiationscom FRPITD 1 firaisethe rateand distance code, we can ade distance = floatCinput¢*Distance: *)) print(*Time:”, (distance / rate)) Saye and execute the code and enter some numbers. Using the Floatfingut element, weve told Python that anything enteredisa Floating point umber rather than a string, “Me Compt Cong Manual ) Getting Started Python) Creating Functions eee arm inaneeieisets Functions. You've already used a few functions, such as the print command but Python enables you to define your own functions. FUNKY FUNCTIONS ‘A function is a command that you enter into Python to do something. It's litle piece of self-contained code that takes data, ‘works on it and then returns the result, Bea e's not just data that a Function works on. They can doall manner of useful things in Python, such as Sort data, change items from one Format to ancther and check the length or typeof items. Basically, function isashort wor that's Faliowed by brackets. For example, tng), Ust) or type. Bey You can pas variables through functions in much the same manner, Le’ assume you want the ‘number of letersin a person's surname, you could use the Flowing code (enterthe text editor for this example} ame=input (“Enter your surnane: ‘count=Len(nane) print C*Your surname has", count, “letters in it.") Press FS and save the code to executeit. 3 ‘function takes data, usually 3 variable, works on itdepending on what the Function is programmed tado and returns the end value. The data being worked on goes. inside the brackets, sof you wented to know how many letters are inthe word antidsestablishmentararism, then you'd enter LenCantidisestablishmentarianisn”) 21 the number 28 ‘wuld return, Python has es of Functions ul into a too Suz ‘many to get into in the limited space available here. However to view thet of bitin ution sabe to Paxton 3 raga to waridocs phanorg/3braryuncionhn. These are the predefined Functions, but since users have created many ‘more, they ee nat the only anes available. junction froma module enter the name of ie followed by fulstop, then the name addtional functions canbe added to Python Tous BULGED tscouch modules ychon hes avast range o Buse ‘modules available that can cover numerous programming duties. ofthe function. For instance using the Math module, since youve They add functions and canbe imported as and when required. For just importedit into Python, you can utilise te square root function ‘example, to use advanced Mathematies Funetions enter Toda0, enter: ‘import: math mmath.sartC16) Once entered, youhave rmadule functions. You cansee that the code is presented as module Function(éat) FORGING FUNCTIONS ‘There are many different Functions you can import created by other Python programmers and you will undoubtedly come Pee sete ee ea eee ens ee eee ete) Pret oO) Press FS to save and run the srit, You can see Hello in the Shel eee eee ence STEP 2 pean pte rey es parr Peper er entree tetas fet rettot none) | import the module then use the uneion. ry this one, and modify Brine CreTtoh nore nicer PrelloC Dovid) a cee Perey if ) Getting Started Python) Conditions and Loops reste tence eau cn eo mR Teun Cenc te Case ena TC Ree cata hectic tee oer cre TRUE CONDITIONS Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking if something is TRUE, then doing something else if itis. Let's create a new Python program that will ask "Now you can use anf statement to check ifthe BUD the sertoinguta word thencrecccosce res all ior length varisble equal to fourand pint» ‘afourletter word ornot. Start with File> New File, andbesinwith friendly conformation fit applies tothe rule the input variable word=input(“Please enter a four-letter word: *) wordsinput(“Please enter @ four-letter word: “) __word_Length-Lencword) Uf word_length = 4: print (word, “is a four-letter word. Well done.” “The double equal sig something ese. means check ifsomething sequal to Now we an create anew vibe then use helen Te colon atthe end of tele Pthon thai guar! Function and pass the word variable through it to. Suz ‘statement is true do everything after the colon get the total numberof letters the user has just entered that's indented, Next, move the cursor backto the beginning oF wordwinputC“Please enter a four-letter word: “) tre Foto vword_length=lenCword) wordwinput(“Please enter a four-letter word: “) ‘nord_lengthsLen(word) Af word_length = 4: print (word, “is a four-letter word. i Welt done”) | else: | print (word, “is not a four-letter word.") | Press Sand svete code to execute it Enter Now expandthe code onc SEP a foursetter word in the Shell to begin with, you SHEDS Eventu mh it could become quite complex. We've ‘ould have the returned message that's the wordis four lee or threedetter words Now press FS again and rerun the program but this time enter a Fiveletter word The Shel wil isplay that t's not a Fourletter word Sri Geta a 0 Ure eter word Ty gn") ! print (word, “is not a four-letter word.”) LOOPS eee ge er na ee ee Cee SMe mee ate se ton cay Cnet De ee eae) STEP.3) kc ate Doge “Uncory print nord) STEP 2 ques eee STEP 4 pee aero pre errr nee te rere Fror x in range (110) ae ee amet eter een eres Rieaeioar ertoren einer E rr earn eee i eee ett Getting Started with Python Python Modules We've mentioned modules previously, (the Math module) but as modules are such a err cusame ea aia eum ete tle eT eC aad them. In this instance we're using the Windows version of Python 3. MASTERING MODULES Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are countless modules available and as we've seen, you can even make your own. though goo, the bul uncon within Pho Theres isnt recognised pip install pygane example on non platforms s the Pygame module, which contains clckthe result then click Run as Administrator. Linux and Mac users ‘mary functions to help create games. Ty-import pygame. can se the Sudo command, with sudo pip install package Clase the command prompt or Teminalané Sia relaunch the IDLE Shell, When you now enter: ‘import pyoaHe the mocks wil be moored int the code ‘tout any probes. You'l find that most code downloaded oF copied Fem the inert wl contain mode maistieam of nie, hese ae usualy he source of ers execton de to Uhembeing sig. [Braet C Python Modules Cal FAIR tiple modules can be imported within your code. To extend our example, use ‘import random import math for I in ranges): ‘printrandom.randint(ay print (nath:pi) Boa ee 25) ‘The modules contain the extra code needed to achieve a certain result within your own code, as ‘we've previously experimented with, For example: ‘import random Brings inthe code from the Random Number Generator module, ‘You can then use tis module to create something tke: for i in range(10): pprint(random.randint(1, 25)) Bom Ee The results astring of random numbers followed by the value of Pas pulled from the Math ‘module using the priat{math function. You can aso pullin certain functions From a module by using the from and impart commands, suchas: from random import randint for i in ranges): printCrandint(l, 25)) Bam rae This ode when sadn erected il platen Sup random numbers from 1 to 25. Youcan play around witha code ta dply more ors and oma geno ler ‘ange. Fr eamole ‘moore rendon for i in rongeC2s): ‘PrintCrandom.randint2, 100)) wnbampubtiationscom Trish crate ore steaminesaproachto GA Programming, You can also use Import module*, wich limport eve ing deed win the named modal However is often regarded as waste of resources but it works ronetheles. Finally, modules canbe imported as alases: ‘import nath’asim printcm.pid OF course, adding comments helps to tell others what's going on [a aaa cares ss “Me Compt Cong Manual =D Getting Started Python) Python Errors eee orn erent cm ers Python declares it’s not able to continue due to something being missed out, wrong or ee ene eC cai iae earn cachet ee caic DEBUGGING Errors in code are called bugs and are perfectly normal. They can often be easily rectified witha little patience. The important thing is to keep looking, experimenting and testing, Eventually your code will be bug Free. Codeisrtaefuidasthewriten word,no matter i Thankful Python elu when comes to Sues how goad the programming language is. Python is. EE displaying errar messages. When you receive an certainly easier than mostlanguages bt even tis prone tosome error ined text from the IDLE Shel til define the error itself “annoying bugs. The most common are typos by the user and whilst along with the ine number where the erorhas occurred, Whist in easytofindin simple dozertine code, maginehaving todebug _the IDLE Edltor this is alittle daunting for lots of code; text editors rmult-thousand tne code. help by including tne numbering The most common of erosisthe typo as weve Syntaxerorsare probably the second most Siare mentioned. The typos are often at the command Suz ‘common errors you'll come across as @ programmer, lev metiping te prin commandfor example. However they aso Evenifthe splin correc, che atl emmand te rong ‘occur when you have numerous variables, all of which have lengthy In Python 3 ths often occurs when Python 2 syntaxes are applied ames. The best advice sto simply gathrough the cade and check The most annoying ofthese isthe pine Function in Python 3 We use your spelling print words") whereas Python? uss print “words”. "oe 8 Otin m ie at oh eg Be Yr se rae or “ee fr train es tres age onan fr ice tortie. (_ Python Errors Gal Pesky brackets are also @nuisancein programming ‘errs, especially when you have something like Bea printcbatanced_checkCinout@)) Remember tat for every there must be an equal numberof Tier oe Anexcellent way to checkyour code step-by-step Isto use Python Tuto’ Visualize web page, found it. Simply at wunwpythontutarcomisualize htmisimod paste your cade into the editor and click the Visualse Execution button torunthe code lne-by:ne. Thishelpsto clear bugs and any misunderstandings ‘There are thousands of online Python resources, code snippets and lengthy discussions across Forums cenhow best to achieve something, Whist 99 per cent ofits goad code, doit always be lured into copying and pasting randam cade Into your ector. More often than not, won't work andthe worst pats that you haven't learnt anything Baa Indes re a nasty pat of Python programming Sup that a lot of beginners fall foul of. Recall the IF loop fram the Condor and oops section, where he lon means everyting indented allowing the statement tobe excited 8 longas true? Missing he indent orhaving too mucha iden, willomeback with ane wnbampubtiationscom Ee Planning makes For good code. Whilst litle old school t's @ good habit to plan what your code vl do before sitting down totypeitout.List the variables that will be used and the modules too;then write autasrip¢For any user Interaction o outputs. Purely out of interes, the word debugging in computing terms comes From Admiral Grace Hopper, wha back nthe 40 was working on a monolithic Harvard Markl lectromechanical computer. According to legend Hopper Found a moth tuck n a relay, thus stopping the system from working. Removal ofthe moth was hence called debugging “Me Compt Cong Manual ED Getting Started Python) Combining What You Know So Far Wee eau une cement omuce ena) we've looked at so far, and apply it to writing a piece of code. This code can then be used Eee ON aes lcd cd toe ee PLAYING WITH PI For this example we're going to create a program that will calculate the value of Pi toa set number of decimal places, as. described by the user. It combines much of what we've learnt, and alittle more. Start by opening Python and rating a New Fein oe the Editor. First we need to get hold of an equation that can accrately cleat thou rendering the computer’ CPU cseless for several minutes. The recommended caleation \sedinsuch cremstances ite Choco Ago, yoo Canfind mere information above eatenvwikipedia. oak? Chudrovshy.sigorthm, You conse the chido Algor to ete STEP 2 your own Python script based on the calculation. Begin paring some rmporae modules and unions win themoddes from decimal import Decimal, getcontext ‘import math This uses the decimal and getcontext Functions from the Decimal ‘madule, both oF which deal with large decimal place numbers and naturally the Math module. Now youcaninserttheiclaaton aigorithn SES art of the code, This isa version of the Chudnovsky Algorithm: ef cale(n): ‘t= Decinal(o) pi = Decinal(o) ddeno = Decimal) k= for k in range(n): + = (ecimal(-1)**410*(nath. Factorial (Decimal (6)*1))*(13591409 +545140134°K) ‘deno = math. factorial (3*k)*Cnath. Factorial(k)**Decinal(3))*(640320°*(3%)) pi += Decimal t)/Decinal(aeno) pi = pi * Decimal (12)/Decimal (640320"*Decinal(1.5)) pi = I/pi return str(pi) Te preiusstep defines the lesthat mate ue) up the algorithm and creates the string that will venta dena the vel of P, acorn the nowy brothers lgortim. You hve no doubt already surmised tat woud be handy to actualy utp thevalve oft te szeen To recy thay cane printCcalec1)) You cansave andexecte the cde at ont SE?6 ‘you like. The output will print the value of Pi to 27 Cecil pcs 3. 1459263359973«207668452591 hist petty impressive on sown, you van some zr trato co ssthe (ser artoow many places shoddbe calcite ‘You can inser aninputtine before the Pcacuation Sug Def command. it needs to be an integer, as it will there deauttoa sting. We can callitnumberfaigit and use the gtcontex Function runberofdigits = intCinputC*pleose enter the number of decimal place to calculate Pi to: “)) getcontext().prec = numberofdigtts You can execute the code now and asks the user Sieh ‘how many decimal places they want to calculate Pi to, ovtputing the resutin the DLE Shel Try th 1000 paces but dot go too high or ese your computer wil be locked upin calculating Fi Partof programming sbeho Ts Sue able to modify code, making itmore presentable. Let's include an element that times how long it takes our computer to calculate the Pi decimal places and present the information ina diferent colour For this, crop into the commandline and import the Colorama module (RP users already have it installed) pip! install colorana Tofinish our code, we needte intaise the Sue Colorama module and start the time Function at the polnt where the calculation starts, and when it finishes, The end results coloured ink displaying how tong the process took (nthe inal or commandline} From decimal. import Decimal, getcontext ‘import math import time import colorana fron colorana inport Fore colorana.init© runberofdigits = intCinputC“please enter the nunber Of decimal places to calculate Pi to: “)) getcontext©.prec ~ nunberofdigits start_tine = tine.timeQ GeF catecn)! ( Combining What You Know So Far Bea to import the Colorama module (which wil outpuc text in efferent colours) along which dictates the foreground, nk, colour) and the Time module to stata virtual stopwatch to see how long ‘ur ealeulations take: import time import colorana from colorana import Fore = Decimat¢a) pi = Decinal(@) deno = Decimal (0) k=0 for k in range(n): £ = (ecinal(-1)**k)*(nath. Factorial Decimal (6)*k))*(135914094545140134"K) eno = math. factorial 3*)*(rath. Factorial (k)**Decimal(3))*(640320°"(3*K)) i += Decimal Ct)/Decimal Cdeno) pi = pi * Decimal (iz)/ Decimal 640320**Decimal(1.5)) pi = Vpi return str¢pi) printceatec1)) rintcFore.RED + “\nTine taken:”, tine.time() = start_time) PEE au mAs CEOS Ru ere Do eae Cae Cue Ne eae nr Ri aL ca you can create lists, tuples, dictionaries and ee us Meme eT) Deu reac) Ene me es We take a look at how you can use date and time Functions, write to files in your system Bo eaten tice curt that will take your coding skills to new levels and open more doors for you. icy Tuples Pera Splitting and Joining Strings eee ee Pree Cnr Writing to Files Soe Python Graphics eae iene Lists Lists are one of the most common types of data structures you will comes across in Python. A list is simply a collection of items, or data if you prefer, that can be accessed as a whole, or individually if wanted. WORKING WITH LISTS. Lists are extremely handy in Python. list can be strings, integers and also variables. You can even include Functions i ists, ‘and lists within lst. 5 Atstisa sequence of ata values ced ters You You canaso access oindxthelstitemin abst by ar create the name of your list followed by an equals ued using the minus sign before the item number [-1], sign, then square brackets and the tems separatedby commas; _orthe second to last item with f2] and so on Trying to reference an note that strings use quotes: item thatisnt inthe is, suchas [10] wll retun an error: numbers = [1, 4, 7, 21, 98, 156] runbers[=1] inythical_creatures ~ ["Unicorn”, “Balrog”, snythical_creatures[-4] “Varpire™, “Dragon”, “Minotaur”} SEE orcsoccrncircimsonctcas ERE hrgssntoto nace seyevonsevee Seceereteeererseceseruece, — EEED Sscectownttrsoans ore Geamuehilicnssyadtlocliyi tien winston Forexample: uberst139 numbers Will output the 4 and 7, being iter numbers 1and 2.Note thatthe ‘ocalluptheentie contents of the Uist. Feturned values dont include the second index postion as you rumbers(3] Tocallthe third from zero item inthe st 21 inthis case) ‘would numbers[:3]to retuin 4,7 and 21), sos ates ne 1 You can update items within an existing list, remove items and evenjoinlststogether For example, to Join two tists you can use: everything = nunbers + mythicalcreatures ‘Then view the combined lst with everything You canview hatcanbe done wth sts by enering Sia Gir(list) into the Shell. The output is the available Functions, for example, insert and poo are used to add and remove items at certain postions. To inser the number 62 atitem index & numbers insert (4, 62) Toremoveit: runbers.popC4) PRP roms an be added toa ist by entering: runberssnunbers+[201] OcForstrings ythical_creatres-aythical_creaturest{"Grifffr"] (rby using the append function nythical creatures. append(“Nessie”) umber .append(278) Pe ae acer wont tin ‘You alto use thet function to break string down uae) into its components. For example: Vistc“pavier) ‘xeaks the name David into toanew st ane=List(*David Hayward”) 14, 7,6. This can then be passed rane ege=[44] user = nane + age user Removal ofitems can be donein two ways. The First isbythe item number: ‘del nunbers(7] ‘Alternatively, by item name: mythical creatures. renoveC"Nessie”) Eee dt wnbampubtiationscom Based on that, you can create a program to store someone'sname and age as alist: rane=input(“What"s your name? “) UnaneslistCname) ‘age=intCinputC*How old are you: “)) Lage=Lage] user = Inane + lage “The combined name and age ist called user, which canbe called byentering ser int the Shell Experiment and see what you can do, > Working with Data Tuples Tuples are very much identical to lists. However, where lists can be updated, deleted or changed in some way, a tuple remains a constant. This is called immutable and they're perfect For storing fixed data items. THE IMMUTABLE TUPLE Reasons For having tuples vary depending on what the program is intended to do. Normally, a tuple is reserved for something special but they're also used for example, in an adventure game, where non-playing character names are stored. 5 ‘tuple createdthe some woyasatst bt nth You can create groupedtuples int its tat conan ar instance you use curved brackets instead of square ue ‘multiple sets of data. For instance, here is a tuple brackets. For example: called NPC (Non-Flayable Characters) containing the character name months=C*Jonuary"ssFebruary”s"March"sisAprivey _ 2ndthelecombat rating for an adventure game "May", “June") NPC=EC*Conan”, 100), (*Belit”, 80), rnonths Valeria”, 957] ed Stag a a ry “Be oh tre oe SE occ winisinctesuranaronec tec RRP ‘arc noteyscnveacesctos EGD eccscmsmeces BEAD eee cee range,ie. indexed according ta their position NPC[O), You can also index the mmonths{0) indvial tuples within the NPC st: — Neca] (1 However, any attempt at deleting or adding tothe tupewillesult wil splay 100 in an erorin the Shell ows Manalseres-Volume 17 From the norm. You would expect the 95 combatting ofthe ‘character Valeria to be NPC[a[5], but t's rot. ts actuals: nect2]t1) Its wath noting that when referencing mule Sia5 tuples within a list, the indexing is slightly different Now unpack the tuple into two corresponding variables: (rane, conbat_rating)=NPC ‘You can now check the values by entering name and combatting Bea wa 2 20 aa ‘which as you can imagine, getsalitle confusing when you've got 3 lotoFtuple data to deal with PRP This means of couse thatthe indexing Follows thus: Remember, swthlists, youcan also index tuples uae) using negative numbers which count backwards | from the endo the data lt. For our example, using the tuple wth multe data ems, you would erence the Valea characte wth Nect2]¢-0 Tuples though use a Feature called unpacking, BED irene tates stored withinatupte se ‘assigned variables First create the tuple with twoitems (name and ‘combat rating) ‘NPc=C*Conan”, 100) wnbampubtiationscom ‘You an use the maxand min Functions findthe Suit highest and lowest values of a tuple composed of numbers For example: runbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) “The numbers canbe integers and lost. To output the highest and lowes ue: primtCnaxCnunbers)) print CniinCnunbers)) “Me Compt Cong Manual > Working with Data Dictionaries Lists are extremely useful but dictionaries in Python are by Far the more technical way of dealing with data items. They can be tricky to get to grips with at first but you'll soon PeeSCer acl Metra s 5 KEY PAIRS ‘A dictionary is tke a lst but instead each data item comes asa pair, these are known as Key and Value. The Key part must be ‘unique and can either be a number or string whereas the Value can be any data tem you like. 5 Letssay you wanttoceateaphoneookin Python. ‘swith its and tuples, you can checte contents ar ‘You would create the dictionary name and enter ued of a dictionary by giving the dictionary a name: the dataincutybracets epmratngthe ley analy clon _phonebod nts example tii spate as ems youve Key:Value. For example: enteredin similar fashion toa lst, which youre no doubt familar swith by now, Phonebooke{“Enma”: 1234, “Daniel”: 3456, “Hannah”: 6789} SE orcwinvesiscnesoiso sg RBBB ‘ncbrre vnasccersy sau | ster 2 esaaaiee oeaeceeeseeigiema °° + cieteaeseaa tects resevenbstiseramensiicnanircke’ panenaeur torturer one Sigenracminescourseseetee, mmoknansie snavoies: phonebook “Hannah” Phonebook2={"“David"; “0987 654 321} ows Manalseres-Volume 17 valueiters tke phonebook[*“David"] = “0987 654 321” phonebook ‘Adding toa dictionary seasy too. You can include ‘anew data item entry by adding the new key and Nest youneedto dfethe ser inputs nd SIEES variables: one For the person’s name, the other forthe phone number ets eep simp avid ngthy Python code) rramesinputC“Enter name runber=intCinput"Enter phone nunber: “)) ‘You canals remove ems fram a dcionay by SMePe issuing the del command followed by the item's key; the value will be removed as well, since both work as a pair of dataitems: ‘del. phonebook{“David"] fat ems Ho tis 38) phonebook[nane] = number Taking this te farthehow about cresting a Serv piece of code that will ask the user For the dictionary key and vale items? Greate anew Ecitor instance and start by coding ina new, bank dictionary phonebook={} wnbampubtiationscom Now hen ousave detects the code, Python Suerdo will ask for 2 name and a number, it will then insert those etter Into the phonebook dona, whihyou can est entering the hl phonebook pPhonebook[“David"] Ifthe number needs to contain spaces you need to makeit.astring, soremove the int part ofthe input “Me Compt Cong Manual Bg Splitting and Joining Strings eR one Tu aun ster gue DR esc come across long sets of strings. A useful skill to learn in Python programming is being able to split those long strings For better readability. STRING THEORIES ‘You've already looked at some list functions, using .insert, remove, and pop but there are also Functions that can be applied tostrings. “The main tool inthe string Function arsenals pl USD wists iyou'reasie to salt apart. astng o ata, based on the argument within the brackets. Fr example here'sa string with three items, each separated by a space ‘text="Daniel Hannah Emma” Now let's turn the string into alist and spitthe contentaccordinaly: names=text.split(* *) ‘Then enter the name of the new lst, names, to see the three tems. Note thatthe text split part has the brackets, quotes then a space followed by closing quotes and brackets. The spaceisthe separator, indicating that each Uist Item entry is separated by a space. Likewise, Sv (Comma Separated ‘Value content has comma, so you'd use ‘text="January, February, March, April May, June” nonths=text. split," rnonths BATES) Te opposte of the split function i join, where BABB As withthe spit function, the separator doesn't you wil have separate items in string and an join have tobe a space ican also be a comma, aFull them alltogether to forma word orjust combination items, stop, abyphen or whatever you ike: ‘depending on the program you're wing For instance a ‘lphabet="", joinC[a”,"6","c","4","e"]) col=",".join(colours) ‘lphabet “This wil splay ‘abede' inthe Shell Nou ntierclrespyjontotheszpztedrane RRA) The'ssonerceing nconsyouzpp oa SMePe you made in Step 4, combining the letters again to uae) ‘string, such as capitalize and Ltitle. For example: Form the name ‘eitLe="conan the cimerian” rrame=”. joinname) title.capitalizeO rane title. titleQ ‘we've joined the string back together and retained thelist called name, passing Itthrough the join Function. Ascoteanolesfuiathe infuntontvten TARE You antovlocomatonensinas Suse _you have a list of words you want to combine into Suit with the ‘in’ and “not in’ Functions, These enable sentence: youto checkf string contains or does not contain) a sequence Liste["Conan”, “raised”, “his”, “mighty”, “sword, °ftavaters “and”, “struck”, “the”, “denon”) message="Have a nice day” texte” “.joinClist) “nice” in message text "bad" not in message Note the space between the quotes before the join function (where “day” not in message there were no quotesin Step 6 join). “night” in message wnbampubtiationscom ED Working with Data Formatting Strings Rec eee iru eu stn unc eee Mr MMR cn on ee A nea Peta ruta cle keouate aur ces 5 STRING FORMATTING ‘Since Python 3, string formatting has become a much neater process, using the format function combined with curly brackets. It's.a more logical and better Formed approach than previous versions. 5 The basi formatnginPthon toca each You canof couse ance integersinto the mi ar ‘variable into the string using the curly brackets: ued unber=10000 ane="Conan” print(“{} of {} was a skilled mercenary, printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a 1D" format name) mmerchant.”.format(nane, place, nunber)) ‘Remember to close the print Function with two sets ‘There are many different ways to apply string of brackets, as you've encased the variable in one, Formatting, some ae quite simple, as we've shown ‘andthe prin function in another. You can include multiple cases of _youhere;athers canbe significantly more complex. I all depends String Formatting in a single pit Function: ‘on what you want from your program. A qood place to reference Frequently regarding string formatting is the Python Docs webpage, Found at www. docs python.org/2.1/ibrary/string html. Here, you wl fied tons of help. rrame=""Conan” place="Cimeria” printC“{} hailed fron the North, in a cold land known as. {}”.formatCnane, place)) Formatting Strings Gal Iereitycucactereealatshaihesung ETERS You ans pintouthe coment ausesinpt Sia5 Formatting function. You need to place an asterisk in Sia in the same fashion: frotoF thelist name rane=input("What"s your name? *) runberss1, 3, 45, 567546, 3425346345, print(*Hello {}.”.format (name) PrintCSome numbers: (2, (+, Oh, Oh, (". formatctnunbers)) \whineng ints te saneepestocalings RRR vou 2 oerdthsiolcate nolo da STEP 6 Ti using string formatting, You can index each item SUED nest ictter ina person's entered name: _2ccording tots position (from 0 to however many are present) ranesinput(“that’s your name? “) runbers=1, 4, 7, 9 printCHello {}.”.formatnane)) printCMore nunbers: {3}, {0}, {2}, Inane=Listname) {1}.". Format*nunbers)) print(The first letter of your nane is a {0}". format *1nane)) Be i Beg ge rasmoiocibyrunecyucanncton TRAE you cn socal gon sparo sande Suary and integers in a single list to be called in the Suerdo ‘them individually within the same print Function, Format function Looking back the code fom Step 7, you can alter it with: characterss[*Conan", “Gelit", “Valeria”, rrames=[“Conan”, “Belit”, “Valeria”) 19, 27, 20) ages=[25, 21, 22] print C*{0} is {3} years old, Whereas {1} is {4} Sears ToLarezromatecnaracters)) Creating two ists. Now you can call each st, an individual tems: printC*{0[0]} ts {201} years old. Whereas {0011} is {1012} years old.”.fornat(nanes, ages)) wmbanpatonsm eceolcecoin ont EE > Working with Data Date and Time PER Renee a eel a ec CRT eee eee aCe ism eet eee ee aCe Rte Mee nae Gaon la actu ce TIME LORDS ‘The Time module contains Functions that help you retrieve the current system time, read the date from strings, Format the time and date and much more. 5 Fist youneedtolmpotthe Te module. 'sone You canseethe sructre of how tines presented ar that's built-in to Python 3 so you shouldn't need to ued by entering: drop nto command prompt and pip install. Once R’Simported, —gewgtoea time) you can cal the current time and date with a simple command: a ‘he outputs dsplayed assuch: “time, struct-timeCtm ee yeor=2017, tmmon-9, tmnday=7, tmhour=9, “ ‘tmmina6, tm_sec=13, tmnday=3, tmyday=250, tm ‘isdst=9)'; obviously dependent on your current time es opposed tothetime this book was written rete hi catericeme eae Thee wenongsforirani ere Rocircmesice sassy EEE mssowycecenearect: Ten mcnoninbetoen detbine Teieadwaht ul itopoat sue gel eaeens eee ves time, strftimeC*KA”) ten tot (oor et we epson) 0:96 (0 Monday) 12026 cut dy) sos ates ne 1 ‘This naturally means you can incorporate various Sia5 Functions into your own code, such 3s: time.strftimeC*¥a") ‘time.strftime(“B") time.strftimeC“%") ‘time.strftimeC4") time.strftimeC“M0s") ( (Date and Time Gal You sawatthe end ofthe previous section, inthe Sia code to calculate Pi to however many decimal places thesers wanted, youcan tine apart evetin Python. Take the code fom above and ater slighty by including start _timextime.time) ‘Then there's: endtimestime.tine()-stort_time ‘Gory arapiocrnaryuen oalagnareny ee = em fart Be Sis Yo Not the ast bo ene wah Hand HRM, peng _you can see these are the hours and minutes and as. the lst entry indicates entering them as %HGM doesnt display the time carecly inthe Shell You can easy recy this with ‘time. steftine CHP) Theuanguiclonte oases Lsteaeceevepernranirin etait sccatege eg ries Fee epic This means you're going to be able to display either BALD tye csrenctime or the te when something cccurted, such asa user entering their name. Try this code in the Editor: import time rrame=input(“Enter Login name: “) printC*Melcone", nane, “\d") printC*User:”, nane, “Logged in at”, time. strFtimeM:2M")) ‘Trytoextendit further toinclude day, manth,yearandso on, wnbampubtiationscom Theres alotthat can be done withthe tne Suerdo module; some of it is quite complex too, such 35, ) Working with Data Writing to Files The ability to read external files within Python is certainly handy but writing to a File is PCM MeCN testator Terie Pinaceae (erent a eens WRITE AND CLOSE ‘The write() Function is slightly more complex than read!). Along with the filename you must also include an access mode which determines whether the file in question isin read or write mode. ESTEE %2"tby opening ILE and enter the folowing: PRED However, the actual text leis stil blank ou can ee check by opening itup). This is because you've i vate the tine of textto the file objectbut nat committed itt the text txt, 7w") Fleitsel Part of che write Functionis that you need to commit the ‘Change the destination from /home/ai/Documentsto your own changes the ile; you can dothsby enterin: system. This code wil create atert fe called text.txt in write mode ‘sing the variable. If there's nile ofthat name in the location it vill create one. Fone aleady eis, it wil overwrite so be careful t.closeO) SEE crconwicwericntcsnrte we), SEP, iscoronsenetenennstoneser BED mccain, ERED procsam esrecnanee instead of reading them. Try this: vwrttento the fe. This sves us the Foundation fr sme interesting cial 7 posses: perhaps the creation of your own log he oreventhe t.writeC'You awake ina snalt, square room. A Pessbties perhaps the cestion single table stands to one side, there is @ locked ‘door in front of you.") Note the 109. k's the number of characters youve entered. sos ates ne 1 Toexpandthiscode you can reopenthefieusing SIE ‘a’, For access or append mode. This will add any text atthe end ofthe orga ine stead ot ping tefl andcreaing Snewone For exemple ‘teopenC/hone/pi/Documents/text.txt,"a") ‘tewnitece\n") t.writeC You stand ond survey your surroundings. (On top of the table is sone meat, ond a cup of water.\n") L (writing to Files [ You an pas variables to file that you've created in ython, Peshaps you want the value of Pi to be ‘written toa, You can cal Pi fromthe Math madule, create 8 new File and pass the output of Pint the new ile: ‘import math printC"Value of Pi is: “,rath.pid PrintC*\nliriting to a file now.) You can keep extending the tex tine by ie, ending SMePe ‘each with a new line (\n). When you're done, Finish the cade wth tore and open the fe inatextedtorto see the results ‘tunriteCThe door is mode oF solid oak with iron strips. It's bolted from the outside, locking you in. You are a prisoner!.\n") eetoseO, Nowlascrete avr caled land asin the pisath. pi ‘You also eed to create anew file in which to write Pt ‘t-open("*/home/pi/Documents/pi.txt”,"w") Remember to change you le location to your own particular system setup, There are various types of il accessto consider {sina the open( function. Each dependson how the files accessed and even the postion of the cursor. For example, r+opensafilein read and write and places the cursor at the tart ofthefle, wnbampubtiationscom Tofinish, you can use string formating to call the variable and write ito the ile, then commit the changes and close the file: t.writeC‘Value of Pi is: {}".formatCpi)) t.close() You can see fom the resuits that youre able to pass any variable toafie. “Me Compt Cong Manual ) Working with Data Exceptions Pe Ne aR eRe cet re aco! assume you ask a user to divide two numbers and they try to divide by zero. This will erect eee dice artes EXCEPTIONAL OBJECTS Rather than stop the flow of your code, Python includes exception objects which handle unexpected errors in the code. You ‘can combat errors by creating conditions where exceptions may occur. You can create an exception error by simply trying to divide anumber by zero. This wil part back Bea vith the ZeroDivsionError: Division by zero message, as seen inthe screenshot. The ZeroDivisionError part isthe exception lass, oF pe ‘You canusethe functions ase exception to create EE ‘our own error handling cade within Python. Let's: assume your code has you warping around the cosmos, a0 mich however ess ina war core breach. To stop the game from vlch there ae mary. exiting due t the warp core going supernova, you can createa custom exception: raise Exception(*warp core breach”) SED host oxestions IB 10029 ry eorsinthecodeyoucanencase the S are raised S potential error within a try: block, This block consists atonal when Python cf ty except, a, where codeishldwtin tg, hen hers foes acossometing at’ anexcepton do someting, eb do someting ee. inherently wrong withthe code However, you an create your ‘own exceptions that are dascned to contain the potential error and Feactto it, 35 opposedto letting the coge fall. ows Manalseres-Volume 17 For example use the Givi by 2eo ero Youcan Sia5 create an exception where the code can handle the error without Python quiting due tothe problem: try: ‘asintCinputC“Enter the first nunber: bsintCinput(“Enter the second nunber: print(a/b) except ZeroDivisionError: printC“You have tried to divide by zero!" else: print(*You didn’t divide by zero. Well done!”) ‘You anus exceptions tohandte avait of useful SMePe tasks. Using an example from our previous tutorials, lets assume you want to open a file and wit tot: try: ‘txt = open("/hone/pi/Docunents/textfile.txt™, “r" txt.writeC*This is @ test. Normal service will shortly resune!”) except I0Error: print (*Error: unable to write the file. Check permissions”) else: print (“Content written to file successfully. Have a nice day.) ‘ext close) Natural youcan qui Fixe sue by charging Sia the “r” read only instance with a “w" For write, This, asi already inl create tne nde the conten hen Committe changes tothe fie, Te end esl wl repr a iferent sstof ercumstances inthis cate, asucestul execution ofthe code Ee You can also use analy: block, which works ina similar Fashion but you can'tuse else witht. To use cour example from Step 6: try: ‘ext try: ‘txt.writeCThis is @ test. Normal service will shortly resune!”) finally: print (“Content written to file successfully. Have a nice day.") ‘text .closeQ) except T0Error: print “Error: permissions”) ‘open*“/hone/pi/Docunents/textfile.txt", “r™) unable to write the file. Check Obviously this wont work du tothe Fie texfil tut being opened as read ony (the pat). Soin this case rather than Python tling you that you're doing something ‘wrong, youve created an exception using the IOErrr class informing the user thatthe permissions are incorrect. A before an erorwillaccur as youve used the "read-only permission. Ifyou change itto "Ww, then the code will execute without the error being displayed inthe IDLE Shell Needless to say, canbe a tricky getting the exception code right the fst tie. Practise though, and you will get the hang oft wnbampubtiationscom “Me Compt Cong Manual (exceptions GET ) Working with Data Python Graphics Pose eer eee Cec rec will Sor cetera EL nes Peta TR one eee aoe LMR USI pete ceuit cen GOING GRAPHICAL ‘You can draw simple graphics, ines, squares and so on, or you can use one of the many Python modules availabe, to bring out some spectacular effects, preeereaenierner ere career ak sent eee RP ic crnnsecceso suns conve ca norenerensen mani nomics eke a ad ‘beyond; you can draw an arc by entering: turtle. circle(s®, 1180), where the size is 50, but youre telling Python to only draw Spartans Bee import turtle turtle.circle so) turtle. getscreen()._root..naintoop() ‘Asusval press 5 to save the code and execute It. Anew window wil row open up andthe Turtle’ will awa crcl, Lets beain by crawing a simple cir. Start a New Fil, then enter the Following code: ows Manalseres-Volume 17 ‘The last part ofthe circle code tells Python to keep the window where the crawingistaking ‘open, sa the user can lick to close it Now, lets Bee place to rem: make a square: ‘import turtle print ("Drawing @ square") for t in rangeC#): ‘turtle. forward(100) turtle. 1eFt(90) turtle.getscreen().—root .nainloop() ‘You canseethat we've inserted aloop to draw the sides of the square. You can adé anew tne tothe square co some colour add turtle.color¢“Red”) “Then you can even change the character to an actual turtle byentering turtle. shopeC“turtte”) ‘You can also use the command turtle. begin 110, and turtLe.end 110 to filinthe square with the chosen colours fed outline yellow filin this case. You can see that the Turtle module can draw out sere ‘some pr joad shapes and become a little ‘more complex as you begin to master the way it works. Enter this example: fron turtle import * color¢*red’, *yellon’) begin A10 hile True forward(200) ef eCA70) if absCpos()) < 1: break end #110) cone lesa diferent method, but very effective — PPI ow e's get the code by imparting the Pygame module: ‘import: pygare Pygare. init, ‘ng = pygane. image. lead(*RP% pra") white = (255, 255, 255) w= 900 h= 450 screen = pygone. display. setnode((n, h)) screen. ALCCwhite)) screen.f1CCuhite)) screen. blitCing,(0,0)) Pygone. display. flip) hile True for event in pygane.event.oet( ‘if event type = pygane.QUT pygane.quit© Inthe peviousstep you partes pyoame, tiated sue the pygame engine and asked it to import our saved RaspbertyPtgo image sovedasRPLpra Next you defined the Darkground colour othe vndow todsploy the mage and the window ease the actual inage mensions Fly youhavea loopte close the window iw = 900 lh = 450 screen = pygame.display.set_mode((m, h)) screen. fill((white)) screen. fill((white)) screen.blit(img, (0,0)) pygame. display. flip() Innile True: for event in pygame.event.get( af event. type == pygane. QUIT pygame.quit() Another way in which you can display oraphis is byusing the Pygame module. There are numeraus ‘ways in which pygame can help you output graphics tothe screen but for now let's ook at displaying a predefined image. Start by ‘pening a browser and finding an image, then save itto the Folder where you save your Python code. os | | pospberyl = ress FStosave and execute the code and your Suit image will be displayed in a new window. Have @ play around withthe colour, ces nd soon and take time to look Upthe many Functions within the Pygame module oo. RaspberryPi ‘The Complete Cong Manual (_ Python Graphics [ =D Working wi Data) Combining What You Know So Far Based on what you've looked at over this section, let's combine it all and come up with Petter arsenite yen itera aka Coa Pua Reheat ac tuck lta elles LOGGING IN For this example, let's ook to a piece of code that creates user logins and then allows them to log into the system and write the time they logged in at. You can even include an option to quit the program by pressing a. Begin by importing the Time mache, rating E ‘The loba status statement separates local BALD 3 cicicrarytohandle the useares and SUED ie rom one that canbe called throughout passwords and creating a variable to evaluate the current status of the cade, tis way youcan se the @=qué element without beng the program: changed inside the Function. We've aso referenced some newly aa efined Functions: ldUser and never which wel get tore users = status SI tre newserfunctonis nex: def newiserO: Nextyouneed todefinesome functions Youcan -_efeateogin = inputC*Create/a'Togin’nanes") Sue? ‘begin by creating the main menu, where all users if createLogin in users: vill return to after selecting the available options: ee ‘def airMenuC): else: global status ‘createPassw = input(*Create password: *) ‘status = input (“Do you have @ login account? uusers[createLogin] = createPassw y/n? Or press q to quit.) printC*\nUser created!\n") ‘if status = *y": ‘Logins=open("/hone/pi/Documents/Logins. oduser©) txt”, “a”? elif status == “n”: Logins.writeC"\n” + createLogin +“ * + nenUser) ccreatePassn) elif status == “a”: ‘logins .close() quito “Thiscreates anew user and password, and writes the entries into 3 fle called logins. (combi ing What You Know So Far [ Youraneestospetyou omioatintrte EEAAA ry ou ees cotusyteckttes tey SIE logins.txt file, since we're using a Raspberry Pi. SHEE hasn't been pressed to exit the program. We can do. Essential ths ads the username ndpasnordinpts fromthe thst userto the existing uses( dictionary, so the key and value structure remains: each user isthe key, the passwords the value iri Lerstatuszisica} status = displayMenu() Greatelogin = inputc-create » login name 1 erenatogn in uses PEP 01 to create the olser Function [SEER uence sae ane 9 SE LSET cee wire ef olduser: ec setae” ‘login = inputC“Enter Login name: *) Se et ee 2, assn = input (“Enter password: “) BESS) Teeesien cata # check if user exists and Login Ee oar wee t nee9 mmatches password al eet “if login in users ond users[login] == passw: glare sees print (*\nLogin successfuli\n") fe ane ae a rg Print C*User:", login, “accessed the system *, time.osctimeC)) os, else print C*\elser doesn" exist or wrong : — ; RaSCCIIN) PEPER hough seemingly minor two lines, the while omer Uoop is what keeps the program cuning Arte end = aaa Geen oe of every function it’s checked againt the current valu of statu F that global value isnt ‘then the program continues. F's equal to then the program can qui. while status ! status = displayvlenu() tse ‘You can now create users, thenloginwith her oe: kee BME nes an passnords witnthelogistx fle bing crested to store te login data and succesful logins being timestamped. Now it's up to yout Further improve the code Perhaps you can impor the tof created users from aprevous session and playa graphic upon a sucessful ogi? Theres afar bichappering here. There ar loin Suey and passw variables, which are then matched to the users dcionay theres amatch, then you have asucesfullgin and the time and date ofthe login outputted. Fthey don't match, then you print an error and the process starts again, etisses pes “pega wmbanpatonsm ee P| bo U Ui Modules ( Using Modules JS a DCU Ce rac PU ed heights. You can create your own ONC as Ue us ee MECC convert a mundane piece of code into ECU eee as Meu eae Pee cee cd SUIT Cee Dn ems LCF ee ocean Tee cute eee een Trecompiete coding manuat — @&® <> Using Modules Calendar Module WORKING WITH DATES ‘The Calendar module i built into Python 3. However, if For some reason it's not installed you can addi using pip install ‘calendar as a Windows administrator or sudo pip install calendar For Linux and macOS. Launeh Python 3 and enter: import: calendar to Sues ‘all up the module and its inherent Functions. Once Ie'soaded into memory, start by entering ssep=calendar. TextCalendar calendar .SUNDAY) ‘sep.prmonth(201?, 9) Tere are numerous functon within the Calendar Size ‘module that may be of interest to you when Fortming your own code. For example, you can display the number of leap years between two spectic years: Leaps=calendar. leapdays(1900, 2018) printCleaps) The results 2, starting from 1904 onward, You can see thatthe days of September 2017 re displayed ina wall calendar fashion, Naturally you can change the 2017, 9 partof the secondline to any year and ‘month you want, a birthday for example (1973, 6). The ist ine configures TextCalendar to star ts weeks ona Sunday you can opt For Monday iFyou prefer ‘import calendar print(“s>>>>>>>>Leap Year Calculatorce FER tre 055ystem( functionis what allows interaction with external programs; you can even call up previous Python programs using this method, You wll obviously need to know the full path and program filename for itto work successfully, However, you can use the following import 0s ‘s.systenC‘start chrome “hetps://mw. youtube. con/ feed/music””) For Step 5's example we used Windows, to show that the OS module works roughly the same across allplatforms.Inthat case, we opened YouTube's music Feed page, so itis therefore possibie to apen specc pages import 0s ‘os. system(chromitn-bronser “http:// bbanpubLications.com/”?) Note in the previous step’s example the use oF single and double-quotes. The single quotes encase the entire command and launching Chromium, whereas the double ‘quotes open the specified page. You can even use variables to call, multiple tabs inthe same browser: import os ‘o=C‘chromiun-browsen “http:// btnpubLications.con/”?) bb=C‘chromiun-bronser “http://m.google.co.uk”?) os.systen(a + b) The abit to manipulate decries, folders Sie you prefer, is one of the OS module's best Features. For example, to create anew directory you can use: ‘import os os.mkdirC*NEW") This creates a new directory within the Current Working Directory, named according tothe objectin the mdi Function You can also renarne any directories youve created byentering: import: os os.renameC*NEW", “OLD") Toddlete them: import os os.rndir¢*OLD") Another module that goes together with O5is Shut You can use the shutil module together with 05 and time to create atime-stamped backup directory, and copy files into it ‘import os, shutil, time root_src_dir = r?/hone/pi/Documents* root_dst_dir = ‘/hone/pi/backup/” + time.asctime() for sre-dir, dirs, files in os.walkCroot_sre_dir): dst_dir = src_dir.replace(root_sre_dir, root_ dst_dir, 1D if not os.path.exists(dst_dir): os.makedirs(dst_dir) for file_ in files: srefile = os.path.Join(src_dir, file) dst ile = os.path.Join(dst_dir, file) Lf 0s.path.exists(ast_file): 0s.renoveCdst_fle) shutil.copy(srefile, dst.dir) print(‘sssssssesBackup completecceececeee) wnbampubtiationscom “Me Compt Cong Manual WHAT IS BERG ae PO ee ac Cae CCS! [ao Cer eos Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction All languages Brand new content ol Tesi c) AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu <> Using Modules Random Module RANDOM NUMBERS, “There are numerous Functions within the Random module, which when applied can create some interesting and very useful Python programs. “ustasvith other moeies you ned to import Sue random before you can use any of the Functions ‘were going to look atin this tutorial Les begin by simply printing a random number fom 1 t0 import randort printCrandoaiint(@,5)) Inour example Sue the number four was returned However ent the pnt union few mere tines andi wl ply dierent integer vals from eset of numbers gen, zt ve. The overalefet though peeudo- fandom adequateforthe average programme to en ther eo For a bigger set of numbers, including floating point values, youcan extend the range by using the ‘multilication sign import random printCrandoe.randem() *100) Will cisplaya floating point number between 0 and 100, tothe tune oF around fifteen decimal points FAIR However, the Random module icv used exclusively For numbers. Youcan useit to selectan entry froma Ist rom random, and thelist can contain anything ‘import random random.choice(L*Conan”, “Belit™D) This will dsplay one of the names of our adventurers at random, hich sa areat addition toa text adventure game. “Valerio”, You ca extend the previous example somewhat by having random choice) select From alist of mixed ‘atiablesForinstance ‘mort random Ist=["David", 44, “BOM Publications”, 3245.23, “Pi”, True, 3.16, “Python”] ‘d=tandom. choi ceCist) print (rnd) Interestingly, you can also use a function within the Random module to shuffethe items inthe is, thus aiding a litle more randomness into the equation: random. shuffleCLst) printCist) ‘This way you can keep shuffling the lst before displaying arandom item From it. {sing shu you can create an ently random BED rvers For example, within s given ange import random Tste[CU] for I in rangec20)] rendon, shuffleCLst) printcist) ep shufing the lst and you cn haves diferent selection of ie from 01020 every bine ‘ue uo ag gn wen we (Random Module <> Let's use an example piece of code which ipsa SUES virtual coin ten thousand times and counts how ‘many times iewilland on heads or tals output={‘*Heads":0, “Tails”:0} coinslistCoutput keys) for i in range(10000): ‘output[random.choiceCcoin)}+=1 printC'Heads:”, output[“Heads”]) print(Tails:”, output[*Tails"]) ist Here'san interesting pece of code. Using a text fle containing 466 thousand words, you can pluck user generated number of words fom the ile (text Mle found at: vewanithub,com/dwyVengish-words ‘import random print(s>>>s>s>>>Random Nord Finderccexexec<<") Print(*\nUsing a 466K English word text file I can ick any words at random.\n") nds-intCinputC*\nHion many words shall T choose? *)) inith_open(*/home/pi/Downloads/words.txt™, rt") asf: words = f.readlines©) BALD 2ncein steps using thestart stop sep oon ‘import random for i in rangeC10): printCrandon.randrangeCo, 200, 7)) Results wll vary but you get the generalidea asto how it works. wnbampubtiationscom You can also select random number froma iven words = [n.rstrip( for w in words] print ") for w in random.sampleCwords, wds): printGn) prints “Me Compt Cong Manual <> Using Modules Tkinter Module GETTING GUI “Tkinter is easy to use but there's lot more you can do with it. Let's stat by seeing how it works and getting some code into it. Before long you will discover just how powerful this module realy is. ‘Tkintoris usually built into Python 3. However, Fits available when youenter: import. tkinter, then youneedto pip install tkinter from the command promot, Wie can starto import modules ifferentl than before, to save on typing and by importing altheir contents: import tkinter as tk Fron tkinter import * ‘The ideal approach isto add maintoop0 into the code to control the Tkinter event loop, but well {get to that soon, You've just created a Tknter widget and there are several more we can play around with btneButton() ben.pack( btn["text”]="Hello everyone!” The ist tine Focuses onthe newly created window. Click back into the Shall and continue the other ines It’s not recornmended to import everything From 8 ‘madule using the asterisk butt wont da any harm normally. Lets begin by creating abasic GUI window, enter: windsTkKO ‘This creates smal, basic window. There's not much else todo at this poine but click the Xin the corner to cose the window. Bee FEAR You cen combine the above into a New Fle ‘import tkinter as tk from tkinter import * btneButtonc) btn.pack( btn[“text*]-"Hello everyonel* ‘Then add some button interactions: def click: print*You just clicked me!”) benl[comand”J=click Tkinter Module <> Save and execute the code rom Step Sanda SEP window appears with Hello everyone!’ inside. IF you dlckthe Helo everyone! burton the Shell output the ex Just clicked met, ’ssimple bt shows you what can be achieved vith afew line of code, You can asa depiay both textand maces wrthin sd a Tkinter window, However, only GIF, PGM or PPM formats aresuppotted. Sond an mage and convert before ing the cade, Here's an example using the BoM Publishing ogo fron tkinter import * root = TKO, logo = PhotolnageCfile="/hane/pi/Donnloads/B0M_ ogo.aif") wl = Label(root, root. titleC*B0M Publications”), ‘mage=1ogo).pack¢side="right") content = “""" From its hunble beginnings in 2004, tthe BOM brand quickly grew from a single publication produced by a tean of just two to one of the biggest anes in global. bookazine publishing, for two sinple reasons. Our passion and comitnent to deliver the very best product each ond every volune. While ‘the conpany has grown with a portfolio of over 250 publications delivered by our international. staff, ‘the foundation that it has been butlt upon rentains ‘the sane, which is why me believe BOM isn’t just ‘the frst ‘choice it’s the only choice for the smart w2 = LabelCroot,, justify-LEFT, ade = 10, ‘textecontent).pack(sides" Left") root maintocp( The previous code is quite weighty, mostly ue tothe content variable holding apart of 8DMis About page From the company website. You cn ‘buiously change the content, te roottitle and theimage to suit your needs, wnbampubtiationscom RAID vou con create radio buttons to. Try: From tkinter import * root = Tk, v= Intvarc) Lobel (root, root.titleC“Options”), text=”*"Choose @ preferred Language:”””, Gustify = LEFT, padx = 20).pack() RadiobuttonCroot, ‘text="Python”, Radiobutton(root, text="Cr", pod = 20, voriable-v, value=2).packConchor=it) ‘maintoop© Yu canals create check boxes, with buttons and cutputto the Salt from tkinter import * root = Tk def var.statesc) printC*Warrior: %d,\nMage: Xd” % Cvart.get©, var2.getO)) Label root, root.titleC“Adventure Gane”), texta">o>>2>>>0>Your adventure rolecceccécece"). grid(ron0, stickyoN) Vari = TatVarC) Checkbuttoncroot, text="Narrioe”, varicblesvart). aridcron=1, sticky=M Var = TntvarC) CheckouttonCreot, text="Mage", variablesvar2). grid¢rom2, sticky=" Buttoncroot, texte’Quit? , comanderoot destroy). aridcrom3, ‘sticky=", pady=4) Buttoncroot, text=’Shon’, comandevar-states). gridcrom3, ‘sticky=£, pady=4) ‘maintoop ‘The code From Step 9 introduced some new ‘geometry elements nto Tkinter. Note the and W arguments. These describe the locations ofthe ‘heck boxes and buttons (North, East, South and West) The row argument places them on separate rows, Have a play around and see what you get. “Me Compt Cong Manual <> Using Modules Pygame Module PYGAMING Pygame isn’t an inherent module to Python but those using the Raspberry Pi will already have it installed. Everyone else wil ‘need to use: pip install pygame from the command prompt. Naturally you need to load up the Pygame modules Into memory before you'e able to utlse them, ‘Once that’s done Pygame requies the user to inialise itpriorto| any ofthe Functions being use: import pygane pygane.initO ‘gamewindow=pygane. display.set.nodeC(800, 600)) pygone.display.set_coption(“Adventure Gane”) es ceate a simple game ready window, and give itatitle You can see that after the ist lines entered, you need to click back he IDLE Shellto continue entering code; als, you can change the title oF the window to anything you tke, Sadly you catclse the ney crested Pygame Size window without closing the Python IDLE Shell, vic tery practical For thisreason, you nee to warkin the tor New > Fl) and crete TveFase whe oor import pygane from pygane. locals import * pygane. init) ‘gamewindow-pygane..di splay. set_node((800, 600)) Pygane.display.set_coption(*Adventure Gane”) runniing=True while running: for event in pygane.event.cetC: if event..type==QUIT: running-False Pygane.quitC) lee Famat Bun Optons wndows ep (. Pygame Module <> ifthe Pygame window til wont SES close don't worry, it’s just a escrepancy between the ILE (which wnt with Tinker andthe Pygeme module you runyour code via the command lin, loses perfectly wll PRTIED Youre coing toshitethe code around abit now, ‘imgepygane image. load(*/hone/pi/DownLoads/ running the main Pygame code withina while loos; spritel.png?) itmakes neater and easier to Follow, We've downloaded a graphic to use and we need to set some parameters for pygame: a ganenindon.blitCing, Gxy)) import pygane Pygane.inttC —— ‘gamenindow.flL¢nhite) while running: spriteCx,y). ‘ganewindon=pygane.di splay set _mode((800,600)) EEE pygane.display.set_caption(*Adventuire Game") for event in pygame.event .get(): black=(0,2,0) ‘if event. type==pygane.QUIT: white=(255,255,255) runniingsFalse PRMD e's vicky gothrough the code changes. We've downloaded image called spritet.png andallocatedit to the defined two colours, lack and white together variable mg; and also defined asprie function andthe Blt function with theierespective RGB colour val Next we've loaded the will allow us to eventually move the image, (6000-15) gamerinden. 411988) Prams di2ploy updatec) tmerindomygme. display. et mode( (200, 600)) Brame aiaplayront-captionc-sarentsre cone) Eleetsie-o°0) for eyent in pygae event. get “Shspyeame nage lad" /hone/pi/Somnlende/=pritet.one"> 7 enindeBLSeCing. (4.99) wnbampubtiationscom ‘The Complete Cong Manual <> Using Modules ) ) ‘Now we can change the cade around again tis BLD tne containing s movement option wthinthe while loop, and adding the variables needed to mavethe spite around the screen: inport pygane from pygone.locals import * pygane init) runningsTrue _gamerindompygane di splay. set-mode(C800, 600)) Pygane.display.set_coption( “Adventure Gane”) black=(0,0.0) vwhite=(255, 255,255) ‘mg-pygane: inage. Load(“/home/pi/Downloads/ spritel. png”) def sprite(x,y): ‘ganewindon.b1itCing, (x,y)) x=¢600"0.45) y-¢6a0"0.8) xchange=0 imgspeed=0 white running: for event in pygane.event .get(): ‘if event. type-QUIT: runningsFalse ‘if event type == pygane. KEYDOMN: ‘if event. key==pygane.K LEFT: xchange=-5 elif event.key==pygame.K_RIGHT: xchange=5 ‘if event .type=-pygame. KEYUP: ‘if event. keysepygane.K_LEFT or event key==pygame. K RIGHT: xchanges x += xchonge ‘gamewindow.flUGnhite) spriteCx,y) pygane. display. update) ygane.quit) Copy the code down and using the let and rightarrow keyson the keyboard you can move your spite across the bottom of the screen, Now, looks lke you have the makings oF a classic arcade 20 scroller inthe works (. Pygame Module <> “You can nowimplement afew ations andutise Sua! ‘some previous tutorial code, The new elements are the Subpraces module, of nich one eeton allows stolen second Pythons rom wit another and were gongtocretes NewFle called pygamebst import pygane inport time ‘import subprocess Pygane. init) screen = pygae display. set_node((800, 250)) clock = pygane. tine.Clock() font = pygane. font.Font Using Modules Create Your Own Modules BUILDING MODULES Modules are Python files, containing code, that you save using a py extension. These are then imported into Python using the ‘now Familiar import command. Lets start by creating a set of basic Mathematics functions. Mutiply a number by two, three and square or aise a number to an exponent (power). Create a New Fle in the IDLEand enter def timestwox): return x * 2 def timesthreec): return x * 3 def squareCx): return x * x oF poner(xy: or return xy Now ye ging to tak the uncon dtiitons Sige ‘out of the program and into a separate file. Hghighthe funcion defntion and choose Edt» Ct Choos Fle Naw Fie ad use > Paste nthe new window You now have ta separate ls one hehe uncon defines, he other wth theuncin cal Under the above code, enter functions to callthe code print Ctimestwo(2)) print Ctimesthree(3)) Print CsquareC4)) print Cpower(S,3)) Save the program as basic math.py and execute it to getthe re If you now try and execute the basic math.oy code again the errorName€rror:name'timestwo! is rot defined’ wil be csplayed. This is cue tote code no longer having accesst the Function definitions eturnto Suae the newly ceeatd window containing the function dfntion, and Clk Fle» Save A. Name this minimathpy ane sve in te same locaton asthe original basic math py program. Now dle the mnimathpy window tothebasc math py window teeopen. (Create Your Own Modules <> PRIM backto the basic math py window: atthe top ofthe ERIIMPM rinaly, you can now create arange of istatements code enter: todetermine what todo withthe number and frommininatiinpontes ublsethe newly created function definitions Af choice == ‘1": printCtimestwoCnunl)) elif choice = °2": printCtimesthree(rumt)) elif choice == '3": print(square(numt)) elif choice = “47: vnun2 = intCinputC“Enter second univer printCpowerCnum, nun2)) else: printC*Invalid input”) “Tis willimport the Function definitions asa module. Press F5to save and execute the program to seein action, aD) ‘You can now use the code further to make the BMD roca tte more vance, vtisng the ney Created movie ots ful Include some user nteracton Stary Creating abasic menu the user can choose fom printc*Select operation. \n") printc"1-Tines by tv") print(2.Times by Three”) print("3. Square”) iF choice a= °y print(es,Poner of) Pim choice = input("\nEnter choice (1/2/3/4):") any PEPER No we can add the user input to gee the number the code will work on: rum = intCinputC*\nEnter numbers) Thiswlsave the user enterednumber asthe vrble nn, . Note thator the st avaale options, the Power Siero of choice, we've added a second variable, num2, "Wispasesa second number trough the Funiondeintion caled SSS SSS ower Save and evectethe program tose kinacon choice = input("\nEnter choice (1/2/3/4):") int = Snecinputcrvnenter rab wmbanpatonsm ———— Index 4 | Say Hello , Wo) Gora Na i ay ] . : uC ut eu) Perens een) DCR UR Lut ce Cem ee as SMS A UUM co kana is created using C++. Being able to Cree eat ech world for you, in terms of desirable professional skills and the ability to Cee Seu eee eee Nut Pete ec) Ca ue ee games and much more. It's used in a Or AcurCeie ice eeCt intestate SC aie eR) the space industry. eC Ser ‘equipment and software needed to get Peru ache eta a ee Ee eeu wh Ema) How to Set Up C++ in Windows. Coed Leeann jow to Set Up C++ in Linux Ceres oer BD se soo- Why C++? eae enc mene Pa raniee a Cuetec keene en or ence ket original C language ands a general purpose object-oriented (OOP) environment. CEVERYTHING Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs, ‘device drivers and even entire operating systems. Dating backto 1979, the start ofthe golden era of home ‘camputing, C4, or rather C with Classes, was the brainchild of Danish computer scientist jare Stroustrup while working on his PhO thesis. Stroustrup’ plan wasto further the orginal language, ‘hich was widely used since the early seventies. C++ proved to be popular among the developers ofthe 80s, since twas a much easier environment togetto arips with ang ‘more importantly, was 99% compatible with the orginal C language. This meant that itcould be used beyond the mainstream Gene mea aera computing labs and by regular people who didn’thave accesso the mainffames and large computing datacentres. (C++ impact inthe digital word is immense, Many o the programs, applications, games and even operating systems are coded using C++. For example al of Adobe's major applications, suchas. Photoshop, InDesign and so on, ae developed in C+. You wil Find that the browser you sur the Internet with s written n C+, a5 ‘wells Windows 10, Microsoft Office and the backbone to Google's search engine, Apple's macOS is written largely in C++ (with some BG #include 2 | using namespace std; 2 void main() A |D{char ch; 5 || cout<<"snter a charater to check it is vowel or not"; 6 cin>>ch; 7 switch (ch) aio ( 9 case'a case'A' 10 cout< New > Empty ile, This creates anew, blank window for you to type, FEED nthe new window, enter the Following: #include Int rain { 7Avy first. C++ program Std::cout << “Hello World!\n": ¥ "Notice how CodeBlocks auto-insets the braces and speech quotes ‘The program starts and another message appears Sey informing you that Code::8locks is currently not the default application For Ce fies. You have two options, to leave everything as its or allow CodeBlocks to associate allC++ ile types. Again, we would recommend you opt forthe lst choice, to associate CodesBlocks with every supported Fle ype ITD liccFle» Save as and save the code witha AppStore. nthe Search boxenter Xcode and then turns into ‘Install App. Enter your Apple ID press Return. There willbe mary suagestions filing the AppStore and Xcode begins to download and install. It may take some time ‘window but t'sthe Fst option, Xcode thet youneed toclickon, depending onthe speed of your internet connection, zaase Take a moment to browse through the app's When the installation is complete, clickon the Open Information, including the compatibility to ensure button to launch Xcode. Click agree to the cence youhave the correct version of macOS, Xcode requires macoS, termsand enter your password to allow Xcode to make changes. 10.12. or laterto install and work tothe system. whenyou've done tat, Xcode bins to install additional components. sos ates ne 1 (How to Set Up C++ on a Mac ec” \uith everything now installed, including the additonal components, Xcode launches, displaying the version number along with three choices and any recent projects that you've worked an; although for afresh install ths shows blank. a Welcome to Xcade Start by cen on Create New Xcode Projects SITES) ‘opens a template window From which to choose the platform youre developing code For Clik the mac tab, hen the Command Line Tool option andl Nexto conto. PSTTSEDD ili the various fields but ensure thatthe Language option atthe bottom is set to C+, Simply choose from the dropdown lt. When you've filled in the Feds, ‘and made sure that Cvs i the chosen language, cick onthe Next button to continue wubampubiatonscam ‘The next step asks where to create a it Repository for all your Future code. Choose alocation on your "Mac, ora network location, and cick the Create button, When you've done all that, you can start to code The left-hand pane etal the Fes usedin the C++ program you're cocing.Clckon the rmaincpp file inthe list You cansee tat Xcode as automaticaly Sie completed a basic Hello World program for you. “he diferences here are that theint rain Function now contains ‘multiple functions and the layout issightly different. Thisisjust cade utilising the content thats available to your Mac. \henyouant to unthe code, clon Prodi > SuzEH0 Run. You may be asked to enable Developer Mode onthe Mic thisis to athorae Xcode to petformfuncons without reading your password every session. When the program executes, the outputs displayed atthe bottom ofthe Xcode window. cong cad a EP Say Hello to C++ How to Set Up C++ in Linux Peer eri enn components preinstalled, such as a compiler. The text editors are also excellent for entering code into, including colour coding, There's also tons of extra software available to help you out. LINUX++ We're going tobe using afresh installation o Linux Min for this particular ttoral. There's a coding on Linux section later in the book ‘The first step with ensuring Linuxis ready for your EEp ‘Amazingly, that’ it Everything is allready For you LD or ccsciscnecktnesytemandsotware re — Maal 2 sar coding, eres how to get your fs. crs upto date. pena Terminoland enter sudo apt-get: Update! program upand runing in Linux Mintthe main texters ed 8 sudo apt-get upgrade Press etum and enteryour {anbe launched by clicking on the Menu and ping Hed nto the pessvort. These commends updetes the entesjtem and ary Searchbar lek on te Tet Estrbutonin the ighshand pane to installed sofware open Xed File Edit View Search Terminal Help PEPER ost Linux distros come preinstaled with al the ERFAM in xed, or anyother text editor you may be usin, necessary components to start coding in Cet tenter the lines of code that make up your C++ Hello However is always worth checking tosee if everything is present, Weld program. To remind you, its sostilluitin the Terminal, enter: sudo apt-get install build-essential. and press Return, fyouhavethe right components, nothing installed butiFyoure mssingsome then int main they reinstalled bythe command. 7 /ANy first C++ program std::cout << “Hello World!\n"; #include Rat cea ERS aortas EE sorts manuaseres-vtune 17 BRTTSED Wren youve entered your code, click le > Save As and choose afolder where you want to save your program. Name the fleas helloworld pp, or ary other name just as long asithas.cpp as the extension lick Save to continue ERTL 1: ist thing you can see is that xec has automatically recognised this as aC Fle since the Fle extension is now set to.cpp. The colour coding is present inthe code and if you open up the fle manager you canals see thatthe Fle'siconhas C++ stamped on it. BETISERD With your code now saved, drop into the Terminal again. You need to navigate tothe location of the Cr Fle youve just saved. Our example isin the Documents Folder, so we can naigate toi by entering: ed Documents. Remember, the Linux Terminals case senstve, so any capitals must be entered correctly. (How to Set Up C++ in Linux BPI before you canexecute the C++ fle youneed to compile. In Linux i's common to use g++, an open source C++ compiler and as youre naw inthe same folder a5 the Cé+file goto the Terminal enter: ge+ helLoworld.cpp and ress return, davideomi Fle £6 View Search Terminal Help Sear FIR there wil bea briet pause as the code is complied by r+ and providing there ae no mistakes or erorsin the code you ae retuinedtto the command promt. The compiling oF the code has created a new fle. you enter Us into the Tesminal you can see that alongside your C++ files a.out S davide Fle Edt View Search Terminal Help ~/oocunents $ ts SCAT} fou PERITD the south isthe compied C++ code. Torunthe code enter: «/a.out and pres Return. The words Hello World? appears cn the screen. However, aout very friendly. Toname it something else post-compiling, you can recomeale with 94+ heLloworld.cpp 0 helLoworld. Ths creates an output Fle called hellowodld which can be run with: ZheLLowor ld, File Edit View Search Terminal Help Other C++ IDEs to Install IF you want to try a different approach to working with your C++ code, then there are plenty of options available to you. Windows is the most prolific platform for C++ IDEs but there are plenty for Mac and Linux users too. DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or all oF them Ifyou lke, but Find the one that ‘works best For you. RTD cicesemccyenaycs comatose saseeowoen sucess ED insane: tea ee, Taschnaedaecemadiamiernacayts tach forentseenerworsinareclsnet “download the latest version. you're stuck clckthe Need Help ink download and instal at www.codelite.org/ For more information. Career a \viminperice EE te cwrnoreenecsusctssococrt REREPRRER cso snes CED i ceiccermsnson Sin acta pnicanirctuneeeti seccemie hetsrremcioitankense fanmexepmasninertaunrets cist sete Roeecntictereaietimunacnereooaete mitre he gee tiviotalomeee ta ‘Windows, Mac, Linuxand even the Raspberry i You can find tat ynamicand static libraries. Find aut more at wwwanetbeans.org/ warwadacore.com/donnilosd Features/cppyindexhtml. (. Other C++ IDEs to Install ei” SRTISTITED, bic vctsuo se SUED Pees ececosetnmowyoeone saunaseer ns feels Ieoures some of emote advanced esturesyou saensapgeaes brwndee Arun, Courd hoten the ‘acd urna fang fseameceadaprercsae Thc Comainj nea tects seiced wducalaiscaier'” stcldagnetanses ena op ctasl ones aye and versions allow a freetrial period, Goto wwwc.visualstudio.comy to muchmore. Go to wwwanjuta.oa/ for mare information ‘see whatt can do fr you. scosslatomocedegnest> FRRIURRSMTSD thsexete salou cepa rez wea create C++ applications For desktop and CielNenisvetel? towrite C++ code for desktop and mobile erwiconments. comes with acode ector and integrated web applications acrosal the major platforms, There's an advanced tools fo testing and debugging, as well as deploying to you chosen tes ely, inzegrated debugger and a configurable workbench to Platform. Rs not free butthere's atrial period on offer before help you create your code. I's avalable for Windows, Mac and Linux Feajuring purchasing: www.qtio/at-featurestibraries-apistools- and sree to download and use: www.monodevelop.com/. andide/. i | ie FEPPIIR sicisned ev crs, espe ts clout, Utinaors a css plaforn Cos Dethatbeastsa ‘Son oler De thts or Widows yes on. ‘apd development of ode rough thesia ond Vweyr ay ters pasts dean toe andwncoerpbeahed | apresie we of ro, Forte nove sa ess nIDe bt behind woyereodngand comping hough hee'snetbeen much, Romp na beauty ht would nk developers tees go Vocatngfocsonetine itscerany one tocar Fyou ware webby Fda moet wawaltimatepperarngex.emt SSreting diferent wbloodshednet/evepp ent trecomplete coding manuat QI ca Fundamentals Tee teu CULL aL) Ren cet egos EWU Roe CUS oetLLg CRS nec ceemr ray Pe eee) CRC CR Torry ED ent sue See ae crete ceed Puen) your own code, produce an output to the screen and store and retrieve data. Building a good foundation is key to mastering C+ and learning how to structure your C++ code will help you Further down the line, Sern Seeeoe iLL) Structure of a C++ Program Cote catcy etree? Peed Cee Cir on) ) C++ Fundamentals) 114 Your First C++ Program We're going to be working exclusively in Windows with Coed::Blocks For this C++ Pec eey ee ta ee eee eeu M etn aime es into a larger coding world. HELLO, WORLD! Its traditional in programming forthe First code to be entered to output the words ‘Hello, Worl to the screen. Interestingly, this dates back to 1968 using a language called BCPL. FETED’ mentioned, we're usina windows 10 andthe PED 2% che moment t doesnt look like much, and latest version of Code:Blocks forthe rest ofthe C++ itmakes even les sense, but well get to that codein thisbook Begin by launching Code:Slocks. When open, click _ in due couse, Now dick on File> Save Fle As. Create ar find 2 con Fle> New > Empty File or press ClileShifteN on the Keyboard. suitable ecaton on your hard crve and in the FileName bo, call : ithelloworld.epp. Clckthe Save as type box and select C/C++ ies. Clckthe Save Butta, PRPISED Now you can see ablank screen, with the tab PRPIPD You censee that Code:Blockshas now changed labelled “Untitled, and the number one inthe top the colour coding, recognising thatthe fle isnow left of the main Code:Blocs window. Beginty clicking in the main C++ cade, Ths means that cade can be auto-elacted from the ‘window, so the cursor isnext tothe number one, and entering CCodesalocks repository Delete the finlude lin and —— reenterit You cansee the auto-elect boxes appearing. Z (Your First C++ Program ci BRTEEM 2urcsclection of commandsis extremelyhandy and BRNMIMBM ote again the colour coding change. Press Return at ‘cuts out potential mistyping Press Returnto get to the end ofthe previous step'stne, andthen enter: line 3, then enter int naino Notethere’s no space between the brackets Std cout << “Hello, world!\n"; FPR cnn restlne blowin min. enter acu bracket: PRIMM ust as bere, CodeBlocks autocompletesthe code you're entering, neucng pacing aosing 4 ‘speech mark as soon as you enter the First. Don’t forget the ‘Ths canbe done by pressing Shftandthekeytotherightof onan semicolon athe endo! then: hs one ofthe mos important English UK keyboard layout elements to.aC++ program and weiltellyou why inthe next —————— section. For now, move the cursor down tothe closing curly bracket peimveiaai +o opm [ae ieeia gitar BETTER otice thet CodeBlocks has automatically created BMI That's allyou need todo forthe moment. it may a corresponding closing curly bracket a couple of ‘ot look teribly amazing but C++is best absorbed lines below, inking the pais wellasasightindent. hiss dueto in small chunks. Dont execute the code atthe mament 2s you need, the structure of Css andie where the meat of the cade sentered, to look at how a Cs+ programs structured fst; then you an build Now enter: and run the code. For now, click on Save, the single floppy disc icon, My fest C+ program serait recone CEE ) C++ Fundamentals) Structure of a ee os eli ero aera rec aie mance as small as a semicolon, and your entire program will Fail to be compiled and executed. Many a professional programmer has fallen foul of sloppy structure. #INCLUDE LLeatning the basics of programming, you begin to understand the structure of a program. The commands may be different From one language to the next, but you will start to see how the code works #INCLUDE Phelloworidcp_X on ‘The tructure ofa C++ program C++ wasiovented by Danish Is quite precise, Every C++ code g peat a reece student Bjame Stroustrup in begins witha dective: include 2 1979, a5 apart of his Ph. ‘©. The directive nstrucsthe 3 thes Inially Cre wascalled C$ preprocessortoincudea a with lasses, which added section ofthe standard C++ Featurestothe already popular: code. For example: include 5 Cprosramminglanguace, siostream> incivdes the 6 ‘while makingit amore instream header to support ser friendly enuironment input/output operations. Uhroughanewstructure. Bjarne Stroustrup, inventor of cr. INT MAIN() [Sisthere | *helloworid.cpp _X | ine main niatesthe deearaton of Function, which isa groupof code statements ner the name moi Al Ccode begins atthe mala function regrdes of where it Jj aslvieswsintrecade 1 #include int main() aonen BRACES The open brace (cry brackets) something that you may nothave come across befor, especialy ifyoute used to Python. The ‘open brace indicates te beginning ofthe ‘main Function and contains all the code that belongs to that Function, sos ra Stes- vere 1 include int main() oo eene COMMENTS Lines that begin witha double lash are comments, This means they ‘wont be executed in the code and are ignored bythe comple. Comments are designed to help you, or anather programmer looking at your code, explain what's going on. There are two types ‘oF comment: /* covers muitiple ine comments, fa sngle tne. Lines that begin with adouble lash are comments. Thi means they won't be executed in the code and ‘are ignored bythe compiler. Comments are designed tahelp you, or another programmer ooking at your code, explain what's going on, There are two types of comment: /* covers multiple tine comments, // Singleline ( STD ‘while std stands For something qute different, in C++ itrmeans ‘Standard. ts part ofthe Standard Namespace in C+, which covers ‘anumber of afferent statements and commands. You can leave the stdz part out ofthe code butit must be declared atthe start with: Using namespace std; not both. For example: = Inths example we're using cout whichis apartof the Standard Namespace, ence why its there, asyoute asking C++to ust from that particuiar namespace, Cout means Character OUTput, which splays, or print, something to the screen. Fwe leave std out we have to declare it atthe stat ofthe code, as mentioned previous Finclude ‘using namespace std; Ant main () Ee cout, wubampubiatonscam ¢ Structure of a C++ Program ci The two chevrons used here are insertion operators This means that whatever follows the chevronsis to be inserted into the stdscout statement. In this case theyre the words ‘Hello, world, “ich are to be displayed onthe screen when you compile and execute the code, OUTPUTS Leading on, the “Hello, worl” part is what we want toappear en the screen when the cade executed. You can enter whatever you lke, a long asi’ inside the quotation marks. The brackets aren needed but some comple insist on them. The \n pat indicates 2 rewrline isto be inserted. My first cout << "Hello, world!\n" 4+ program ;AND} Finally you can see that ines within a Furetion code block (except comments) end with a semicolon. This marks the end ofthe statement and ll statements in C++ must have one atthe end or the compiler Failsto build the code, The very last ine has the cesing brace to indicate the end of the main Function. Vincluae lasing namespace st: ant main() cout << Mente, world!\a"7 teconieecoont CE ) C++ Fundamentals Compile and Execute ire minicom et enka structure of one. Let's actually get things moving and compile and execute, or run if Neen et ies eeu eee aa ccs 18 GREETINGS FROM C++ Compiling and executing C++ code From Code:Blocks is extraordinarily easy; just a matter of clicking an icon and seeing the result. Here's how i's done, BETTER) Oven CodeBlocks ifyou havent already, and loadup the previously saved Hella Word code you created. Eneure that there are no vaible errors, such as missing semicolons at the end of the std:cout ine. PEPIED Scart by clicking onthe Build icon the yellow cog. [this point your code has now been run through the CodeBlocks compiler and checked For any errors. Youcansee the resuits of the Bulle by looking to the bottom window pane. Any messages regarding the qualty ofthe code are displayed here. Buidlog | F Build messages x |) CppCheck/Ve in "no project" (compiler: unknown) === 5), 0 warning(s) (0 minute(s), 0 second(s)) IF your cade's ooking similar tothe one in our screerahat, then look to the ment bar along the top der the Fortran entryin the topmost menu you can see a group of icons:a yellow cog, green pay button and acoa/play button together. These are Build, Aun, Bull and Run Functions ofthe scree. g Fortran wxSmith Tools (Sr een cic++ BRPIID Nove cickon the Runicon, the green play button. ‘command tne box appears on your screen splaying the words Hello, word, Fllowed by the time ts taken toexecute the code, and asking you pres akey to continue. Well cone, you just compiled and executed your Fist C+ program, ( Compile and Execute QPS Pressngany key nthe commandline boxcloses Create deliberate erorinthe Sua retuming you to Code::Blocks. Let's alter the code Sue semicolon from the cout line, so it reads: ihtly, Under the include in, enter: cout << “Hello, world!\n" using namespace std; Starthere X| *helloworld.cpp x Then delete the st: part ofthe Cout ine; tke so: cout << “Hello, norld\n"; 2 using namespace std; a 4 _ int main() T ficinie corer sot $e meron p Te te mis 7 1) cont << "e110, worta!\n" : at 5 7 1] cout se meine, wound ar 8 : 10 Inorderto apply the new changes tothe code, ou Now ickthe Buldand Runicon again to al the ted crap, bull and un toni. This ne changesto the cage. Thine Code-lecsrefses however, youcan spl cickthe Bule/Ranicon, the contined”toexecite the cde, due tothe eroryou putin. nthe Log pane at yelow cog andareen ply bton the bottom ofthe seen you are normed ofthe ero nth et Expected before token in cating the missing semicolon BETTER staswementionedinthe previous pages, you BRIMBINM replace the semicolon and under the coutine don't need to ave std:cout If you already declare enter a newline to your code: sing namespace ste a the beginning of the code. We could have easly icked the Buin ian to begin with buti’s wath going through the available options You can aso see that by building and The \nsimply adds anew line under the last ine of outputted text. running the le has been saved. ‘Bull and Run the code, to display your handiwork, cout << “And greetings from C++!\n"; ) C++ Fundamentals.) Using Comments Coen Cee ue emer n rg combine to make a game, application or even an entire operating system, in actual Fact Oe Naeem estan cece 120 THE IMPORTANCE OF COMMENTING Comments inside code re basically human readable descriptions that detail what the code is doing at that particular point. They don sound especially important but code without commentsis one oF the mary frustrating areas of programming, regardless of whether youre aprofessional or just stating aut In short, all code should be commentedtin such a manner as to effectively describe the purpose of line, section, or individual elements. You should getinto the habit of commenting as muchas possible, by imagining that someone who daesnit know arything| about programming can pick up your cade and understand what its {going todo simply by reading your comments Ina professional envranment, comments are vital ta the success ofthe code and ultimately, the company. an organisation, many programmers workin teams alongside engineers, other developers, hardware analysts and so on. IFyou're apart ofthe team that’s ‘writing @ bespoke piece of software forthe company then your comments help save alot of time should something go wrong, and another team member has to pick up and follow the trailto pinpoint the sue. Place yourse'n the shoes oF someone whose jb itis tofind ot ‘what's wrong with a program. The program has in excess of 00,000, lines of code, spread across several ifferent madules. You can soon appreciate the reed foralitle help fom the original programmers nthe form oF good comment. The best comments ae always concise and link the code logically, detailing what happens when the program hits this ine or section YYoudor’tneedto comment on every line. Something along the lines of ifxe-0 doesnt requiceyouto comment that ifx equals zero then «do something that's goingto be obvious tothe reader. However, Fx equalling zeros something that drastically changes the program for the user such as, they've run outoflves, then it certainly needsto| ‘commented on. Evenif the code is your own, you should rite comments asf you were goingto publi share it with others. This way you can return| tothat code and always understand whatt was you did or where it was you went wrong or what worked bilan ‘Comments ae gaod practise and once you understand howto adda comment where needed, you soon dota if it’s second nature C++ COMMENTS ‘Commenting in C++ involves brief examples but this is how they work. ESTTE DD Usioa the Helo world code as an example. you can easly comment on different sections ofthe code Using the double Forward slash Uy fest C+ progean cout << “Hello, world!\n": Finciae ‘using namespace sti tnt main Br fee eee sitters Pe (Using Comments ci 19a double Forward slash /, ora Forward slash and an asterisk, '/*. You've already seen some Be careful when commenting, especialy with block comment.’ ery easy to forget to add the dosing asterisk and forward slash and thus negate any code that fallsnside the comment block However youcan ao add comments tthe end Suere of a line of code, to describe in a better way what's going on: cout << “Hello, world!\n"; //This Line outputs the words ‘Hello, world!”. The \n denotes @ new Line. Note, you don't have to puta semicolon at the end oF a comment. Tiss because I's tnein te code that's ignored bythe comple. PEPE You can comment outseverallines by using the Forward slash and asterisk 7/7 This comment. can cover several Lines without the need to add more slashes */ _Justrememberto finish the black comment withthe oppaste ‘asterisk and Forward slash. a wubampubiatonscam BRTEED Ob vousyyityou try and buld and execute the code itertors out, complaining of amissing curly bracket to finish off the black of code. IF you've made the error afew times, then itcan be time consuming to go back and recy. Thankfully the colour coding n CodeBlocks helps identity ‘comments from code, ESTEE "you using black comments, it's good practise InC¥+ to addan asterikto each new line ofthe comment block. This alo helps you to remember ta close the comment biock of before continuing with the code: 7 This coment can 7 cover several lines * without the need to add more slashes */ reconieecoont IE ) C++ Fundamentals 12 Variables Variables differ slightly when using C++ as opposed to Python. In Python, you can simply state that ‘a! equals 10 and a variable is assigned. However, in C++ a variable has to be declared with its type before it can be used. THE DECLARATION OF VARIABLES You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can declare, Here's how It works, (Open up new, blank C+ file and enter the usual You can build and run the code bukit won't do ED oennsces Bee ‘much, other than store the values 1Oand 5 to the ae integers and b. To output the contents ofthe variables, add using nanespace std; cout << a; cout <= "\n?s int main a rE : uit << bs ‘ing nenopece a The cout <<" part as aetar 3 simply placesa new ine between the outbutof I‘ toands. we sme masa () ee BETTER Seertsimpleby eating twovariables, and, with BRIMPBB naturally you can declare a new variable, call it fone having a value of 10 and the other 5. You result and output some simple arithmetic: use the datatype into declare these variables. within the curly ‘ brackets, enter: ima result = a +b; into; cout << result; — ut ats — fren cere Insert the above into the code as per the screenshot bes; BPTI You canassigna value ca variable as soon asyou declare it. The code youve typed in could ook like this, nstecs int @ = 10; int b= 55 int result = a +b; cout << results ED SS crncionteesseine neem int © C10); int 8; hen, fram the C++ 2011 standard, using curly brackets: int result foxb}s FED vou can create alot es, which ae variables that are declared outside any function and used in within the entire code. What youve used soar are bles used inside the Function For example include using namespace std; int StartLives = 3; int main © t stortLives = StortLives = 1; cout << Start ives; Variables he variable States, able, In game, for ample, FED the previous se whichis global player’ ives 0 up or down depending on how wel or how bad theyre doing, When the player restarts the game, the StartLives return tits default tate: 3, Here we've asigned 3 ives, then subtracted 1 leaving 2 ives lef, BID the modern c++ compilerisFarmore intelligent than most programmers give credit. while there are numerous datatypes you cand you can fi auto Feature efor vari #include using namespace std; auto pi = 3.141593; int rain { double area, radius = 1.5; ‘area = pi * radius * radius; cout << area; FERED 4 coule of new elements here: Fst, auto won't work unless you goto Settings > Compiler and tick the box labeled "Have Ge Follow the C++11 SO Ce* Language Standard [std=c++1Y. Then, the new datatype, double, which le-prcision Floating poin value. Enable C=+11,then bile andrun the code. The result shouldbe 7.05858, ) C++ Fundamentals) Data Types Variables, as we've seen, store information that the programmer can then later call up, and manipulate if required. Variables are simply reserved memory locations that store RSet ees Ue ea Renae lected 124 THE VALUE OF DATA “There are many cfferent datatypes avalable forthe programme In Cre, suchas an integer, floating paint, Boolean, character and so on.’ widely ccepted that there are seven basic datatypes often called Primitive Builtin Types: however, you can create your own datatypes should the need evr arise within your code “The seven basie datatypes are: aade Se?) Gens Coa Double Floating Point Ce iii No Value “These basictypes can also be extended using the Following modifiers: Long, Short Signed and Unsigned Basically his means the modifiers can expand the minimum anc maximum range values for each data type. For example, the nt dat type has a default value range of 2147483648 to 2147483647, fair value, you would agree, Now ifyou were to use one ofthe modifiers, the range alters 020 4294967295 2147483648 102147403647 32768 to 32767 £065,535, Signed Shor. nt =-32768 to 32767 147493647 to 2147483647 147483647 to 2147483647 204290967295 Naturally you can get away with using the basic type without the ‘modifier, as there's plenty of range provided wit each data type. However, is considered good C++ programming practise to use the modifiers when possible. There ae issues when using the modifiers though, Double represents a doublefloating point value, which you can use For incredibly acurate numbers but those numbers are only accurate Upto the fifteenth decimal place. There's als the problem when using nanespace std; double PI = 3.141592653589793238463; int rain { cout << PIS y » 3 | double Pr 5 tnt maint) 6 7 cout << Bs * s 0 Build and run the code and as you can see the autputisonly 3.18158, representing cou’ limitations inthis example, You can alter the code including the aforementioned cout precision Function, fr greater accuracy. Take precision athe way upto 22 decimal places, with the Following code: include using nanespace std; double PI = 3.141592653589793238463; int rain { cout .precision(22); cout <« PI; ¥ Stathere | Oatatypescpp i finciads using namespace std; typedef int metres; Aint waing t metres distance; distance = 15; cout << “distance in metres is: << distance; This code w ‘Then in the main cade block, there's anew variable caled distance, vihich isan integer sa you're basically telling the compiler tha theres another name for int. We assigned the value 15 to distance and displayed the output: distance in metres is 15. Iemightsaunda litle confusing ta begin with but the more you use (C++ and create your own code the easier ie becomes, ) C++ Fundamentals) Strings SS Tee es) eed eWeek ce Une Le RAL ees eel DC Bole) a could have a universal greeting in your code ‘Welcome’ and assign that asa string to be called up wherever you like in the program. STRING THEORY ‘There are different ways in which you can create a string of characters, which historically are all carried over From the original Clanguage, and are still supported by C++. Tocreasngyousse ech factin Ooene ERTIES outs sndnnthe code and ween snes oe new C++ file and begin with the usual header: Sie ‘onthe screen. While this is perfectly Fine, it's natasing sing alas which defines cet that an be represented asa stream of characters and does need to be terminated tke an array. The code can therefore be represented as: #include using namespace std; a #include o using namespace std; ¥ int main © [Qajorson gsyrece, £ [re e[ial 211 Sedo b>, ‘char greet] = “Welcome”; cout << greet << \n"; BRTESED 5 e0syt0 confuse string with an array. Here'san BRUNI in c++ there's als a string Function, which works in aay, which canbe terminated with all character: ‘much the same way. Using the greting code again, ‘include aenemn Using namespace. stds include using namespace std; Ant rain © 1 ‘int Lengths string greeti = “Hello”; string greet2 =“, world!"; string greet3 = greeti + greet2; length = greet3.sizeQ; cout << “The Length of the combined strings is: * << Length << “\n"s } Uso the avlable operations that ome wth the BRED oi incon oucon manus theconersofa string. For example, to remove characters rom sting you coud ue: #include using namespace std; int rain © { string strg “Here is a long sentence in @ string cout stra. cout: erase (10,5); << strg G++ Maths POP ei ere ncaied built:n scope for some quite intense maths. C++ has alot to offer someone who CCN arene ue oie a een ede tae relatively simple. 128 C++ =MC? ‘The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++ Math Library, you can also calculate square roots, powers trig and more. 14's mathematical operations follow the same patterns a those taught in school, in that muliliation and dision take precedence over addition and subtraction You can aler that though. For now, create anew file and enter #include include using namespace std; int wain © cacy ajar mara sr include include using namespace std; int wain © float nueber = 134; cout << “The square root of “ << number << is: “<< sqrt(number) << “\n?; Herewe rested anew float caled number and Siaru used the sqrtinumber) Function to display the squire oot 34, te vaio thesaiale, number auld andrun (C++ Maths of numbers an be done wi ED ecustna #include include using namespace std; int nain © float nunber = 12; cout << number <<“ to the poner of 2 is * << onCnunber, 2) << *\n" cout << number << “ to the poner of 3 is * << Poncrunber, 3) << “\n"; ‘cout << nunber << “ to the power of .08 is “ << ponCnunber, @.8) << “\n?; PID ese we created afloat called number withthe value oF 12, and the powivarable, power) is where the calculation happens. OF course you can ealulate powers and square roots without using variables. For example, pow (12,2) ‘outputs the same value a the Fist cut nen te code, FERETD he valuc of Pic also stored in the cmath header Library. tan be called up with the M PI Function. Enter cout << M_Pfinto the code and you get 3.14158; or you can se eto calculate: #include include using namespace std; int rain © { double area, radius = 1.5; orea = MPI * radius * radius; cout << area << "\n"; Ree eM Deuce et na terete sc d Se ee esr eee eee eee ese ee ies Deemer enn DOS cele ureter om Cee eens and output are all covered inthe ieee mis to understand how a C++ program Dae sore) that personal touch with improved user Petter ON tere me —— —_—<—$—$ ) C++ Input/Output) User Interaction SS Cc eect ce a nN em DeSean tea mae Meee AA ERs RRL Re keoM Me Me MULE Re [kee TL HELLO, DAVE You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard Input stream, to prompt a user response, BEER trina that you want the usertoinput into the RARE) The cin command works inthe opposite way from program needs ta be stored somewhere inthe the cout command. Wehthe First cout ine you're system memory, soit canbe retrieved and used. Therefere, ary _cutputting "What is your age’ to the screen asincicated with the input must Fist be declared as variable, sol’sready tobe used by _chevrons. Cin uses opposite Facing chewrons indicating an input. The the user. Start by creating a blank C++ ile with headers inputs putinto the integer age and called upin the second cout command, Buld and run the code. Fineluae ‘using namespace sta ane main 0) a ESTEE RD | you're asking a question, you need to store the input asa string; to ask the user their name, you would use i ESTED) The datatype ofthe variable must alo matchthe using manespace stds type of inputyou want From the user. For example, to.aska user their age, you would use an integer tke this: = — #include > names { cout << “\nHello, “ << nane <<“, I hope you're int ages nell today?\n"; cout << “what is your age: “; + cin >> age; =< iam cout <<"\nYou are“ << age’ << years old.\n"; = using namespace std; int rain © { ‘int num, num; cout << “Enter to whole numbers: cin 95 num >> rund; cout << “you entered * << num << * and * << umd << Nn? PETE DD Licwise, inputted data can be manipulated once you have stored ina variable. Fr instance, ask the ser Fortwo umbers and da same maths an them: include using namespace std; int rain © { float num nu cout << “Enter tno numbers: \n"; cin >> um >> nun2s cout << num <<“ + uml + rund << “\n"; << numa << * 4 (_ User interaction ci BRPTD wile cin works wellfor most input tasks, does ve aliitation, Gn always considers spaces asa terminator soi's designed for ust single words not multiple words. However, getline takes cinas the fist argument andthe variable as the second #include using namespace std; int rain © { string mystr; cout << “Enter a sentence: \n"; getlineCcin, nystr); cout << “Your sentence is: characters tong.\n"; ¥ “ ce mystr.size() << Sui «with spaces. when you're done the code reads the number of characters. I you remove the getine line and replace t with in >> mystr and try again, the result splays the number of characters upto the Fist space. FETED DD Cetin is usualy a command that new c++ programmers Faget to include. The terminating white spaces annoying when you cat igure out why your code lest working, I shor, it's best touse getine(cin, variable) in Future: #include Using nanespace std; int rain © { string none; cout << “Enter your full mane: \n"; getlineCcin, name); cout << *\nHlello, << name << *\a"; eeomecoimnt CT ) C++ Input/Output) ey Character Literals In C++ literalis an object or variable that once defined remains the same throughout Re eer cm ent ie ere eet ee UN been using at the end of a cout statement to signify a new line. ESCAPE SEQUENCE When used in something like a cout statement, character literals are also called Escape Sequence Codes. They allow you to Insert quote, an alert, new tine and much more. FETTER estes new ++ Fileand enter the relevant headers include using namespace std; int rain © { ‘cout << “Hello, user. This is how to use Vrquotes\”."; You've already experienced the \n character Uteral placing a newline wherever t's called. The ine: cout -<"Hello\n” <<"ma Ce4\n" <<"Program\n"; outputs three lines of text, each starting after the last. Theres evenacaractr teal hat can rage an Suz alarm. in Windows 10, it’s the notification sound that chimes when you use\a. Try this code, and turn up your sound, #include Using nanespace std; int nain © { ‘cout << “ALARM! \o"s iw +] - Character AHANDY CHART “There are numerous character literals, or escape sequence codes, to choose from. We therefore thought it would be good For ‘you to have a handy chart available, for those times when you need to insert a code, ESCAPE SEQUENCE CODE Res Ba Single Quote Peter eetorecen ce en food So cl Tab fertical Tab fiers woe Unicode (UTF-8) Woven Unicode (UTF-16) UNICODE CHARACTERS (UTF-8) Unicode choracters ae sym are standard across x alllatforms. For example, the copyright symbol, that ered keyboard by entering the Unicode code followed by ALTSX. 2 fies > copyright symbol enter ifinclude using namespace std; int main © { cout << “\u00A9"; UNICODE CHARACTER TABLE list ofthe avaliable Unicode characters can be found at wwwainicade- table-com/en/. Hover your mouse over the ) C++ Input/Output » Defining Constants Constants are fixed values in your code. They can be any basic data type but as the Pee eet ia Ua enme nae ela renee Mean e) FeO ine ene ct em ecco eee Reon #DEFINE ‘The pre-processors are instructions to the compiler to pre-process the information before it goes ahead and compiles the code. #include isa pre-processor as s #define. FATED ¥ou can usethetdefine pe-processorto define ary EATEN Note the capitals for defined constants, t's constants you want in our code. Start by creating 3 considered good programming practise to define all new C++ file complete withthe usual headers: constantsin capitals. Here, the assigned values ae 50, 40 and 60, so lets callthern up: include omens sinelovarctortos a ieee . teetre LENGTH 50 foci MOTH 48 a define HEIGHT 6 = int main O = Do] tinclade { ———— cout ce “Length {s:.* using namespace std; ‘define PI 3.14159 int rain © { ‘cout. << “The value of Pi is: * << PI << endl; Defining Constants ci Another method of defining aconstantis withthe const keyword. Use const together with a datatype, variable and value const type variable = value, Using Pas an example: include using namespace std; int rain { ‘const double PI = 3.14159; cout << “The value OF Pi is: “ << PI << endl; Because yout sing cons within the main blockoF Siz code, you need to Finish the line with a semicolon. You canuse eter ang asthe nes and lus dot clash, But iCsworthmentining that define reqies no memory so youre Coding to asetomount of memory, tefne your best bet Const works in much the same way as #define You can create static integers and even newlines: #include using namespace std; nt rain 1 ‘const int LENGTH = 50; 40; ‘const int WIOTH ‘const char NENLIN ‘int area; ‘orea = LENGTH * WIDTH; cout << “Area is << area << NEWLINE; ¥ tecomecoinm nt Ci BED ostxioue) File Input/Output eee ie mr comer et cieueaa ent output Functionality. However, to be able to read and write From a file you need to el Ere eee) eet FSTREAMS “There are two main data types within the fstream library that are used to open file, read from it and write tot; these are cofstream and ifstream. Here's how they work. Trefatinkstoceneanewcefieadsore TRAE wevercttedconmens nthesceensetot en Sue" with the usual headers you need to include the new Sie 2 to help you understand the process. You created feeambendec a.tringcaled name, tore the ses mputtedname, You ao Gated text fe ced area th he steam nei and ‘rewile.open tines), asked the user for their name and stored it and then writen the data to the le, #include include Using nanespace std; int rain © (nciode finetede include > age; “ include windows. using namespace std; int rain © t ‘string word; ‘ifstrean newfile (*C:\\users\\david\\ Docurent's\\Cirmeria. xt"): ‘cout << "Ctnmeria, by Robert E Howard: \n” << end while Cnewfile >> word) 4 cout << word << endl; Steep(1008); return 0; FED vou can manipulate the while statement to display aifferene results depending on what code les within the loop. For example, to reac the poem, Cimmeria, word by word, youwould ented include using namespace std; int rain t string word; ‘ifstrean newfite (*C:\\users\\david\\ Docunent s\\Cinmeria. xt” ‘cout << *Cinmeria, by Robert £ Howard: \n” << endl; while Chewfile >> word) 4 cout << word << endl; ? return 0; FEPITD sice20 works io miliseconds, so Sleep(1000) ‘one second, Seep(10000)isten seconds and so ‘on, Combining the sieep Function along with the header it needs) anda while loop enables you to come up with some interesting countdown code. #include include using namespace std; int rain ‘ int a= 10; while Ca != 0) 4 cout << a << endl; a=0-1; Sleep(1000); 2 ‘cout << *\nBlast OFFI" << endl: return 0; ‘The Complete Coding Manual 144 Pie i enn nc et iio structure is different. A For loop is split into three stages: an initialiser, a condition and an incremental step. Once set up, the loop repeats itselF until the condition becomes false. LOOPY LOOPS. ‘The initalise stage of a for loop is executed only once and this sets the point reference for the loop. The condition is evaluated bythe loop to seeifit's true or False and then the increment is executed. The loop then repeats the second and third stage. EEE ieate anew Cr4 fle, with the standard headers: After the loop, you created a compound statement, In races (curly brackets), that displays the current value ofthe integer num. Every time the for loop repeats ital, the second and third stages ofthe loop, tadds 1 untilthe conchtion <30, Is false. The loop then ends andthe code continues, ending neatly include cout << *Namber: << nim << ends ——_ 2 using namespace std; return 0 a : t ‘//For Loop Begins ERED Working through the process ofthe for loop begin bycreating aninteger called num and assigning ta value of 1, Next, set the condition, n this case num being less than 30. The last stage is where you create the increments; here it’s the value of num being added by 1, [' for( ime num = 1; mum < 30; nan = mum 41) ‘BOM Manual Series Vlune 17 for( int @= 10; a != 0; a=0-1) 4 cout << a << endl; Sleep(1000); ‘cout << *\nBlast OFFI" << endl; return k the countdown code, don forget to nc Heresa of aforlaop dling the Suze the windows.h library, so you can use the Sleep Sue) ‘multiplication tables of a user inputted number ommand. Build and runthe cade; nthe command console you can Handy fr students See the numbers 10to1 countdown none second increment, until it reaches zero and Blast OF! appears t int nj cout << “Enter a number to view its tines table: *; for Gnt t= 4; i 12; +i) £ cout using namespace std; int rain © 1 um with The code inside atleast once, then the conditions 1 _ ESTED) Gesinwithasimpte number 4 ‘int num = 35 0 4 cout << “Number: “ << num << endl; rum = num + 1; 2 while Chum < 305 return 0; ' EE cots ana seres-volur BETTIE you want code to add up user inputted nu Lntilthe user enters zero ‘ float nurber, sum = 0.05 cout << “*#¥* Program to execute @ Do. hile Loop continuously ****" << endl; cout << “\nknter @ to stop and display the sum of all the nunbers entered\n” << endl; cout << “\n- An << endl; dot cout<<"\nPlease enter a nunber: ciro>nunber; sun += numbers : whileCnunber != 0.0); coutce? Total. sum of all numbers: “< Tistestexlined when ou sea number BORER i's going on herr Tobegh an integer ced tose conan rumss ested on assaned wah eval 1 The statement comes ns andinthiscare we've sittedthe — Codethat te condison tev, of rum sles thon. then the 7 tose thn the bers shou be ened if C num < 30) : corm cout << "The number is less than 30.” << endl: {COULTEEITVALUSTORNOMDEONSERSESEINMIESSICNALS | PRIM 1 ‘using namespace std: _— int main () es ; EEE) cots stanatseres-votune 17 BSTESED Wren you change the vaueto anything 30, then build and run the code, you can see that the only line to be outputted to the screen ithe second cout statement, displaying the current value of rum, This s because the inital statements false so itignores the code within the braces. PPFD You can include anif'statement withina do loop For example: i Foat ten; 0 4 cout << "\nEnter the temperature Cor 10000 to exit): * << endl; cin >> temp; if Ctenp <= 0) a cout << “\nBrrer, it’s really cold!” << endl + if Cteno > 0.9 cout ) Loops and Decision Making IF... Else Statement There is a much better way to use an if statement in your code, withif... else. If... else Perum ea ee meee ccucr ten er ea keels MNase Ree RN eel Leet R Co IF YES, ELSE NO ‘There are two sections of code that can be executed depending on the outcome inanif visualise once you get used tots structure. «else statement. t's quite easy to PEPER cesinwithanewcs+fleandthestandardheaders: [RMB the Fist ine in the code creates the integer called ‘pum and givesit a value of 1. The statement include checks toseethe value of num sles thanthity and isle using manespace std; = outputs “The number sess than 30 othe consol. int rain © i 3 4 yom - ; fm STR er Sn hn 8 ch ‘The else companion tof checksf the number ERED te scconecoetom eitsatemententne ALE ores so ants ther elas To Gitte ‘uberis greater than 30" tothe console and nally, the codes a terminated satisfactorily. ‘int num = ihe number is Yess then 30!" ec ena; ‘if C num < 30) a cout << "The minber is Less than 30!" << he mates arte tan 361 30) 4 cout << "The nunber is greater than 30} << endl else if (num 4 endl 3 return 0; 30) cout << “The nunber is exactly 301” << FREED te new adcition to the code is what's known 25 8 rested if. else statement This allows you to check far multiple conditions. in his ase, ifthe user enters arumber less than 30, greater than 30 r actually 30 sel, cifferent outcome is presented to them, ESTED You cn ake thisupanotch and cesteatwoplyes umber guessing game, Begin by creating the varables ‘int num, guess, tries = 0; ‘cout << ***¥** Two-player number guessing gane a ‘cout << “\nPlayer One, enter a nunber for Player Two to guess: “ << endl; ‘cin >> num cout << string(S0, ‘\n"); The cout stra, Vine erste seen Su! Player Two doesn't see the entered number. Now ancrete ado loop footer hile do 4 cout << “\nPlayer Two, enter your guess: * cin >> guess; triest3 Uf (guess > nun) 4 cout << “\nToo High!\n" << endl; r else if Cquess < num { cout << “\nToo Low!\n™ << endl; y else if (guess { um) cout << “Well done! You got it in * << tries <<“ guesses!” << endl; y ¥ while (guess 1= nun) return 0; Grab a second player, then bull andrun the code Player One enters the number tobe guessed, then PlayerTwo can take asmany quesses.as th reed to get the right umber. Want tomake itharder? Maybe use ‘decimal numbers Else Statement a dade s{ Programming Programming with the FUZE Sa ca Ee Chto aca ena oe eset eeu eect PORE esas Ua i Cac cual Dee eee Chun ad students, teachers and enthusiasts to peer Ee euaruc nc) Se eu oc De eee ney the UK, the FUZE is the perfect EES Canaan case Pee eeu eee education, all presented in a cleverly designed retro-themed keyboard case. CT ecu aed with its own programming language: 4-7 Nome aad you're able to create simple routines, games, and complex algorithms Pree Tac) Cr crest e Readiris See Programming with the FUZE The FUZE Project is a learning environment that's built around the Raspberry Pi and a custom programming language based on BASIC. The FUZE Workstation is the hardware side of the project, incorporating a Raspberry Pi inside a stunning retro-themed case, complete with a full-sized keyboard, IO board and connectivity. The software side is FUZE BASIC, available for both Windows and as a boot image for Raspberry Pi models 2 and 3. Introducing the FUZE Project Setting Up the FUZE Dee ees eee en htc ka ea tanen atc roe en ea sel ahem ald mee ureh em av el) the Raspberry Pi 3). Before you begin though, let’s see how to set up the workstation, LIGHT THE FUZE Cetting the FUZE up and running sas simples plugging ina standard desktop computer butts always worth running through the process For those who don'thnow what to do, 1u power up your FUZE, make sure that the or now, use the Ethernet port, LAN cable, forthe ‘connection tothe home network nd ultimately reariO backel the outside world You can setup the WiFi buts always easier to ‘ards already inserted but cepending on establch a wired connection Fs i ‘Connectthe Ethernet packaged, the electronics kt box. cable to reariO backplate ofthe F wm. ‘monitor arf your exsting manitor (TV) Next, open un the bax containing the mouseand plug an support more than one HOM mes witha qualty HDMI bag and cannect ane end tothe HOM porcon the ofthe FUZE andthe otherto the rear ofthe mor itinto one ofthe USB ports onthe rearlO ofthe FUZE Setting Up the FUZE ining the power pack and plug |Fyou want the W 2 and inalyto the 0 ent desktop presen tly Programming with the FUZE Getting Started with FUZE BASIC BACK TO BASICS Let's begin our programming journey with FUZE BASIC, an environment where you can create anything from simple scripts to.complex ‘games with graphics and sounds. HED \Fyoure using a rkstation, then FU just Eee ‘The retro style int ingle ckaway. See the secand Fin the bottom ight themes thatyou panel, the one that's colouredwhiteonared background Clickit,and taste. Thedefautview sthatof a voulliaundhthe Fu complete witha Céa-syleretrahterface. ferent view presthe Insert ky to ele throu ;oucan alo double clckthe FUZE BASIC V3 icon onthe desktop. Interfaces. Youline doubt recognise some of them, sofindone youtke, ee EEEED the screenyou'te looking at ows calledimmediate Mode; pressing te Enter key wl cursor where er, then type Hello ‘onthe seen vl display and the Raspbery Fi (since it'already running ona RP). you can start enter code Tr this browser to wir Auze.o.uk/download fuze html ang Follow the teverjone and press Enter again, The ou lownlaad instruction ASIC For Windows andthe tep-by- whatever youve typed int the quotation marks Getting Started with FUZE BASIC rine 10 + 20 + 30, and pres The sumofthe numbersyouve aqucklsting to ask for user input. Enter this enteredwill now be displayed onthe screen, inthiscase the number 4@ cls 60. Try mare numbers and eve different mathematical symbal 2OHnGUS MRCS CURRSPLSTTES 30 print 40 print “Hello *; nf Enter ron toexecute the code previous code, screen [CLS], ther ingthe inputs the viable n§. The oni also capable of toring ver ea jookat in asking Foruserin more depth nthe next tuto Print a line 30 puts bl ne screen, whistthe Print each line ‘command at line 40 dsplaysthe message Hel Loand the contents of =e thevarisble nf Print @ of computing, you ne doubt emember that cading working nthe Program Ector. Te enter the Program Elta ype inthe came with ine numbers. FUZE BASIC works the same way. WhistsUll__command new to clear any ragrams already storedin memory and in immediate Mode, eter press the FZ key. As you can see, Program Edt looks significantly 1@ print “Hello” {ferent to immediate Mode 20 goto 10 Now enter run, The word Hello shoulé now cycle down the screen Programming with the FUZE Coding with FUZE BASIC - Part 1 LET THERE BE VARIABLES We've already looked at assigning some vaiablesin the previous tutorial so let's extend that and see what else we can do with them. Enter the Program Editor, by pressing the F2 key. ED Press F2 to enter Editor mode and cick on New. Now Within the Program Ector enter te Following, let's expand onthe simple code. Enter the follow pressing Enter ater each ine: eg Let x=10 Let ya20 Print x Let 2-30 Now lek on the Save button, along thetop ofthescreenandsave Print x+y +z the program as Variabes1’Clckthe OK buttontoreturntothe _Saveas'Varables? and Runit. You now have the Editor and the Run button to execute the code, the screen you've assigned X,Y and Z with num Printed the total tof 600n value Ereey Dp what ®ve wantedto change the value ofa variable? Enter thisisting Let x10 Let xex-1 Print x feMode TobeginwithX equalled 10 butthe next tine subtracts 1 making it avn thssimpe code, youve created the variable called X you'veallocated the value 10 tot. The secand line my prints the ‘urrene value of X—which is oF course, 10.

You might also like