100% found this document useful (3 votes)
958 views194 pages

2020-05-01 The Essential Coding Manual

Code is everywhere, and by understanding it we can better understand the growing digital world around us. The Essential Coding Manual aims to help you get to grips with coding.

Uploaded by

nelu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (3 votes)
958 views194 pages

2020-05-01 The Essential Coding Manual

Code is everywhere, and by understanding it we can better understand the growing digital world around us. The Essential Coding Manual aims to help you get to grips with coding.

Uploaded by

nelu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 194
be eg eeaeS en THE COMPLETE Coding MANUAL @ Learn to Code @ Projects &ldeas @ Develop Your Skills Packed with | Learnthe LearnC++ | Windows 10 Aco) octal MM CTA C(O Col Ct Ld Politely of Python coding and projects Black Dog Media Master Your Tech To continue learning more about Your Apple tech visit us at: www.bdmpublications.com fare ae} Print & digital editions Featuring the very latest updates Step-by-step tutorials and guides Created by BDM experts Check out our latest titles today! ; a NY SPECIAL DEALS and Bonus Content \ aad ‘Sign up to our monthly newsletter bdmpublications.com/ultimate-photoshop and get the latest updates, offers aa ec ets eu alee R Cur and news from BDM. We are here Reem ene mace ea Ree ters to help you Master Your Tech! ' BDM’s Manual Series THE COMPLETE Coding MANUAL Engineer your Future; learn to code! COR ia a Us Te orn car, power up the washing machine, whatever Poca Deus Mc aa ad Pa BS Tes or object contains some form of code. From ron BO ei Ean eR Gea ppnntaenerenens Reset queen eu Pet ont cue arc a a happens. And you can learn how it all works. Peeheers Coding requires patience, imagination and great Cee en Radice Raced} happening when you enter the code. The Complete Coding Manual’ See Ceo ee ee ane ad Ce uta eae eat cese eer eerie aes BCU eM t ea nu Re a Coo RR OU os e neu CUM tes Peed fc ee acerca 8 ABrief Hi ing 10 Being a Programmer 2 ing a Programming Language ing a Coding Platform InNumbers thon? tting to Kno How to Set Up Py How to Set Up Py pee err Starting P Your First Cade uting Your uting Code from the Command Line Numbers and Expressions Using Comments Working with Variables User Input ting Functions ditions and Loops ules Python Errors, mbining What You Tuples Dictionaries Splitting and Formatting Strings Date and Time What Far (05 Module Random Module Tkinter Module Pygame Module wn Modules Up C++ ona Mac + in Linux tonstall Your First C++ Program Structure of a Cr+ Program Compile and Exec Using Comme ariables Strings CH Maths | Defining Constants File Input/Output ex: y NY 442) Loops and Decision Making While Loop For Loop Do... While Loop Batch File Programming Loops and Repetition Creating a Batch File Game Tracking the iss Using Text Fil jing Mista hon Beginner's Mistak inner's Mistake: _ foe ene aren a Foundations \ (Coding Foundations ¢ OR kets Coco Aes iets CE Cust ce) Pe eau uly unlimited number of tools to help MEU MCS RUS a RR ard In this section, we look at what you will Ree ena ee eeu ee ures Pee eas so hours, learning how to code correctly ee tea Mace) little help, you can master the basics and start your coding journey. oa ew bampubtiatinscom A Brief History of Coding Tecoma nee eT cetage ten isa modern concept that's only really happened in the last fifty years or so. However, that assumption is quite wrong, coding has actually been around For quite some time. Oe RRR RRR R MRC OR CXR ROOK Essentially al forms of coding are made up of ones and zeros, on or off states. This works Fora modern computer and even the oldest known computational device. oe, Cree ea ae aeasE a ego there significant advances Cee on ter erecta Ce Coes oe es ern ent er ene eee) eet) ee ema lca ey ene) Cece at ea Doan) Ceara eee but was made amousby Alan een eee ear eed reeereteesiarey ae aera retin ani Bo Pete ene aan Python seer eee ees roach orien frenetic nme tani pre eaetatern ay aor Hels See ae enn Serta cc) eet mtd pomeranian Ree tea errers Pesan eed source ather code to improve thelr own. Sete ge erie Peeters eas es eter Pete ies aaa eerie a) and ALGOL 58 were developec. Renan ee eens Eto eeaa developed a compiler frit. time, Bae et ened Cea ok cee ey peo eaten ete careretarerey Being a Programmer Deen ee een one eC Ce em erat aha creates code. What they're creating the code for can be anything from a video game to a critical element on-board the International Space Station. How do you become a Puna mu dempubliatonscom ‘Times have changed since programming in the“80s, but the core values stillremain. “It’s up to you how far to take your coding adventure!” Being able to follow logical pattern and ‘an end result is one ofthe most valued ski of a programmer. (. Being a Programmer ei MORE THAN CODE For those of you old enough to remember the'80s, the golden era of home computing, the world of computing was avery different scene to how its today. &-bit computers that you could purchase asa whole, s opposed to being in kit Form and you having to solder the parts together, were the stuff cof dreams; and getting your hands on one was sheer bliss contained within large plastic box, However, it wasnt so much the new technology that Computers then offered, moreover It was the fact that fr the ist time ever, you could contro what was being viewed on the ‘television, Instead of simply playing one ofthe thousands of games available at the time, many users decided they wanted to create their own content, their ‘own games; or simply something that could help them with their homework corhome finances. The simplicity ofthe 8-bit home computer meant that creating something from a ew lines of BASIC code was achievable and so the first generation of home-bred programmer was born, From that point on, programming expanded exponentially. It wasn't long before the bedroom coder was thing ofthe past and huge teams of esigners, coders, artists and musicians were involved in making a single ‘game. Ths of course led to the programmer becoming more than simply someone who could Fashion a sprite on the screen and makeit move tthe press ofakey. ‘Naturally, me has moved on and with the technology that we use. However, the Fundamentals of programming remain the same; but what exactly does ittake tobe a programmer” “The single most common tat of any programmer, regardless of what they'e doing is the ability to see a logical pattern. By this we mean someone who can logically Fellow something From stat to Finish and envisage the intended outcome. While you may not Feel you're sucha person, tis possible to train your brain into this way of thinking Yes, t takes time but once you stat to thinkin this particular way you will be able toconstruct and Fallow code. Second to logicis an understanding of mathematics. You donit have to be ata genius evel ut you do need to understand the rudiments of maths ‘Maths s all about being able to solve a problem and code mostly falls under the umbrella of mathematics. Being able to see the big pictures certainly beneficial forthe modern programmer. Undoubtedly, asa programmer, you wil be part ofa team ‘of other programmers, and more than likely art ofan even bigger team of designers, all of whom ae creating a final product. While you may only be expected to create a small element ofthat Final product, being able to Understand what everyone else is doing wil help you create something that’s ultimately better than simply being locked in your own coding cubicle. Finally there's also level of creativity neededto be a good programmer ‘Again though, you dont need tobe a creative genus, ust have the Imagination tobe able to see the end product and how the user wilt interact with it Thereis of course a lot more involved in being a programmer, including learning te actual code itself, However, with time, patience and the if 16, O00 mstocmene” shitinte 6th. Stteriit & ere RS MOST SOUGHT-AFTER re are over ron jobs posted every six months inthe UK. JOBS.IN THE UK. Python Data Science is Google ithe top Data Science, Blockchain New York and san thought to become the company for hiring Python ‘and Machine Learning Francisco are the top most soughtafeer ob in developers, closely are the Fastest growing Python developer ees the coming years followed by Microsot Python coding sil inthe world Python developers enjoy an average salary of 2 S== £60,000 Cosy) (750%) “7900 ) Cage) (95%) (75) (79%) (4%) 959 OF ALLBEGINNER 175% OF ALLPYTHON 79% OF ALL 49% OF WINDOWS i CODERS START WITH DEVELOPERS USE PROGRAMMERS 1ODEVELOPERS : ‘AND STILLUSE, PYTHON 3, WHEREAS USE PYTHON USE PYTHONS: 5 PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE AS THEIR MAIN 5 PRIMARY OR OUTDATED PYTHON 2 ITASA SECONDARY PROGRAMMING z SECONDARY LANGUAGE. VERSION. LANGUAGE. ‘LANGUAGE. g a: EP Introducing Python Why Python? Seer ie cu eure ee Cee aku Bo Ree ene eeu Reece eso et dd att are designed For scientific work, others For mobile platforms and such. So why choose Praeurtiace nieces 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 ‘actossthe screen. may not sound terribly exciting to a generation that's used to ultrahigh definition graphics and open werld, muli- player online gaming. However, fortysomething years ago it was binginaly bilan. Naturally these bedroom coders helped form the Foundations For ‘every piece of digital technology we use today. Some went onto became chief developers for top sofware companies, whereas ctherspushed the avaliable hardware tits limits and founded the billon pound gaming empire that continually amazes us. ec tar Poet ba Goh ft ne 0B a 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 canbe butt using a variety of programming languages. The languagesin use today difer depending onthe stuation, the platform the device's use and how the device wilinteract with its S vrcncereny 6 S/S CCH > CO artoe ‘satcutsor(py): ae certssenatasnteoret| He eid arrayetrL::childLonteocua) pelt rae stleurger >= 0) refresiportcursor): certTachataoneracen wold, serayeerL:paine(oras ¥) { ‘rtnEnsc Dine Eee eeetieec: beet hSStocus = Hasrocusoeep(: Gavi" oreineeetys mt te = Theor cetserotUO; 5g <,colum.catcount(); jst) { liver adorned ee Stersgrea I Yfe'a colum.cetcomt() «1 >= 0) lend(scatarmisabled, Scoloreaper): sf iStets « catcount)) stop Seeteiney il SilrPeop t stzeey) bs ibsetam = Foe P tttandoyta): << column catcaune(): 340) ( ser Sxttaban deh) 3 ‘envronment or users. Operating systems such as windows, macOS ‘andsuch are usually a combination of C++, Ci, assembly and some Form of visuabased anguage. Games generally use C++ whist web pages can use a plethora of avaliable lanquages such as HTML, Java, Python and soon, "More generat purpose pragrammingls used to create programs, ‘apps software or whatever else you wantto cal them. They're widely used across all hardware platforms and suit vitwally every conceivable application. Some operate fester than others and some ‘are easier to lear and use than others. Pythonis one such general purpose language. Python's what’ known as a High-Level Language, in that ‘tals’ tothe hardware and operating system using a variety of aay, varables, objects arithmetic, subroutines oops and countless more interactions Whist t's not as streamlined as a LowLevel Language, which can dea directly with memory addresses, call stacks and registers is benefit isthat t's universally accessible ‘and easy to lean, /F Te: twoke. java finpore. java. lang.reflect.*; class anvoke { PUTER void main string () args) ¢ try Class. forwane args(0l ) ‘pedtethod’ args], hw clase Gjeck Pee =m. snyoke ut, nuT1 9: Sj28Sn cue gesnelnt Svcs stathe method: * + argeLad 7 ofenss: S Margo eee IF. ShafsCtarnamete 5 can fand te class 1 Bech Cinsitinethodeteption 225°C 1 Gea RAR tao 9« een! Rave’ peratoston to ake hat } Egech'C xnvocacontargetexception e4 ) { Fi an excapeion ocurred while invoking that inethod System. oue.printIn¢ Shethodthren an: * +6. ‘getTargetexeaption( ”) frets i P avaisa powerful language that’s used in web pages, set-top boxes, ‘Tvsandevencars. ¢ Why Python? ei Python was created over twenty sik years ago and has evolved to became an ideal beainnerslanguage for learning 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 ofexternat hardware and the computer sel. Pythons Free to downoad, install and use ands avalable forLinux, \Windows, macOS, MS-DOS, 05/2, 0S, IBM iseries machines, and even RISC OS. thas been vated one ofthe top five programming languages in the world and continually evolving ahead ofthe hardware and Internet development curve. So to answer the question: why Pythor? Simply put i's ree, easy to learn, exceptionally powerful, universaly accepted, effective and 2 superb learning and educational tool BASIC was once the starter language that early ‘Bbithome computer users learned. Python sa more moder take on BASIC, it's easy to learn _and makes or an ideal beginners programming language. nnn CT EP Introducing Python Equipment You Will Need a Cole TaN Ta Loan VA LECT Kee ee] Oe ol nL Colt Centaies Funes oncatan curr ecient eit ese ect WHAT WE'RE USING ‘Thankfully, Python isa multiplatform programming language available 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 Windows (From XP onward) an either a32 or 64-bit processor an Apple Maco Linuxinstalled PC. AN IDE [AnIDE (integrated Developer Environment) is usedto enter and execute Python code. It enables you to inspect your prosram code and the values within the code, as ‘well as offering advanced Features. There are many different IDEs avalable so Find the one that works For you and gives the best results 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 edtorisan deal emranment to enter code int, I's not an absolute necessity, Youcan enter and execute code directly From the IDLE but atext editor, ‘suchas Sublime Text or Notepad++, offers more advanced features and colour coding ‘when entering code, INTERNET ACCESS Python i an ever evolving environment and as such newversion often introduce new concepts or change existing commands and code structure to make amore efficient language. Having acces tothe Internet wil keep you up-to-date, help you cout 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 entirely new, and you illgtthere 2 Eauipmen Youwilied THE RASPBERRY PI Why use a Raspberry Pi? The Raspberry Pisa tiny computer that's very cheap to purchase, but offers the user a Fantastic learning platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras. PGs aal ‘The Raspberry Pi 4 Model ete latest version, Incorporating a more powerful CPU, a choice of 168, 28 oF 448 memory versions and Wil and Bluetooth ‘support You can pick up a Pt From around £33, increasing Upto €54 forthe 4G8 memory version, or asa pat of kit For £50, depending onthe kityou'e interested in, uatasan The FUZE is learning environment built on the latest model ofthe Raspberry Pi. You can purchase the workstations that -ome with an electronic kit and even arabot arm For you te bull and program. You can Find mere information on the FUZE at wwwfuze.couk We have several great Raspberry Piles avaiable via wow. Lbdmpublications.com, Our Pibooks cover how to buy your Fist Raspberry setitupand use it there are some great step examples, The Raspberry P's main operating system is a Debian based Linux dstrbution that comes with everything youneed in simple touse package. t's streamlined forthe Pland isan ideal platform for hardware and software projects, Python rogramming and even asa deskton computer Raspberry Pitoo Getting to Know Python CaaS Et Mee eC Cue ee eee language on which to learn how to code, but it’s also powerful enough to be used by Cee ac at ees ach cn PYTHON POWER PEL Race ene uu er Tue Beane eo eee Lee Erin “The Python Software Foundation, a non-profit organisation devoted Ree eae cats eee eee eee) eee ren et eer renee er eae Seo eee eee Pe eee ere Pe ea ee Sree ey Penne ee eens CERRO Rach aaa Se us eee ea eed caer easy Se eee ney Cee Sees eared Penney ett) care Petrie oie eek Seren a True eer Eee ces Oe ne ere eee en te enna’ Image ofa black hole was released the supermassive back hle in Rr aaee eI eee eed Seer ere ete eg telescopes spanning the world (called the Event Horizon Telescope Coe cers eda eee ee cee eee ae ero eee te eee ters See ee ee es cluster, the team then used Python to painstakingly stitch together Se ee eee poeee econo eee es ea eee eee er ene een Perea iit ete rg is Peer tener eg eres ee ee) en te ee ee eats ways of interacting with people online. For example, when you search for something on the Amazon website you wil usually notice Sener cen ue PYTHON 3 VS PYTHON 2 mm-- Ima typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language: re Lee Read agers eee eter er pe i nn meeps Ere Soe id A ue nt ne ante ee sea i gees ie ee ee oe ee as ee ee De ee eg en a eee eens Core ae oy ee eer ane tey Cesare eer rit eee See eee Ee err) ene eta rete eer cas ene ene ee rea eee eta ere ee Neer ery thinking script that not ony displays items, news sores, books, other websites and ideas relating to what you've searched for, eee eee ere cE een cen eee en ear PU haso tater ad Ree tet ets ce Eee et eee one ea ee tot alldepends on what the developer wants from their AlPython code. Feedforward neural network r Ce nea ences ee emia sens eee eee ey Ce ee es et eee ee ee ‘etween the olderversion and thenewer Python 2s good, but ee ee i ri es Coes Renee cere ec eee Ge omers Python oraving popclanty has mest that Ws srudentta start Peer eer eerie eet ener te erates te Se this does mean le te last you see oft Many Linux distros use Python 2 ibraies, as does macOs and to be Fal forthe developers ee ee ee eg Ce i ees ee pee eae ee ZEN OF PYTHON Peery Store orca oer Pe ene eT reer ei Thisisa collection of 20 Sed Influences the design of od eee Pore etd Seu Se a ed Soa pects Peta non) Femi ine tenner ee eee eet eee ey anne ne) Paneer tetera nes Pee eer aes paneer sti? ee EP Introducing Python How to Set Up Python in Windows Mee ee WEIN Goa a eed ana eal DME Ae aN Sauna eae eat eC eI a reer Menem elem tt Ceti Meee eM Reus ae lt ailg snares INSTALLING PYTHON 3.X Microsoft Windows doesn’t come with Python preinstalled as standard, so it will be necessary to install it yourself manually ‘Thankfully, it’s an easy process to follow. Start by opening your web browser to www python, CChoasing the Customise option allows youto ‘ora/downloads). Look Fr the button detaling the specify certain parameters, and whist you may Download link or Python 3x. Python is regulary updated, changing stay with the defaults i's a good habit to adopt as, sometimes (not the lst digit For each bugfix and update, Therefore, dort worryif with Python, thankfully, nstallers can include unwanted adltional yousee Python 38, ormore, aslong ats Python 3, the code inthis Features. On the rst screen available, ensure all boxes are tcked book wll work ine and click the Next button, en eI ) options Features a 7 in jen bans Wr fore ESTEE (lckthe Download button for version 3xand ESTED Te next page of options include some interesting save the fle to your Download older When the adeiions to Python. Ensure the Associate fle with Fleis downloaded, doublecckthe executable andthe Python __—Python, Create Shortcuts, Add Python to Environment Variables, installation wizard wil launch, From here, youhavetwo choices: __Precompile Standard Library and Install for All Users options are Install Now and Customise installation, We recommené opting for ticked. These make using Python later much easier. Click instal when the Customise instalation link, you're ready to continue, J insta python 3:70 (22-bit) J advanced options our Saemtomrabs _ BE scrosticiorcom You may need to confirm the installation wth the Windows authentication notification. Simply dick es and Python will begin to install. Once te instalation s complete, te Final Python wiz rd. page wil allow you to view the some online tutor a — windows STEP 6 sire secsettita d window however i'sbest to click onthe ink next othe shield detailed Disable Path Length Limi. Ths wil allow Python ta bypass the Windows 260 character limitation, enablin execute Python programs stored in deep folders arranger Yes again, to authentiate the proces, then youcan Close the installation window © Dizable path length iit FEED windows 10 users can now find the installed Python 3.xwithin the Start button Recently Added section The ist lnk, Python 3.x (32-bit) wil aunch the command line version oF Python when licked (more en that in amament). Te open the IDLE, type IDLE into Windows start. oo ®@ Fiters \ Best match IDLE (Python 3.7 32-bit) Desktop app = search suggestions 2D idle How to Set Up Python in Windows Bead é the Python Shell where you can begin your Python programming journey, Don’t worry if your versionis newer, along asi’ Python 3x our code works inside your Python 3 interface, ‘licking on the IDLE Python 3.x 32-bit ink launch FEED you now click on the windows Start button again and ths time type: CMD, you'll be presented with the Command Prompt link lick to get to the Windows command line erviconment. Toenter Python within the cammand line, you red to type: python and press Ente ETD the command ine version of Python works in ‘much the same way asthe Shell you opened in ep 8 note the three leftfacing arrows (22>).Whistl’s a perfectly Fine environment, ts not too user friendly, so leave the command line for naw. Enter: exit) to leave and close the Command Prompt window b> Introducing 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 For this particular tutorial we will stick to Linux Mint. First you need to ascertain which version of Python Sid is currently installed in your Linux system. To begin with, dap into a Terminal session From your dstro’s menu, or Mie the CulealteTheys. davidedavid mine:~ Next enter python’ =-version nthe Terminal SUPA ‘screen, You should have the output relating to. version 2x Pthonin the dpa. Most Unux dato come th Seth Python 2 and aby def atthe’ plenty of ode ot there silovlabie for thon 2. Now enter python’ =-verston davidedavid-mint:~ File E6t View Search Terminal Help Loree Demet! faerosresnts Peng eerie Inourcasewe have both Python 2 and 3 instal. Sues ‘As long as Python 3.x. is installed, then the code in. ‘our tutorials will work. It's always worth checking to see if the distro tas been updated with the later versions enter sudo apt-get Update && sudo apt-get upgrade to update the ster on snidodavistine~ (nce he pte and upgrade completes ent STEELS) python3 =-version again to see if Python 3x is upc or eveninad sang aryounie thon ye ring temo rcent mar vere the runes ae the Indat patches ps futhe updates Often theyre unnecessy, Dut theycncontan vane elements However, if you want the latest, cutting edge version, you'll need to buld Python from source entering these commands into the Terminal: St sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev Libncursesn5-dev libssl-dev Libsqlite3-dev tk-dev Libgdon-dev Libe6-dev Libez2-dev ‘Open up your Linux web browser and goto the SEE Python download page: htps://www.python.org/ ‘downloads Click on the Downloads, Followee bythe button under the Python Saurce window. This opens a download dialogue box, choose a location, then sart the downiosd proces, @ python ee noma Inthe Termin got the Doioads oder Gary byentering: ed DownLoads/. Then unzip the contersof the domlonea thon sourcecode with at 2 python-3¥-¥:tarsaz ence the swith the ves ramets Youve downloaded, Now ethene upped fle wi fon 3.7 (Within the Python Folder, enter: Be configure Sudo nake altinstall Thiscould take awhile, depending on the speed of your computer. Once finished, enter python3.7 =-version to check the latest installed version. You now have Python 3.7 installed, alongside older Python 3xx and Python 2 (How to Set Up Python in Linux For the GUIDLE,youneed to enter te fallowing Suz) ‘command into the Terminal: sudo opt-get install. ‘a3 ‘The IDLE can then be started with the command: idLe3. Note ha IDLE runs adferent version to the one you installed From source. iden -/DomiaasPyhon 3.72 FERRET DD Youll atsoneed PP Pp installs Packages), which is atoolto help you install moce modules and extras, Enter: sudo apt-get install python3-pip (nce PiPis installed, check Fr the atest update with pip3 install upgrade pip when compete, close the Terminal and Python 2:xwillbe avalable athe Programming section inyour dsto's menu, Installation of Python on macOS can be dane in much the ‘same way 3 the Windows instalation. Simply go tothe Python ‘webpage, hover your mouse pointer over the Downloads Uinkand el ‘Mac 05X From the options. You will then be ‘uidecto the Python relasres For Mac versions long with the ‘ecessary installers For macs 64-bit For OS x 10.9 and later meen Foundations vbnpubeatons com Python Foundations RSC Say arate cee Oe a SSNs Beek Ca tay ER Cath aC le First piece of code, save it and run it in PT ass RRC Ee) ORR a MSU EC tas] ES Co) RO eeu eee time with Python. Let’s start and see Cede Para aS 34 Er Er) Po User input eating Functions ditions and Le a cents => Python Foundations) Starting Python for the First Time We're using Python 3 under Windows 10 for these Following examples. Don't worry if your version of Python is 3.4.2, or something lesser than the current version, as long as. One Lane Mc kia STARTING PYTHON ‘As when learning anything new, you need to start slow. You can pick up the pace as your experience grows, but For now, let's Just get something appearing on the screen. Don't worry, you'll soon be coding like a pro! ESTESEDD ickon the windows Startbutton,andstarttyping ERIM For example, in the Shell enter: 242 ‘ile’, The result willbe the curently installed -fter pressing Enter, the next line wil display the version of Python, IDLE (Python 3.7 32-bit for example. Youcan answer: 4. Basically, Python has taken the cade’ and produced the Pin t tothe Start fr convenience, otherwise simply clcktheiconto relevant output, launch the Python Shell ESTED The Shells where youcanentercode andseethe [ERTS The Python Shell acts very much Uke calculator, responses and output of code you've programmed since code is basicaly a series of mathematical, into Python. Thisisakind of sandbox iFyou ull where you're able interactions withthe system integers, which are the infinite to try out some simple code and processes. sequence of whole numbers, can easly be added, subtracted maltiplied, and soon. ne ¢ Starting Python for the First Time [ PRPEEM wile that's very interesting, is not particularly ESTEEM The Python Leica confiquable environment. ‘exciting, Instead try ths: you dontke the way the colours ae represented, thenyou can always change them vi Options > Configure IDLE, and clicking onthe Highlighting tab, However, we dont recommend that Just entritinto the ILE as you've donein the previous steps. as you won't be seeing the same a our screenshots. print¢“Hetlo everyone!”) Thesaltlemoetionineyaiensinchced ERE swith rogers anise elem your First bit of code. The Print command is Fairly ue! ‘operating system, there are numerous shortcut seFenpanaton tps hogs yon Sreqres the puestiess Keys We dst have oor for th alr, buch the Ops _as well ac quotes inorder to output content to the screen inthis > Configure IDLE and under the Keystab, youll see alist ofthe casethe Hello everyone bi. current bindings. >>> print(“Hello everyone!™) Hello everyone! >>| BETTER You'thave notice the colour coding within the BEPSET BD the Python ILE isa power interface, nd one Python IDLE. The colours represent diferent that’s actualy been wtten in Python using one elements of Python code. They are: ofthe available CU toolkits. f you want to know the many ins and cuts For the Shel we recommend you take a Few moments to view REC a clas Ue htps/docspythonor9/3ibrary/ile html, which deta many oF Green Strings Dark Red ~ Comments Laos Purple—Funcions Light Red— Error Messages Orange — Commands IDLE Colour Coding Green| aoe | Tari mre foe [Feces [enti pred [Erermeseege | apstacser Your First Code , you've already written your First piece of code with the print("Hello everyone!") Function from the previous tutorial. However, let’s expand that and look at Ph eee Cnr h eautace nici cs PLAYING WITH PYTHON AAs 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. yore doadeyion oieseopmtanes — ETRE vert rae tte benube se ous? a did in the previous page. In the Shell, enter the Sule? s) ‘output is the 2+2 you asked to be printed to the Familiar Fllowing screen. The quotation marks ae defining what's being outoutted rint(*Helto" tothe DLE Shell to print the total of 2+2 youl need to remove epee the quotes: print(2i2) PETESED predicted, che word Hell appearsin the shell — EWM vou can continue as such, printing 242, 46442343, as blue text indicating output froma string, t's and so onto the Shell An easier way isto use a fairy straightforward, and daesn requretoo much explanation, variable, which something we wil coven more depth later. For Nowe row, enter primtc2i2") oe bez wm broscon hae you have donehere sass theletersa Nowletsaedasuame: GES and b two values: 2 and 2. These are now variables, Sia surnane="Hayward” ‘hich cn be callee upon by Python to output, add, subtract, divide be called upon by Python to output, add, subtract, div ae and son, Fors long as their numbers stay the same, Try ths \We now have two variables containing both a first nameand 3 surname, and we can print them independently. printca) printcb), Teoupeolvelstzencsoaetecurere — EREAEB i wewereto spo nesanerotiness tore, Bere values of a and b individually, as essentially you've Sie using the + symbol, the name wouldn't appear aeledthomtobe prted separate youwanetoadsthem dp, cvrediyinthe output nthe Shel. Ty yuan ie the Following an print carb) ‘We need a space between the two, defining them as two separate Tis code takesthe value of both and b. adds themtogether, and values and not something you mathematically play around with. ccutputs the result. FED vou can play round with different kinds oF variables ERINBIRB in python 3 we con separate the two variables together with the Print function. For example, we vith aspace by using 8 commar could assign variables for someone's name: print(nane, surname) ‘Alternatively, you can ad the space yourself rane="David” printnane) print(nane+" “+surnane) As you can see, the se ofthe comma is much neater. Congratulations, you've ust taken your fst stes into the wide world of Python, Your First Code [ a => Python Foundations) Saving and Executing Your Code While working in the IDLE Shell is perfectly fine For snippets of code, it’s not designed RTC Cm eC en eM eran eet te aren ks Rem use tac ae ene ee a 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 Ecltor will allow you to save and execute your Python code, FETED Fist.coenthe Python OLE shell when t'sup, click BIBI as you can see the same colour coding isin place in the IDLE Elitor asi isn the Shel enabling you to better understand what's going on with your code To execute the cade, hawever, you need to Fst save. Press FS and youll havea Save..checkbox open. con File > New File ths wil 9pen a new window with Untitled asits name. This sthe Python IDLE Editor, and withinit you can enter the code you need to create your Future programs. ESTEE Te ILE Ecitoris forallintents and purposes,a ERTS) lick on the OK button inthe Save box, and select a simple text edtor with Python features, colour destination where youl'save all your Python code. coding and 0 on. You enter code as you would within the Shell,so The destination canbe a dedicated Folder called Python, or you can taking an example From the previous tutorial, enter just dumpit wherever you ke. Remember to keep atid filesystem, printCHetlo everyone!” though itl help you out inthe Future, os Enter aname for your cade, ‘print hell! For ‘example, and click onthe Save button. As soon asthe Python codes saved, i's executed and the output willbe etal in the IDLE Shel inthis case, the words Hello everyone! This show the vast majority of your Python code willbe conducted, Enterit nto the Editor, hit F, savethe code, and look atthe output in the Shell Sometimes things wil differ, depending on whether you've requested a separate ‘window, but essentially that'sthe process and, uness otherwise stated, thisis the method we wil use. Letsextend the code and enter a few examales From the previous tutorial: nz bez rane="David” surnanes"Hayward” print(nane, surname) print Carb) you press FS now, youllbe asked to save the fle again, asie’s been ‘maxified From before Hyd the Ox ton thee wl be verurten Sie with the new code entries, and executed; with the cutputinthe Shel snot problem wth jt hese es, but you were toed ager fle overwiing an become an sue into use le > Save As fli the or Ta ese a bck rere FERED sou open the ie locaton ofthe saved Python code, youl notice that it ends in apy extension, ‘This is the default Python Flename, any code youcreate willbe whateverpy, and any code downloaded From the many Internat Python resource sites wile py. ust ensue that the code is written Fr Python 3 BETTSET BD Now create anew file. close the Ector, and open anewrnstance Fle > New Fle fromthe Shel. Enter the following, and save as hello.py ‘o="Python” boris” "cool!" print(a, by ¢) ‘We will use this cage inthe nex tutorial. ——— Saving and Executing Your Code [ Python Foundations Executing Code From the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we na Guat the command line level Sie" ‘routine automatically included all the necessary Sime Python using the command python and pressing nec words the command ine. To begin with, clckon the Shel, with the Family, tne right Facing arrows asthe cursor (>>>). art Button, and type: end, how we can run code that was made in 1d hellospy, et’ ster the code you ED occ storevous oz printcay susan erminal in macOS, Linux, and Raspberry Pl operating systems Asyou can see, it works exactly the same Noweenter exit@ to leave the command ine ED Python sesson and return back to re command prompt. Enter the folder where prev the hellepy fi J saved the code fom the ous tutorial and ist the avaiable les within you should see IF youve previously used Python 3 on a Maco Linux, and bsequenty the RaspbertyP, you maybe a tle confused as towhy the Windows version of Python wsesthe command ine: python instead of python The eason behind this that UND Ike systems such as macOS and Linux, already have Pthan libraries preinstalled. These older branes are present because some ofthe macOSand Linux tem sities ely on Python 2 and therefore instaling a newer version ‘oF Python, and thus aerng the executable name, couldhave dre consequencesta thesystem, Ac result developers decided thatthe best aparoach For macOS and Linux ystems would be to leave the command line “python as exclusive Python 2 use, and newer versions of usrinstlled Python would be python3 Executing Code from the Command Line BED From within the same folder as the code you're going torn enter the followinginto the commandline python hetlo.py This will execute the code we created, which to remind you is ‘="Python” boris” cool!” printca, bs © Tiss an issue with Windows, a i dese use any Python aries other than the ones installed by the user themselves when actually instaling Python. When a Windows user install Pythan, the installation wizard wil auto-ncude the command ie Instance tothe core Windaws PATH variable, which you can view by entering path into the command tine, This pointsto the python. ‘exe file required to execute Python code from the commandline, fe dont recommend you install bath Python 2and Python 3 within windows 10; natural, you canif you want, but realistically, although Python 2stilhasafootholdin the coding world, Python 3is the newest version However if youd, then you wil need to Fenarne one ofthe Python versione nan as they willbe installed in iferen folders and both use python.exe asthe commandtine executable.’ litie long-winded, so unless there'sadre needto have both versions of Python installed it’s best stick to Python 3. => Python Foundati ns) Numbers and Expressions Me aE rear rele ae Ue Re ar like. Now let's expand on that, and see just how powerful Python is as a calculator. You can work within the IDLE Shell, or in the Editor, whichever you like. IT’S ALL MATHS, MAN ‘You can get some really impressive results from the mathematical powers of Python, as maths isthe driving Force behind the ‘code with most, if not al, programming languages. ESPTSER open uothe cutversion of Python 3, asmentioned IM voucanuseal rvs you can use ether the Shell or the Ecitor. For the the customary _Est_st_oty_coti_ind time being, we're going to use the Shell. Fyou've opted touse a Mathematical operations: divide, thirépartytext editor, note that youneedto get tothe IDLEShell multiply, brackets and soon," ipe-Tcueione, sorsicat or 1 For this parc the tutoria, Practise witha few,forexample: °° > ia Sop uote = ae Paonateusounese Se eae aera a Ba ee peace aries aazaeay es EATER "the Shellenterthe Following: syouveno a BD csi | Se sion produces adecimal ss ‘pumber.n Python, these are Recast oe ‘SAREE TEENA called leats,orfioating point Sn ‘Asyou can see, Python canhandle some quite large numbers, arithmetic however, ou ‘ needaninteger asopposedtoa —aaosean Cory ecimal answer, thenyoucan use o> samerseeravoseaneaat se a oh hotatcin, tn S738, OnE) Bae vin SP HE Gee a GOUDIe slash: Pectin, ee 6 man ome toma ve So snaunes = peta irene andsoon, > cant ¢ Numbers and Expressions [ Youeanato use armenian Thswitbe SUED sropcrstionto re car out ong cron voy MD Gsctayed ss see theremainderleft overfrom cn 3:232 "3-7 ete ‘0b11, converting the integer ‘vision. For example: ge Scpisimer, seeaxtet ee" intobinay, and adding the prefix = an Ob to the front. Fyou wane to So spsontssass remove the 0b prefs, then you wil dply 3333200003, ahcn |r ruse Rotene dreaming hyu [Berens = now enter: of —— ee eon eore Shen ‘he Fomatcommandcomens aa SS sae valu, the number 3,808 4 Tiswildspayt.yhihisthe ny formatiedrepreention remainder left over fram dividing == as controlled by the Format hadtStamanas 10 by 3. ve specification, the ’b’ part. pe Nextupwe BE, Pat Sa owen ‘A Boolean Expressions loicl statement that wi SUD etre power nein REED cher ve or fse Wecan use these to compere operator oc exponenttion TAMA, “rt 8a, and eso ee Flea to lethan or greater han, Ty youwanttobetecineal Us ina New ie Towork out the power of homer something you can use a paeeaielaseiiiseae - double mutipletionsymbo 2 ie print, ordowestaronteayboud: — 23 pe print, 10°10 Se ware print, sini 52092, bawere Swe pranks, Sueyouabesdseauthe bs un a 3sics behind maths operators. . ———— Tesherpimiinate — [Eoiiienaes Poi CANTATA SED) ‘eutin Python. oN print, not @ == 7 and b = 6) PEAT cxccute the code from Step, andyoulsee a series of True or False statements depending on the resu ofthe two defining values: 6 and 7. I's an extension oF ‘what we've looked at, and an important part af programming. a ESTER) Numbers and expressions don't stop there. Python has numerous bulla Functions to work out sets of numbers, absolute values, ‘complex numbers, anda host of Mathematical expressions and Pythogarian tongueswisters. For example, to convert a number to binary, use: ® bincay wmebrecn => Python Foundati ns) Using Comments PEIN a ik ae Ree erie eccrine e unnamed code line by line, but when the code starts to hit thousands of lines, things get a little difficult to read. #COMMENTS! ‘A method used by most programmers For keeping their code readable, is by commenting on certain sections. For example, if ‘variable is used, the programmer comments on what it’s supposed to do, It's just good practise STEER) Wiclistartby creating snewinstance ofthe DLE IM) resavethe code and execute it. Youllsee thatthe Edtor (Fle > New File, an then create a simple ‘output in the IDLE Shall stil the same as before, ‘arable and print command: espite the extra lines being added. Simply put, the hash symbol a denotes aline text the programmer can inset, to inform them oA ne wale of Aisi"99 eran ace erases esas = F SS Saat Seer rt hep rien oe soe EE ccvccicwireur vce newiner | ERBEP) tccosunetaivevoabe swe cesess ERD foros couse ane SRR EN San See ‘we expected. Now let's acd some ofthe types of comments you'd cis, the value decreases by 1. The programmer could insert 3 normally see within code: routine along the ines of # Set the start value of A to 10 oot ‘ont0 printC*You've just lost a tifel”) # Print the current value of A printC*You now have”, a, “Lives left!” print(“The value of A is,”, a) (B -commenepy- Ci non CaaelCormenty 10 psec Bin} while we know thatthe variable A denotes number fives and the player hasjust lost one, a casual viewer, or someone checking the code, may nat know. Imagine fora ‘moment that the codes twenty thousand tines lng, instead of just cour seven, You can see how handy comments are, Boom =a x Baa Essentially, the new code together with comments could look ike # Set the start value of A to 10 o=10 4 Print the current volue of A print(*The value of A is,", a) 4 Player lost a Life! omod 4# Inform player, and display current value of A ives) printC*You've just Lost a life!™) PrintC*You now have”, a, “Lives Left!” Bay You can use comments in different ways For ‘example, Block Comments area large section of tet that details whats going onin the code, such asteling the code reader which variables you" planning on using 4 This is the best game ever, and has been developed by a crack squad of Python experts # who haven"t slept or washed in weeks. Despite being very snieLly, the code at Least # works really well. BEET D ie comments are comments that Fllowa section of code. Take our examples From above, instead of inserting the code ona separate ine, we could use 0-10 # Set the start value of A to 10 Print(*The value of A is,", a) # Print the current value of A o-a-1 # Player lost a Life! printC*You've just lost a life!") printC"You now have”, a, “Lives Left!" # Inform player, and display current value of A (lives) ‘The comment, the hash symbol, can also be used to comment out sections of code you don’t want tobe executed in your program. For instance, Fyou wanted to remove the First print statement, you would use: 4# print(*The value of A'is,”, a) ( “Conmenspy- Cynon Code'Commentspy 870) File Edt Fomst_ Ran Optont Window Hep # set the start value of At 10 # Fran che carsent value of & f prune (eThe value of A sey", a] FEETDD You also use three single quotes to comment ‘outa Block Comment, muitvine setion oF ‘comments. For ther to wotk, place them before and after the areas youwant to comment: ‘This is the best game ever, and has been developed by a crack squad of Python experts ‘tho haven’t slept or washed in weeks. Despite being very snelly, the code at Least works really well. 77? / Using Comments [ => Python Foundati ns) Working with Variables eee aE Sc gear Canker ee emg ee ate eco ie Maat einen rei certain values to a variable. VARIOUS VARIABLES ‘We'llbe working with the Python 3 IDLE Shell inthis tutorial f you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. BETESERD 00 programming languages you're required touse adolasignto denotea string, which sa ‘arable made up of muliple characters, such as aname of aperson. In Python this isnt necessary, so for example, nthe Shell enter: ranes"David Hayward? (use your own name, unless you're also| «alled David Hayward) ‘As we've seen previously variables can be concatenated using the plus symbol between the variable names. In our example, we can use: print. Cname +: tg ttle). The middle part, between the quotations, allows sto adda colon and a space. as vaiablesare connected without spaces, we need toad them manually You ancheckthetype of verabe nue by esha Gue2 the type!'© command, placing the name of the vsibeinie the baits nor ame ube ‘57pe none) Ada new ring vob title escended From Colts” ‘weiner e Wecan also Be _ within another varable. For example to combine both name and tle variables intoanew ‘ible, we use: charactersnane +: “+ title Then outputthe conten ofthe ew variable as: print (character) ‘Numbers are stored asiferent vaisbles: gems Type Cage) Which as we know, are integers. (Working with Variables [ PSTD However you cant combine both strings and STEED This presents bit ofa problem when you want integer type variables in the same command as you towork witha number that’s been inputted by ‘woulda setof similar variables. You'lneed totum one into the the use, for example, as age + 10's both string variable and an ‘ther, o vice versa. When you doteyto combine bath youll get an integer, t won't work. Instead, you need to enter: ‘error message: ee re ‘Thiswill Typecast the age string nto an integer that can be on mal worked wth, a aera ae estas tases cure ae ae ES Ee ee Alternatively, you can use: Now enter type(shiint) and you'll see that Python has allocated | between the words in quotes, as the commas treat each argument taprint separately. ESTER) other example of Typecastingiswhenyoussk — NBM when combining integers and feats Python Forinput from the user, such asa number. for Usually converts the integer toa float, but should ‘example, enter: the reverse ever be applied, i's worth remembering that Python : = Clovsnt return the enact value, When converting afloat to an RPA SHELA ESRC integer, Python wil always round down tothe nearest integer, ‘Alldata stored fom the Input commandisstored asastring variable. called truncating; in aur case instead of 19.93 itbecames 18 ao a => Python Foundati ns) User Input VRE olu Morel Mere eo Ra Reel ROMER Coe Pee ere iene eae seen Mie) tcc ice rice a a USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding. A game, for example, may ‘ask for a character's name, whereas a database can ask for personal details. EATER isnot already, open the Python 31OLE shell BREED Now that we have the user's name stored ina and stata New File nthe Edltor, Let’ begin with couple of variables, we cn call them up whenever something really simple, enter: ‘we want: printc*Helto") printC*elcone”, firstnane, surnane, . T hope: ‘irstnane=inputC*What ts your first name? “) you're nell today.”) print(*Thanks.") Surnane=inputC*And what is your surnane? *) [Bwaran-corencaeran oar | Be Fle_Edt_Formt_Rn Options Window Help Brine ("Hel i0-*) Fizotnanersnput (Wet ie your first name?) Pinamerinpst(vhnd war 4a your surname? *") BED Seviccccetwcon na yarocnie RRIF sven ma oon srccam oe ESD soso sin rene Piss ete loane atthe. fevournnane yl coeteensnaae loniby Tetmnart e clcoson roan eee ‘your surname; also stored its oun variable (surname). the code: Poy | print¢*elcone”, firstname, surnames, T hope et mt niey_ pte you're well today.”) User Input. Bea the input command, For example, you canaskthe userthetrname, andhave the input inthe line below: print¢“Hetlo. Whats your name?) rramesinput © tet: neat ‘The code From the previous step i often egarded as being litle neater than having a lengthy ‘amount of text inthe input command, butit's not arule that’s setin Stone, so do as youlike in these situations. Expanding onthe code, tiythis print C*Halt! Who goes there?”) rane=input© You dar'talways have te include quoted text within What you've created here sa condition, based on the user'sinput In short, we're using the input From the user and measuring it against a condition. Therefore, f the User enters David astheirname, the guard wil allow them to pass Unhindered. however, they enter aname other than Davi, the ‘uard challenges them toa ight. ‘As you learned previously, ay input from a user isautomaticallya string, so you'll need apaly a “TypeCatt inorder to tur it into something eee Th creates ome Interesting addtions to the input command. For example: # Code to calculate rate and distance printC*“Input rate and a distance") rate = floatCinput("Rate: “)) (a eee nce from the user to Flesh outthe game a ite: iF namess"David": printC"Melcome, good sir. You may pass.”) else: printC*I know you not. Prepare for battle!") W's agoodstarto atext adventure game, perhaps? Now we can expand ont, and use the raw input Dees Ghat BRTTSET BD (70 tofiralsetherate and dstance code wecan ad: distance = floatCinputC*Distance: “)) print(*Time:”, (distance / rate)) Save and execute the code, and enter some numbers. Using the Float(input element, weve tld Python that anything enteredisa Floating point umber rather than a string, => Python Foundati ns) Creating Functions Now that you've mastered the use of variables and user input, the next step is to tackle Meee ene Er Cut eet at itn n tare ance ereanencmmen nite tm FUNKY FUNCTIONS ‘Afunction s a command that you enter into Python in order to do something t's. litte piece of self-contained code that takes data, works on it, and then returns the result. FEPTED sot oniydatathat a function workson. Functions ERIM You can pas variables through functions in much cando all manne of useful things in Python, suchas the same manner. Lets asume you want the sort data, change items from one format to another, and check the number flttesn a person's surname, you couldusethe folowing length or typeof items. Bacall afuncionisashort word foliowed code (enterthe text editor Fr ths example) boybrackes. For example, en0, ist), or type. ane=input (“Enter your surname: *) od — Gg x Count=LenCnane) fa en any pi et print C*Your surname has", count, “Letters in Teen mane ana ee mT fem 2S, caer ema tn Press FS and save the code to executeit. ETE “forctontaesdats usalvaverisbe, worison FEIESNEB thon hastens oFFunction bul itt fa too ED terse ethane, care et ei todo,andretumsthe ence The cata Beng wrkedon goes However, to view te st of ulin uncon avsiale to Python inside the brackets, soiFyou wanted to know how many eters 3, navigate to hetpsi/docspython.org/3/lbrary/functions.hem. are inthe word antidsestabishmentaranism, then you'd enter: These are the predefined Functions, but since users have created ‘TenC*antidisestablishnentarianise”), sndtherumber 28 mary mare, they're not the only ones avaiable ‘would return, (Brame ‘Adonai functions con be addedt Python SUP through modules. Python has a vast range of tvodulesavaloble that can cover merous programming dues functions and canbe imported as and when required. Fo iced Mathematics Funetios They ad example, ‘import math Once entered, youll have access to allthe Math madule Functions: FORGING FUNCTIONS There are many different Functio BED To use a function from a module, enter the name o! the module, Followed by afullstop, then the name ofthe Function. Forinstance, using the math module, since we've just imported into Python, we can vtlse the square root function, mmath.sqrtc16) Asyou can see, the codes presented as module function (data). reated by other Python programmers, which you can import and you'll undoubtedly come Pee e er en tte nen een te eet) PRR choose File» New File to enter the editor, et ese meee ee cea ey Fret loO) Cee eee ee ens eee ort ste 2 Jala fee Hettocnane) | Brint C"Hetto™ ee ee eer ee Sn cae STEP 3 eee ena aetna poereute acre BRPEPD wha: you've ust doneis import the Hello Fun See eee ee ares re arene tere ee ene et eee meee eee Hier addCa, DD] => Python Foundati ns) Conditions and Loops Conditions and loops are what make a program interesting, they can be simple or rather ea UN eat ei eon ater citer ort they could be the number of lives left in a game, or just displaying a countdown. 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 i isn't. Levscreatea ew ten progam ot wiasthe SER Now wel sean tstaterwnt ta deci he word tsertolput ora encheck tose ese Tenge egal four andi fouletterword oot Stat th Fla New Fl sndbepn th confomatoneeplestothende the npu val sordstroatePeaseTenterarfourstettarina sordctrputcePtenseTentenrerfourstateewordsas) mraclengtictenceand) fepenastenpeene? Print (word, "is'a four-Letter word. Well: done") 2 “The double equal sign something ese checkif something i equa to FEE veconccesrensaie esecin REP ncona news tesbvoo nat os ESRD orcs suscsacroaransctrs ts Tocris Sones ace ‘get the total numberof letters the user hasjust entered that's indented. Next, move the cursor backto the beginning oF wordwinputC“Please enter a four-letter word: “) tne Foto: vword_length=lenCword) nord-input(“Please enter a four-letter word: *) ‘nord_LengtheLen(word) aaa Af word_length = 4: a a x Conditions and L BED Meee teccctomecreiene — ERSPB rowed tense trots 2Fourletter ward intheShelito begin with Jou Eventualy could become qute complex Weve shouldhove the returned message thatthe wordisfourlettas. ad Now press FS again, and rerun the program, but thistime, enter a Fiveletter word, The Shel wil display thatt'snot a Four letter word, ‘onion for three-letter words: wordinput(*Please enter @ four-letter word: *) word_lengtheLen(nord) if word_length == 4: print (word, “is @ four-letter word. Well one.” elif word_length == 3: print (word, “is a three-letter word. Try again.” else: print (word, “is not @ four-letter word.”) LOOPS ‘Although a loop looks quite similar to a condition, they are somewhat different in their operation. A loop will un through the same block of code a number of times, usually with the support of a condition, imple while statement. ke if, EM the Foro ee Set Seen rene jables inside square brackets. For example: Pronds=[Cate SDogn, sUniconne] Thediference between f and while that when IM the eed eee corny Serene eer eee emenaee ete settee Python Foundations Python Modules eon re ee emer eon eee uated using modules is such a large part of getting the most from Python it’s worth dedicating Eee Cuore ok MASTERING MODULES Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are counties modules available, and as we've seen, you can even make your own, PRFID) 2erovah good, the builtin functions within Python ERNE the result isan erorin the 1OLE Shel asthe are inited. The use of modules, however allows us Pygare module fntrecognised or installed in tomake more sophisticated programs. Asyou re aware, modules Python. To installa module we can use PIP (ip installs Package) arePython scripts that are imported, suchas impart math, Clase down the IDLE Sell and drop into a command prompt o Terminal session, At an elevated admin command prompt, enter: mW pip install pygane Some modules especalyon the Raspberry are The PP instalation requresan ele Sieve included by default; the Math module is a prime Sie to it installing components at different locations, ‘example. Sed, other modules aren't always avalable. A goed Start with a search for CMD, via the Start button, ight-c the example on non platforms isthe Pygame module, which contains result, and then click Run as Administrator. Linux and Mac users can ‘many functions to help create games. Ty-import pygame. Use the Sudo command, with sudo pip install package. ‘lose the command prompt or Terminal, nd re- launch the IDLE Shel. When you now enter import rygane, the module will be imported into the cade without any problems. Youl find that most code downloaded, or copied, From the Internet will contain amodule, msinsteam or unique, and their absence is commonly the source of errors in execution & ‘The modules contain the extra code needed to achieve a certain result within your own code, with hich we've previously experimented. For example: ‘import random Brings inthe code From the Random number generator module. We can then use this module to create something Ike: for i in rangecto): ‘print(random.randint(1, 25)) we (Python Modules [ ‘Multiple modules canbe imported within your code. ‘mort: random ‘import math for I in rangetS: pprint(random.randint(1, 25)) print (math: pi) (anni ce aid =o x The results astring of random numbers followed by the value of, as pulled from the math ‘madule using the print(math.) function. You can also pullin certain functions From a module by using the From and import commands, suchas: from random import randint for i in rangecs: printCrandint(l, 25)) This code, when saved and executed, wil display ten Sueru random numbers from 1 to 25. Youcan play around vith the code to display more or less, and From a greater or lesser range. For example: ‘import random for i in rangeC2s): ‘printCrandom.randint 2, 100)) This helps create a more streamlined approsch to SE programming, You can also use: import module*, hich willimport everything defined within the named module. However is often regarded as awaste of resources, butit works onetheles. Finally, modules can be imported as alases ‘import math asim printcm.pid OF course, adding comments helps to tel others whet’s going on => Python Foundations Python Errors It. goes without saying that you'll eventually come across an error in your code, where Python will declare it’s not able to continue due to something being missed out, wrong, Cee cas em aut atind DEBUGGING Errors in code are called bugs, they're perfectly normal and can often be easily rect 2d with a litle patience. The thing is to keep looking, experimenting, and testing. Eventually your code will be bug free. PPD code lent assluidas the written word,no matter how good the programming language's. Python is ‘cettainlyeasierthan most languages, but even iis prone to some annoying bugs. The most common are typos bythe user, and while ‘sy to find n smple dozerine code, imagine having to debug rmult-thousand tne code. As we'vementoned, hemos common of eros Suave the typo, often at the command level, mistyping the prin commando eel Hore thy alo cou when youve ‘Set nurerov vale lo vis hve enthy ames The best, ice sto spy gotvoghthe code and check ou spel, ‘Thankful Python is helpful when it comes to displaying error messages. when you receive an errorinredink from the IDLE Shel twill define the error itself, alongwith the tine number where the error has occurred While in the IDLE Ector this salle daunting for lots of code, textedtors| helpby including tine numbering. PEPE Syntax rors are probably the second most common erors you'll come across a programmer. Evenif the spelling ie corcect, the actual command ial s wrong. In Python 3 ths often occurs when Python 2 syntaxes ae applied. The ‘mast annoying of these isthe print Function In Python 3, we use print words"), whereas Python? uses print “words”. (Breese =a x tt gem (_ Python Errors [ TED Pests brackets are also a culos of programming ‘errs, especially when you have something ike: printCbatanced_checkCinout©)) Remember tat for every''there must be an equal numberof ‘There are thousands of onlin Python resources, code snippets and lengthy discussions across Forums on how best to achieve something. While 9% oft is good cade, dart always be lured into copying and pasting random code into your editor. More often than nat, it wont work and Frustratinaly, you wont have leamed anything. Baa An excellent way to check your code step-bystep is touse Python Tutors Visualse web page, Found at ‘wurw pythontutor.comvisualizehtmlsmode=edit. Simply paste your code into the editor and cick the Visualize Execution button to run the code line-byine. Thishelp to ear bugs, andany rmisunderstandings. Planing mates fr good code, While te old Sie ‘school, it's @ good habit to plan what your code will obefore sting down totypettout Us the varies tht lle Used, along with the modules, and write outa serpt for any user Interaction or outputs. FED misses conus een rns from the Conditions and Loops section, where the colon means everything indented Fellowing the statementisto be executed _aslong as t's true? Missing the indent or having too much oF an indent, will come back with an errr, PEPE BD Purely cut of interest, the word debuaging in ‘computing terms comes From Admiral Grace Hopper who, back inthe 0s, was working on a monolithic Harvard Markl lectromechanical computer. According to legend, Hopper Found a moth tuck n a relay, thus preventing the system from working. Removal of the moth was hence called: debuosing, => Python Foundations Combining What You Know So Far As we've reached the end of this section, let's take a moment to combine all we've looked at so Far and apply it to writing a piece of code. This code can then be used to esa ni cae m neem eR aes PLAYING WITH PI For this example, we're going to create a program that will calculate the value of Pito a set number of decimal places; as described by the user. It combines much of what we've learned, anda little more. EPID starsty opening Python and creating aNewFilein ERMA) the previous step defines the rules that make up the Editor Fist, we need to get hold ofan equation both the algorithm and reating the string that thatcan accurately calculate P without rendering the computer's eventually display the value of Pi according to the Chudnovsky (CPU useless for several nutes. The recommended calculation _brother's algorithm. As you have ne doubt already surmised, t Lsedin such crcumstancesis the Chudnovsky Algorithm, you would be handy to actually output the value of Pita the screen. To can find more information about at enwikipedia.ora/wik/ rectify that we can add: (Chudnovsky_algorithm, nue ‘We can utilise the Chudnovsky Algorithm to create ° EEE Wc anettsethecrudnosey Ago to ceate BRED yo con save andere the code at this point. f (begin by importing some Important modules and Functions you tke. The output wil print the value of Pito 27 Tie appl eA ete elt ST Tee cecil places: 3.141592653889734207668453591.vihile pretty within ere modes impressive on is ovmn, we want some user interaction to ask he from decimal import Decimal, getcontext ‘ser as to how many places Pishouid be calculated. ‘import wath ‘This uses the decimal and getcontext functions fromthe decimal EEN) we can insert. an inputline before the Pi calculation ‘module, both of which del with lage decal place numbers, and, Def command need to be an integer, ast wl raturaly, che math module otherwise default toasting, Wecancalit numberofdats, anduse the getcontextFuncion PETER owwecaninsrtthericaluationalgarthm —_punberoFdigits = intCinputC*please enter the partofthe code Thsisa version ofthe rumber of decinal place to calculate Pi to: “D> Chudnosky Algorithm: getcontext©).prec = nunberofdigits ef caite(n): o = Decinal(o) ei aay pi = Decimal(o) a ddeno = Decimal (a) k=0 for k in rangen): t = (ecimal¢-1)*4k)*(math. factorial Decinal (6)*k))*(13591409+545140134%) deno = math, factorial @3*k)*(nath. factorial(k)**Decimal(3))*(640320°*(3*4)) . pi += Decimal (t)/Decimal (deno) a pi = pi * Decimal(12)/ Decimal (640320**Decinal(1.5)) pi = Upi return str¢pi) ss PSTTSERD Wiccan execute the code now, anditllaskthe user tohow many decimal paces they wantto calculate Pian then output the result inthe IDLE She. Try itwith 1000 places, but dont go to high or else your computer will be locked up freadting Partofprogenminis SUEPO being able to modify code, raking ore eerste ets ice areomert tha tines how ong itles ou Conputrtoalesatethe Sadial pares and preset the nverrabonin erent {Stour Forth chopintothe command ire soderpo the coon ode wee aeayhave stated vip install colorana Torin or code we need tose the EuEP AT colorama module, and then start the time Function axthepointwherthe cast stars aden tfnses The end resut apaysnclared i wlan the preestok On the Terminal orcommanctin) 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 ef calecn) with the Fore Function (which cctates the Foreground, ink, colou, and the time module to start a virtua stopwatch to see how long ‘ur ealeulations take: import time import colorana Fron colorama import Fore = Decinat(a) i = Decimal (oy ‘deno = Decinal(0) kao for k in range(n): t = @ecimal(=1)*#K)*Cnath. factorial (Decimal 6)*K))*(13591409+545140134"K), deno = rath. Factorial(3*k)*(nath. Factorial k)**Decimal (3))*(640320**(3*K)) i 4= Decimal (t)/Decimat (deno) pi= pi * Decimal (i2)/ Decimal (640320**Decimal(1.5)) pi = pi return steCpi) printcealeci>) printCFore.RED + “\nTine token:”, time.time) = start_time) 5 eevee » Data kl , hh ae eo 5 Pea ee teas ety - gold or oil, and with it, you can elect o Reeser Cues . ee eee es Cer cee are id POR Cameesticn erin a a Peete orate eee es “» . 7 Seer Meee cera) Mo od | @® © Python's ability to cope with data - e a a and how it can be organised in your eee G ean ees » TM) created and how to read and write Create seur tetas) \ Prentice r res yd ~ Cae eres nea ’ e eras Bee an 14 Wrting Fes p an - Cy ae . Peed Combining eee ) Manipulating Data Lists Lists are one of the most common types of data structures you will come across in Python. A list is simply a collection of item Eee emetic te natch cen 9 data if you prefer, which can be accessed WORKING WITH LISTS. Lists are extremely handy in Python. A list can be strings, integers, and also variables. You can even include Functions in iss, ‘and lists within lst. EEE *lstisasequence of data values called tems. You create the name of your ist followed by an equal ‘sign, then square brackets and the items separated by commas, note that strings use quotes: numbers = [1, 4, 7, 21, 98, 156] nythical_creatures ~ ["Unicorn”, “Balrog”, "Varpire™, “Dragon”, “Minotaur™} (Breuirone = x You can also access, or index, the lastitem in alist by Using the minus sign before the item number [-1], oF the second to last item with [2], and so on. Trying to reference an ‘em that sn’tin the list, such as [10] wil return an error: runbers[-1] anythical_creatures[-4] Bee BETES Orc youve defined your ist. you can call each by referencing itsname followed by number. ists startthe ist item entry 350, fllowed by 1,2, 3, andso.on. Forexample: numbers ‘ocallupthe entire contents of the Uist. runbers(3] ‘Tocallthe item third rom zero inthe Uist (21 in thiscase) ‘aie FEEL Sicnaissimiarto indexing, butyou can retrieve ‘multiple items in alist by separating tem numbers vith acolon.For example: runbers(1:3] ‘willoutput 4 and 7, those being item numbers 1 and2. Note that the returned values don’ include the second index position (as you ‘would numbers{t:3] to return 4 7 and 21), BP ogc tors wien csi ene join two lists we can use: everything = nunbers + mythicalcreatures ‘Then vew the combined lst wth everything PD tems canbe added toa list by entering runbers=nunbers+[201] OrForstrings nythical_creatres-aythical_creaturess{"Griffir"] (rby using the append function: nythical_creatures.append(Nessie") runbers.eppend(278) Remora of tems can be done n two ays, The Fist Sueru is by the item number: ‘del nunbers(7} ‘The second, byitem name: mythical creatures. renoveC"Nessie”) BE coviunnrcance servi ssbeneg Soest esete cee feciosfreoroe nit svewneccioouoa env, numbers. insert(4, 62) vats tear attendee numbers .pop(4) vireo You atousete it uncon tabresk a sting down Sie into its components. For example: Vistc*avia?) breaks the name Dav nto toa newist ane=List(*David Hayward”) 1,6. This can then be passed rane age=[44] user = nane + age PEPER cesecon tht, we cn reatea program to store someones name and age asst: rnaneinputC*nhat"s your nave? “) {nane=listCnane) agenintCinput “Hon old are you: “)) lage=fage] user = Inane + Lage “The combined name and age ist called user, which canbe called byentering ser into the Shell Experiment and see what you can do, ar Me Ma uel eam ete ce och eee een Meme Terrace) perfect for storing fixed data items. tant. This is called immutable, and THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the program is intended to do. Mostly a tupleis reserved for something ‘special, but they/re also used, as an example, in an adventure game where non-playing character names are stored. ESPTSPB * leis creates the same way asalist, butin this Instance you use curved brackets instead of square brackets For example: nmonths=C*January”, “February”, “March”, “April”, “May”, “June") rnonths Dineen =o x You can create grouped tuples int lists that contain multiple sets of data. For instance, here we havea tuple called NPC (Now Playable Characters) containing the character ‘name and their combat rating, for an adventure game: NEC=EC*Conan”, 100), C*BeLit”, 80), “Valeria”, 95)] a Ash tthe tems within a named tle canbe BARD oe) acordngtother posioninthe dats ange: sonths (2) tonths(S] ‘And soon, However, any attempt at deleting, or adding, tothe type ‘wl result in an errr inthe Shel ESTEE £2ch ofthese data items can be accessed asawhole byentering NPC nto the Shell or tey canbe indewed according to ther position NPC]. You can alsoindex the individual tuples within the NPC ist ecto} (1) il splay 100 ’sworth noting that when referencing mutiple tuples within ais, the indexing is ighly different From the norm. You would expect the 95 combatting ofthe character Valeria to be NPC[a[S], however its not, k's actually wecr2]t1 STEED Now unpeckthe tupteinto woe corresponding variables: (Crane, conbat rating) =NPC ‘You can now check the values by entering name and combat_rating cs FID this means, of couse, thatthe indexing follows thus: ot ° 2 1 20 aa ye This, as you can imagine, gets little confusing when you have alot of tuple data to deal with, Remember a witht youcan aso ndextupes Sie using negative numbers, which count backwards fromthe endf the data S,foraur ample ng the tue with ult data ters we wouldrefrence tele character th Nect2]¢-01) a Tuples though, use a feature called unpacking, Sueru where the data items stored within a tuple are ‘assigned variables Fst create the tuple with two ems (ame and ‘combat rating) ‘nPc=C*Conan”, 100) & \We can use the max and min Functions to find the Suz highest and lowest values of a tuple composed of rpumbers. For example: runberss(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) “The numbers canbe integers and floats. To output the highest and lowest, us: printnaxcrunbers)> print¢mincrunbers)> eccnnen CI EP Manipulating Data Dictionaries Lists are extremely useful, but dictionaries in Python are by Far the more technical way of dealing with data items. Although they can be tricky to get to grips with at first, Net evn eer cen tment a KEY PAIRS ‘A dictionary is tke alist, But instead each data item comes as a pair, the ‘are known as Key and Value. The Key part must be ‘unique and can either be a number or string, but the Value can be any data item you like. PTSD evs say you want to create a phonebook in Python, You would create the dilonary name, and contain the data in curt brackets, separating the key and value bya colon Key:Value. For example: phonebooke{ “Enna”: 1234, “Daniel”: 3456, “Hanna 789} & ESTED ith sesand tuples, you can check the contents of adicionary by cling the icionary name; phonebook, in this example. This will display the data tems youve {enteredin similar fashion toa lst, wich youre no doubt familar with by now, swt ts tunes, nd0 on tings need Gee to be enclosed in quotes (single or double), while itegerscanbe lft pan Remember ht these on De ee string, or an integer, you ust need to enclose the relevant one in quotes: Phonebook2={"“David"; “0987 654 321} Bresson a ESTED Te benefit of using dictionary is that you can enter the key to index the value, Using the Phonebook exemple From the previous steps, we can enter: phonebook “Enna” phonebook “Hannah” a ‘Adding toa dictionary iseasy too. You can include Bea ‘anew data item entry by adding the new key and valueitems as suck: phonebook[“David"] = “0987 654 321” Phonebook eiensome =o x ‘nd you can also remove items from a dictionary byissuing the del command followed bythe IRemskey-the value will aso be removed as wel since both ‘work as pair of data items: ‘del. phonebook(“David’ Next, we need to define the user inputs and Bea variables, one forthe person's name, the other for their phone number (we wil keep it simple to avoid enathy Python code) rrameminputC“Enter name: “) runber=intCinputC“Enter phone nunber: “)) & Note we've kept the number as an integer instead (oF astring eventhough the value can be both aninteger anda string, Now we need to ade the user's inputted variables tothe newly created blank dictionary. Using the same process asin Step 5, we can enter phonebook[nane] = number aw Taking thisa step Further how about creating 3 Sue piece of code that will ask the user For the dictionary key and val items? Greate anew Ector instance, and sta by ‘coding in anew, blank dictionary: phonebook={} Now when we save and execute the code, Python Bea willask fora name and a number. wil then insert those entries int the phonebook dictionary, which we can test by entering nto the Shell: phonebook phonebook[“David"] Ifthe number needs to contain spaces youineedto makeita string, so remove the int par-of the input. EP Manipulating Data ) UD) Splitting and Joining Strings ene Re Tatas cr Aiea aM Co 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 ‘We've already looked at some list functions, using .nsert, remove, and .pop, but there are also Functions that can be applied tostrings. Themantstintestingfucionasenls sod. EEEEMED reteh nto ncn ats Sued ‘With it, you're able to split apart a string of data, one quotes, then a space followed by closing quotes: basedon the argument wahinte brackets For example hee'sa__ and backts. The space ste separate, nacating tat ech st stinguath thet echseoarate bya spac: item entry separated by space tense CSV (Comma Separated ‘sext=*Dontel anna Emmat ‘aus conte asa cone, so we woud se: text="January, February, March, April May, June” ke months=text. split," cr maces Months Sects ine of om tr we etm = ESTEE Now ters turn the string into alist, andspitthe ESTED We've previously seen how, using aname, we can contentaccordingly: splita string into individual letters asa ist: omes=text.split(* *) rame=1ist(*Davie”) ‘And enter the name of the new list, names, to see the threeitems, MAM ‘The retuned vues 1, Whit may seem le Pm Uselessunder ordinary crcumstances, coud be and for eating Falster Sean seer mesonw ar me |spelinggame, for evant = 7 BSPEEM The converse ofthe spit function s join, where separate items ina string, canjoin together to form ‘awerd, or usta combination oF items; depending on the program youre wrking, Fr istance: ‘alphabet=”. join([“a”,"6”,"c","a,"e"]) ‘alphabet ‘This wil splay ‘abede' inthe Shell Farm the name: rame=”. joinCname) \We can therefore apply join tothe separated name we made in Step 4, combining the letters again to ‘we've joined the string back together and retained thelist called name, passing Itthrough the join Function. & ‘swith the spltfuncton, the separator doesn't Bea havetto be a space ican alo be a comma, ora Full stop, oralyphen, or whatever you tke colours+[*Red”, “Green”, “Blue”] cole,” join(edtours) ‘itLe="conan the cimerian” title.copitalizeO title. titleQ There's some interesting Functions you can apply to string, such as capitalize and title For example: a ‘good example of using the jin functions when you have list of words ou want to combine into asentence Liste[“Conan”, “raised”, “his”, “mighty”, “sword”, “ond”, “struck”, “the”, “denon”) text=* “.joinclist) text Note the space between te quotes before the jon function (where there were no quotesin Step 6 joi). You canals use logic operators on strings, Suz with the in and not in functions. These enable you to check a string contains (or does not contain) a sequence cof characters message="Have a nice day" “mice” in message "bad" not in message “day” not in message “night” in message ewbdmpubiatonscam EP Manipulating Data ) UD) Formatting Strings As you work with data, creating lists, dictionaries, and objects you'll often want to print out the results. Merging strings with data is easy, especially with Python 3, as earlier versions of Pythons tended to complicate matters STRING FORMATTING ‘Since Python 3, string Formatting has become a much neater process, using the format function combined with curly brackets. “This makes things easier to Follow and, as with most coding, there are other ways to do things but this ways recommended. BEPESEB the basic formatting in Python ito all each ED Wc can, of course, also include integers into the mix: variable into the string using the curly brackets: meee rane="Conan? printc*{} of {} was a skitled mercenary, printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold fron a ‘O° fornetnane)) merchant.”.format(nane, place, ninber)) BETTER Perembertodosete print function wth two sets BRNMENPBM There are many cifferen: ways to apply string OF brackets, 2s you've encased the varabein one, formating. some are aie simple, aswe've shown ‘and he print funconin another You anincude muliple cases oF youlere, and otherscan be significantly more comple. tall {8ng Frmattngin single prin urn: epends on what you want fom your program. A.good place to feferencefreqventy, regarding sting formating, the Python Docs webpege ound at tps/docs aython.org/3.ibrary/ String html, Here, you wilfind tons of hel, rame=""Conan™ place="Cimeria” Print(“{} hailed from the North, in a cold land known as {}”.formatCnane, place) Dama TEED teresting’, you can reference st using the string formatting Function. You needto place an ‘asterisk in Front ofthe listrame: runbers=1, 3, 45, 567546, 3425346345, PrintCSone numbers: Ch, Oy Oy (" format ctnunbers)) a (Formatting Strings ei ESTEEM Youcen print utthe content ofa users inputin the same fashion: ramesinputC“What’s your name? “) print(*Hello {}.”.format (name) FED 2 vith indexing inlss,the same applies to caling a lst using string formatting. We can index each item _2ccording tots position (from 0 to however many are present) runbers=1, 4, 7, 9 printCMore numbers: {3}, {0}, (2h, {1}. Format *nunbers)) ws BRPISERD 2 2 you probably suspect, you can mixstrings and integers ina single list tobe called inthe Format function characterss["Conan”, “Belit”, “Valeria”, 19, 27, 20) print C“{0} is {3} years old, Whereas {1} is {4} years old.”. format(*characters)) ry Andyou can extend thi sine code exalt Sie display the first letter in @ person's entered name: nanesinput(“that’s your name? “) printCHello {}.”.formatnane)) Inane=ListCname) print(The first letter of your nane is a {0}". format(*1nane)) BSTESET BD You con abso cal upon apair of sts, and reference them inivdvaly within the same print Function, Looking back atthe cade from Step 7, we can ater wth rrames=[“Conan”, “Belit”, “Valeria”) ages=([25, 21, 22] Creating two sts. Now we can call each ist, and individual tems: printC*{0[0]} ts {101} years old. Whereas {0011} is {1017} years old.”.fornat(nanes, ages)) ccnnen CE EP Manipulating Data Date and Time When working with data it's often handy to have access to the time. For example, you may Ned ols uP aE Ae Crater em ela ee ei ec mit ee Ma een aes cn el anette 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. Ba First you need tolimportthe Time module. t’sone that’s builtin to Python 3,50 you shouldn't need to ‘drop into a command prompt ané pip instal t. Once it's imported, ‘we can call the curent time and date with a simple command: import time ‘time asctimeC) (Woeesvene =e x tine.local. time) ‘he outputs dsplayed as such: “time, struct timeCtm yeor=2019, tnon-9, tmnday=7, tm_hour=9, ‘tmminaG, tm_sec=13, tmndays3, tmyday=250, tm ‘isdst=0)'; obviously dependent on your current time, as opposed tothetime this book was written, You can see the structure af howrtime is presented byentering: ‘The time function is solt nto nine tuples, these are ‘vided up into indexed items, as with any other tuple, and shown inthe screen shot below. 8 kage ye zoe : send 01061 (0 0r6t me apse) © coyote 096 (0 Monday) 7 ayot yee 1206 cto dy) © bape saings 1,01, 1 means tary eters OST There re numerous uncon bli the Sue) Time module. One of the most common of these teatime wis youre abe to presen ie ange oF sxaumene srt convers etme peo ating, Forever, te dopa the corer ay the eee cane time, strftimeC*KA?) a (Date and Time ei Naturally this means you can incorporate various Functions into your own code, such a5: time.strftimeC*%a”) time.strftime 5") time.strftimeC“%") time.strftimeC“947") time.strftimeC“M0s") Notte sto eri, wth and KM, a8 lad you can see, these are the hours and minutes and as. the lst entry indicates entering them as HM doesnt display the time carecly inthe Shell we can easy rectify this wth time. strftimeC*m 301") os BSTETD Wc an alsouse the Time moduleto display the amount o time taken fr an event to happen. For ‘example, taking the above code, we can alter itsightly by including start_time-time.timeQ) nd endtimestime.time()-start_time Dict cinttnaneshtten ign O78 sax The output willook similar tothe screenshot below. The timer Function needs tobe ether side oF the input statement, as that’s when the variable name being created ~ ‘epending on havi long the user took taog in The length of time then displayed on the last ine ofthe code, asthe endtime variable. Bpemiome = 3 x ‘This means you'te going to be abe to display ether thecurent ime, orthe time when something ‘eccurted such asa user entering ther name. Try this code inthe Editor import time rane=inputC“Enter Login none: “) printCMelcone”, none, “\d) printCUser:”, nane, “Logged in at”, time. strftime H:2")) ‘Trytocextenditfurthertoinclude day, month, year, and s0 on BEPEET BD theres lot thatcan be done with the Time rmadule, some of itis quite complex too such asdlsplaying the number of seconds since January 1st 1970. Fyou vant to dill down Further inta the Time module then inthe Shel enter-he1pCtime to display the curent Python version help ile For the Time module o ccm EP Manipulating Data Opening Files enue eu Leaman chem eae Car ete ea eee Mae ar Cente ene ROR Stace Senha ines a oe OPEN, READ AND WRITE InPython, you create a ite object, similar to creating a variable, only you pass inthe ile using the open() function. Fi usualy categorised as text or binary. ETT St2rtby entering some textinto your system's tet editor. The text editor is preferable toa word processor, as word processors include background formatting ang ‘other elements. n our example, we have the poem The Cimmerian, byRobert E Howard, and we've saved the leas poem. \Fyou now enter poem into the Shell, you will get some information regarding the tet file you'vejust asked tobe opened, We can now use the poem variable to read the contents ofthe Fle: poen.read() Note than a /nentryin the text represents 3 newline, as wehave sed previous. You use the open Fnceonto pass the eins Glee variable as an object. You can name the file object “anything you tke, but you wil need to tell Python the name and location ofthe text fle you'e opening poensopen(“C:\\Users\\david\ \Docunents\\poem. xt) ‘The eason fr the double slash (is because Python wil read this _as Unicode Error, thinking you've entered: \U-Thisis Windows-only, Lux and Mac worthave ti sue o Fy erter prea second ne, you ue) notice that the text has been removed from the fe Youll need ete poen-openC*C:\\Users\\aavid\\ Dociments\\poem xt) scantorerestetheFie That, fewer ete print(poem.read()) Now the /nenties ae removed in Favour of new inesand Feadable text. - (_ Opening Files ei ‘As wth sts, tuples, dictionaries and soon, you're able ta index individual characters ofthe text Forexample: poen.read¢s) Displaysthe Firs Five characters, while entering; poen.read¢5) ‘illislay the next ve. Entering (1 wil display one character at atime, & Similarly, you can display one tine of text at time by {sing the readline Function. For example. poermopenC:\\Users\\david\\Docunents\\poem. txt") Poen.readlineC) ‘il display the fist ine of the text. And: Poen.readtineC ‘ll isplay the nest tne of text. ow BSPETM extending this further you can use readlinesto cgraballthe lines ofthe text and store them as ‘multiple ists. These canthen be stored as avarable poemopen(“C:\\Users\\david\\Document's\\poen. txt”) Vinesepoen.reodLines() Vines(0} Vines(i} Vines(2} aw for Lines in Vines: printClines) ‘And, since hiss Python, there are other ways to produce the same output poensopenCC:\\Users\\davie\\Document's\\poem. txt") for Lines in poe ‘We can also use the fr statement to read thellines oF text backtous: printClines) ‘As you may suspect, you can pass the readline) Function into a variable, allowing youtocallit again, Bea :\\Users\\david\\Docunents\\poem. txt") Line=poen. readlLine() line BEPET DD (2's imacine that you wanted to print the text acharacter at atime, as would an old dot matrix printer Wecan use the Time madule mixed with what we've looked there. Ty this: import time ppoer=open“C:\\User's\\david\\Docunents\poem. txt") Lines=poen..read() for lines in Lines: print(lines, ende”™) ‘time.sleepC.15) ‘The output ifunto view, and easy incorporated into your own code EP Manipulating Data Writing to Files Ee Ee er stay enter Men a Sar TTI eae eT e etek steel ed of a program to a file, which you can then use to read() back into Python, or as a text file For perusal later. WRITE AND CLOSE “The write() Function is slightly more complex than read(). Along with the filename, you must also include an access mode that determines whether the file in question is in read or write mode. scl opeme CA wd eerie floxng abel (obviously entering your own username location): teopen(*C:\\Users\\david\\Documents\\text..txt”, “w") Thacode vl ete ater fle alten we made ng Theva fibres of tate th ato Cente ore aad ns Cutie -sobe cet FERED ovr ve ssicstcb ssn gsc ERD ores corsicntncncnne oe ‘urtten the line of text tothe fle object, but not committed itto the fle itselt Part ofthe write functions that we needto commit the changes othe fle, we can do this by entering: t-close() \We can now write tothe textile using the write) Function, This works opposite to read, writing ines instead of reading them Try this: t.writeC*You awake ina small, square room. A. single table stands to one side, there is @ locked ‘door in front of you.") Note the 109, t's the numberof characters you've entered (at toe ae ea oe FIR x ow cn wtente wines ED sscsorcisscsitieeersste nee geretetgnn er anentoeen ioe srigaeccaun roe omiaheweentetcni eens (aeuone aw i ay mar He a its, hw (Writing to Fi q ‘To expand ths code, we can re-open the fle using 1, for accessor append mode, Thiswill add any text ‘atthe end ofthe origina ine, instead of wiping the Fle and creating ‘anew one. For example ‘teopenC/hone/pi/Documents/text. txt”, "a") t.writeC*\n") t.writeC You stand ond survey your surroundings. On top of the table is sone meat, ond a cup of ater.\n") aw We can keep extending the text line byline, eng each witha newline (i. When you're one Finish the code with tclose(), and open the file in atext ‘editor ta see the results: t.writeC"The door is made of solid oak with iron strips. It’s bolted from the outside, locking you in, You are a prisoner! tecloseQ) BSPTD Wc can pass variables toa file that we've created in ython, Perhaps we want the value ofPito be ‘written toile, We can cal Pifrom the Math module, create anew file, and pass the output of Pinto the new fil: import math printC*Value of Pi is: “,rath.pid PrintC*\nliriting to a file non.") a pisath.pi Now let's create a variable called pi, and assign itthe value oF i Wie also need to create anew file to write Pi to: ‘teopenCC:\Wsers\\dovid\\Documents\\pi txt”, “W") Remember to change you le location to your own particular system setup, & There ate varoustype of fle access to consider Siery using the open() function, Each depends on how the Fielsaccesed, and even the postion ofthe cor For example, ‘opens ein read and wie an laces the crsor tthe tat of ef FREED och we ness transect changes and close the file: t.writeC‘Value of Pi is: {}”.format(pi)) t-closeC) ‘Asyou cansee from the results, youre able to pass any variable to afle, ) Manipulating Data Exceptions POM ee EI en ean a ec eee ess rl eRe eet ge emcee Mtge N eect tee emer ey two numbers, and they try to divide by zero. This will create an error, and break your code. EXCEPTIONAL OBJECTS Rather than stop the flow of your code, Python includes exception objects, which handle unexpected errors in the code. We 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 report back vith the ZereDivisiontrror: Division by zero message, as sen in the screenshot. The ZeroDivisionfsor part isthe exception class, of hich there ae mary. \We can use the Functions raise exception to create ‘our own error handling code within Python. Lets assume your code has you warping around the cosmos, too much, however, results na warp core breach. Tostop the game from exiting due to the warp core going supernova, we can create 3 custom exception: raise Exception(*warp core breach”) & 5 EEE Mostexcentions are raised ‘automatically when Python ‘comes across something that's inherently wrong withthe code However, we can create our own, ‘exceptions that are desioned to ‘contain the potential eror and Feact tot, 35 opposedto letting the code fall. wabenpubliations.cm EID over ecosmeccnve cece FED oereo tines Mat ns Soneows Lommecorcusmiebnor terse ocmoticentns concrete a ESTED or exemple, using the cvde by zero error we can create an exception where the code can handle the error without Python quiting due tothe problem: try: ‘sintCinput(“Enter the first nunber: “)) beintCinput(“Enter the second nunber: “)) printCa/b) except ZeroDivisionError: printC*You have tried to divide by zero!") else: printC*You didn't divide by zero. Well done!) TED ¥0u can useexcentions to hance a variety of useful tasks, Using an example From our previous tutorials, lets assume you want to open afile and write to try: ‘txt = opent"C:\\Users\\david\ \Documents\\textfile: ext”, tr") ‘txt writeC"This is @ test. Normal service will shortly resume!) except T0Error: print “Error: unable to write the file. Check Permissions”) else: print (“Content written to file successfully. Have @ nice day.”) ‘ext closeQ bv this won worke tothe ie tee Suer ‘being opened as read only (the “r* part). So in this. «case, rather than Python telling us we're doing someting wrong ‘we've created an exception, using the IOError clas, informing the user that the permissions ae incorrect. STE i2tuclly, we can quickly Fixthe issue by changing the read only instance with a"w' forte This, asyou already know, wil create the Fle and write the content then ‘ommitthe changes tothe le, The end result will report a different setof circumstances in this case, 3 successful execution ofthe code. Youscan aio use afinaly block hich woksina Sie ‘Similar Fashion, but you cannot use else with it. Hint: ‘ound to delete the esthet il om your foie: try: ‘txt, = open C:\\Wsers\david\\Documents\textfile. SY try: ‘txt.writeCThis is @ test. Normal service will shortly resune!”) fmally: print (“Content written to fle successfully. Have a nice day.”) txt.closeQ) except TOError: print “Error: permissions”) unable to write the file. Check ‘before an or wai ae we've ted the Siero read-only permission. IF we change itto a “w", then the code wl enecute without the eror being dspayed inthe DLE Shel. Nedless to say, it can bea tricky getting the exception code right the first time. Practise though, and you will get the hang of it we EP Manipulating Data ) UD) Python Graphics MCR ee insta ee eet ome une acc aie there comes a time when a bit of graphical representation wouldn't go amiss. Python 3 eaten tic cen eae iene gets GOING GRAPHICAL ‘You can draw simple graphics, in some spectacular effects. squares and 50 on, or you can use one of the many Python modules available to bring out ETTEEERD One ot the best graphical modulesto begin earning RATE The command trtecirle(S) is what draws the Python graphicsis Turtle. The Turtle module i, as Circle on the screen, with 50 being the size. You the name suggests, based onthe turtle robots used in many schools can play around withthe sizesif you like, going upto 100, 150, and that can be programmed to draw something onalarge piece of beyond: you can draw an ac by entering turle,cincleCS0, paper on the Floor. The Turtle madule can be Imported with 1180), where the sizes 50, But you're telling Python to only draw Import turtle. ‘a0 ofthe circ EEG (ctsbenin by crawingasimplecirce. Start anew — FATES) The astpart ofthe circle code els Pthontokeeo Fil, then enter the Following code: the window where the drawing taking place to a remain open, sothe user canclckto else it. Now let's make a square turtle.circle so) ——= ‘turtle. getscreen(). root. naintoop() print(*Drawing @ square") ‘As usual press FStosavethe code and execute. Thiswillopenupa for t in rangeC4): new window and the Turtle’ wil draw circle. ‘turtle. forward(100) turtle. 1eFt(90) turtle.getscreen().—root .rainloop() ‘Youll notice weve inserted a loop to draw the sides ofthe square, PTEEM To add some colour we can addanewlineto the square code turtle.color¢“Red”) ‘And we can even change the charactrto an actual turtle by entering turtle. shapeC“turtte”) ‘We can aso use the command turtle begin Fill, andturtle.end_ Fill to filin the square with the chosen colours inthis ase, red outline, and yellow PETIT) *syoucan see, the Turtle madule can draw out some prety good shapes, and become ate more comple, asyou begin to master the way works. enter this example: fron turtle import * color(éred?, *yelton’) begin ALLO while True: Forward(200) 1eFeC170) iF abscpos) <1: break end fU10) done tesa different method, buvvery effective * BSPETM Now er’ get the code by imparting the pygame module ‘import: pygane pygare. init, ‘ing = pygane. image. lead(*RP% png”) white = (255, 255, 255) * w= 900 h= 450 screen = pygone. display. setnode((n, h)) screen. flCCwhite)) screen.f1¢Cwhite)) screen. blitCing,(0,0)) Pygone. display. flip) a while True for event in pygane.event.get(): ‘if event type = pygane.QUT pygane.quit© FETED 0 the oreviousstep we've imported pygame, initiated the pygame engine, and asked it to import cur saved Raspberry Pilogo image, saved as APpng, Next, we efined the background colour af the window to dspay the image, and the window size as per the actual image cimensions. Finally, we have aloop to cose the window. w= 900 h = 450 ‘screen = pygame.display.set_mode((w, h)) screen. Fill((white)) screen. Fill((white)) ‘screen:blit(ing, (0,0)) pygame. display. #11p() while Tru for event in pygame-event.get(): af event. type == pygame. QUIT: Pygame.quit() FED other way you can ceplay oraphics by using the Pygame module, There are numerous ways in ‘hich pygame can help you output graphicsto the screen, but for now let's ook at displaying a pre-defined image. Start by opening 2 browser and finding an image, then save itt thelder where you save your Python code. as u Ss | & | ss RETR ress FS to save and execute the code, and your image willbe displayed in anew window. Have @ play around with the colours, sizes and soon, and take time to look ‘Up the many Functions within the Pygame module to. taspberryPi or: (_ Python Graphics ei EP Manipulating Data ) J) Combining What You Know So Far CSE Too ar A Lo) eke Mae cee oD eek A Reo Ln) piece of code that can easily be applied into a real-world situation; or at the very least, something which you can incorporate into your programs. LOGGING IN For this example, let's ook to apiece of code that will create user logins then allow them to log nto the system, and write the time at which they logged in. We can even include an option to quit the program by pressing 'q. LecsbeanbyingernatheTine nee ceaira REESE The abl state septal Sie anew dictionary to handle the usernames and SIEES variable From one that can be called throughout passwords and resting avarableoeaintethecurentstatu ofthe cde thsway we can se the cau element without being the program: changed inside the Function. We've aso referenced some newiy cea >>>>5o>>sLeap Year Calculator BETES You can abo create aprogram that will splay al TES You're also able to print the individual months or the days, weeks, and months within a given year days ofthe week ‘were sure youl agree that’s quite a handy bit of code to have. tohand, hacia wecnatoatbenaniecrdasins ERERE tec nee io anasto the Bere ‘month by using a simple for loop: Sie) Functions in HTML, so that you can display it on a oe vwebate Letsstat by eating soe TB “aepmontney chen Pyonon “Thiscode wil create an HTML flecalled cal, open it witha browser and tdlspaysthe calendar For January 2019. PPT You cansce that code produced some zerosat the BMBINM of course, you can modify that to display given being, this 's due tothe starting day of the vearasa web page calendar: ‘week Sunday in this case, and overlapping days Fram the previous ‘month. So, the counting othe days wil stare on Saturday tstune ‘mort calendar 2019 and wil total 30 asthe output correctly displays yeor=int(input(“Enter the year to display os a ‘nebpage: *)) formatyear(yeor)) cal.close() é This code asks the user fora year, then creates the necessary E ‘webpage. Remember to change your file destination EP Using Modules ) OS Module INTO THE SYSTEM (One of the primary features of the OS module isthe ability to list, move, create, delete and otherwise interact with files stored on the system; making itthe perfect module for backup code. \We can start the 5 module with some simple Functions t see how t interacts withthe operating system environment that Python is running on. IF you're using Linux, corthe Raspberry Pry this: import 0s hone=os.getcndC) primtChone) ‘The returned result, From printing the variable home, isthe current user's home older onthe system. In Step 1 thats /home/p, it will be diferent depending on the username youloginas, and the operating system you use. For example, Windows 10 would output: C\Users\david\AppData\ Local\Programs\python\Python37-32, a TER) wrtcrostorsson PETE The windows outputiscifferent a thats the current working directory of Python, as determined bythe system. As you suspect, the os.getewdl) functions asking Python to retrieve the Current Working Directory. Linux users will see something along the same lines asthe Raspber'y Pas will macOS users, Anotherinteresting element tothe OS module'sits ability to launch programs thatare installed inthe hostsyster. Fo instance, we wanted to launch the Chromium Web ‘Browser from within a Python program we can usethe command: import 0s browsersos.systen(‘start chrome?) BETTE Te 05system0 function iswhat allows interaction [REMPM cing able to manipulate directories, or folders it with external programs you can even call up OU prefers one of the OS module’ best Features. previous Python programs using thismethod. YoUwilobvously For exemple,toceateanew directory yu Can se ‘need to know the ful ath and program file name for eto work successfully However you can also se the following eel —— “Thiscreates anew decor within the specfied Decor (C}20M), er ramed acordng to te objectin the midi Functor (C\BOMNEW). PEPE vou can abso rename any directories youve created byentering FID To showthat the asmodule worksroughtythe Or detetethem, same across all platforms, we need ta specifythe import 0s name of the app according to the O5 on which youre working. For oS. adin(*C=\NBOMNXOLD") ‘example, ona Raspberry you would enter EER voce otic ssw nos BERD cocci wiosane Sosetsbnczonooane nae od roman PEPER Note, inthe previousstep's example the use oF single and double-quotes The single quotes encase the entire command, and launching Chromium, whereasthe double | dst_dir = sre_dir.replace(root_sre_dir, root ‘quotes open the specified page Youcan even use variables to ‘open webpages EP 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. As with other modules, youll need import random before you can use any ofthe Functions ‘we're going to look atin this tutorial, Let's begin by simply printing a Fandom number From 1 to 5 tmorcranen Mirae. : three was returned, However, enter the print Function a Few ‘mare times andi wl splay Aiferent integer values From the set of numbers given, zero to Five. The overalleffec, although paeudorandom, adequate For the average programmer to Uls in theircode, For a bigger set of numbers, including floating point values, we can extend the range by using the ‘multiplication sign ‘import random printCrandon.randon() *100) Will csplaya floating point number, between 0 and 100, to the tune oF around fifteen decimal points RD wscrstoesson However, the Random modle isnt used exclsively For numbers, We can ure toselecta list entxy From Fandom; and thelist can contain anything ‘import random random.choiceC[“Conan", “Valeria”, “Belit™]) This will dsplay one of the names of our adventurers at random, vihich isa great addition toa text adventure game. \We can extend the previous example somewhat by having random choice) select froma of mixed variables. For instance: ‘import random Ist=[“David", 46, “Avengers”, 3245.32, “Pi*, True, 3.14, “Python”) ‘mnd=tandom. choicest) print (rnd) (Random Module Fe ccinsynccnsurshncnwcnie RBA ee ceampeseearoxuhaess ED ocseuaccvtiricicenectn, ease agshtemet ores eheenn revokes ‘This way, you can keep shuffling the lst before displaying a random item From it. BPE sng ste we can ceatean entirely condom it cf numbers for example whine given ange: import random ‘Aste[Li] for I in range(20)] Z ‘random. shuffleClst) BIR :e'san interesting pece of code. Using a text printcist) BMD Fi cresining 466 thousand words we cn pack a wer generated number of words fromthe fe ext le founda Fatsi/othb.con/Gnyenglsh words Keep shuffling thelist, and youll havea different selection of items From 080 20 everytime. o BRTESEDD Wiccan also select a random number froma given range in steps, using the start, stop, step loop: “import random for i in range(10): /— printrandom.randrange(@, 200, 72) Result vary, butyou getthe general idea as to how it works, a EP Using Modules ) Tkinter Module GETTING GUI ‘Tkinter is easy to use, but there's alot more you can do with it Let's start by seeing how it works, and then getting some code into it. Titers usualy ule to Python 3, howeverlF ous? it'savailable when you enter: import ‘tkinter, Lhenyoul need to pips eater rm the command prompt. Uiecanstartto import modules cferent than before. tosave on spin by mooring al ther contents: Import tkinter a5 tk from tkinter import * ERED rouchit'snt recommended to import everthing froma module using the asterisk normally wont o anyharm. Le’ begin by creating abasic GUI window, enter: windsTkKO “This creates smal, basic window. At this point, there's not much ‘else to do but lick the Xin the corner to close the window. BR) wtcrstoeson The dea approach to ad mailoop into the Sule? S) code to control the Tkinter event loop, but we'll eto thatsoon Youve it created Ter widget, and thee ae Several mare ie an ply around benaButtond btn.packQ) bing text™]="Het10 everyone!” The ist tine Focuses onthe newly created window. Click back into the Shall and continue the other ines FETT Wc an combine the above into aNew Fle: import tkinter as tk from tkinter import * btneButtonc) btn.pack() btn[“text*]-"Hello everyonel* ‘Then add some button interactions: def click(: print(*vou just. clicked me!”) benf*connand”}=click (1k terModule @ ES \ Save and execute the code from Step 5, anda ‘window wil appear with Hello everyone! inside, IF you click the Hello everyone! button the Shel will output the tet You just clicked me’. t's simple, but shows you what can be ‘achieved with afew ins of code BRED We can also display both text andimages within Tkinter window. However, only GF, PGM, or PPM Formats are supported. So find an image, nd convertit before using the code, Here's an example using the Raspberty Pi logo: BSTETD Wc can create radio buttons too. Try: ‘And we can create check boxes, with button, and futput tothe hell: The previous code saute weighs mest due to Sieru the content variable holding @ part of Raspberry Pi's ‘About page, om the company website. You an about change the conte the rote and he mage ost your reeds. FETD the code rom Step 9 introduced some new ‘geometry elements nto Tkinter. Note the stiky=N, € and W arguments? These describe the locations of the check 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 Ung odes Pygame Module PYGAMING As stated, Pygame isn'tan inherent module to Python. Those using the Raspberry Pi will already have it installed, Everyone ‘else will need to use pip install pygame from the command prompt. BETIS tually, we need to load up the Pyeame modules into memory before were able to ubise ther. Once that’s done, Pygame requiresthe user to intial it prior to any of the functions being use: import pygane pygone. init) FETED (2tscreatea simple, came ready window and give itatitle ‘gamewindow=pygane..display.set.nodeC(800, 600)) ygane.display.set_coption(“Adventure Gane”) ‘Yu wil notice that after the Fist line i entered, youl need to click backinto the IDLE Shell to continue entering code. In dion, you can change the title ofthe window to anything you like FED sedi, you cant cose the newiy crested Pygame ‘window without closing the Python IDLE Shell vitich sat very practical For this reason, we need to workin the editor (New File) and create aTrue/Fase while oop: ‘import pygane from pygane. locals import * pygane. imit() ‘gamewindowepygane..display.set.modeCC800, 600)) Pygane.display.set_coption(“Adventure Gane") unning=True hile running: for event in pygane.event.get(): ‘if event. type==QUIT: running=False pygane.quitC 2 Pysome Nol BSE che Pygame window stil wont lose, dnt worry it's justa = STEED) econ now implement afew adsitions, and tiie some previous tutorial cade, Thenew elements are inthe subprocess module, of which one Function alows uso launcha ‘second Python scr from within another, and we're going to createa \When we run this code, til display tong, rnatrow Pygame window with the intro text scrolting tothe right. After 2 pause often seconds, then launches the main game Python script, where we can move the warir spre around. Overall the effects quite good, but there's always room Focimproverent. ———— EP 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. Lev starty crating ase bis Mathamatis ous? a Functions. Multiply a number by two or three, and Square or aise 8 number toan exponent (power). Create a New Fle inthe IDLEand enter def timestHoGd: & return x * 2 ' . def timesthreeCx): - return x * 3: def squareCx): return x * x def poner(x,y): “ return x ** y PETISED Uncerthe above code, enter functionsto call, the code: print Ctimestwo(2)) print Ctimesthree(3)) Print CsquareC4)) print Cponer(S,3)) Save the program as basic math py and executeit to getthe resis TER) wrscrostoesson Nowe gong toate fncon defintons Sule?) ‘out of the program and into a separate file. Vighlghtthe function dfntons and chose Eat» cut chooee Fle» New Flan ee E> ast ne ne wins We now vet separate es one wnthefunctoncetinton the ceher th he anton as FETIP vou now ty and execute the basic mathoy code again, the errorName€rror:name'timestw! is rot defined’ wil be csplayed. This is cue to tne code no longer having access to the Function definitions the newly created window containing the Function definitions and ee cickFile > Save As. arve this rminimath.py and saveitin the same location a the axiginal basic math oy program. Now dose the minimathpy window, sothe basi_math.py window is leteopen, (Create Your Own Modules [ BSTESTD Gackt the basic math py window, atthe top ofthe ERIN rinaly, we can now create a ange off statements code enter: todetermine what todo withthe number, and ‘Te Ublsethe newly created function definitions ‘Tis willimport the Function definitions asa module. Press FS to save and execute the program, and see it inaction. ‘We can now make the programa little more advanced, by utlsing the new created module to Itsfull.Letsnclude some use interaction, Star-by creating abasic ‘menu from which the user can choose Nowwe can adhe wer nputtagetthe number SEO the code will work on: ‘punt = imtCinput(*\nEnter number: >) Tis willsave the userentered number as the variable num, a ne ee eee ESTESETBD ote that forthe last avaliable options the Power B . ere ; of choice, we've added a second variable: num2, esti can ncn cali niceentabe lings This passes a second number through the Function definition called |file_fsit_Format_Run 0 ower. Save and execute the programto see tin action ‘Fem mimimach impore © os EMRE ("4.Power of") a choice = input(*\ntncer choice (2/2/3/4):") uml = snt(anpur(*\nznter musbe Introducing eC Introducing C++ Eps fore eD EMEC cr cin) Pee as eT Care Ne Sa Cea eee a MM NU a tes inux, is created using C++. Being able Ree eased Re sme tac PRO en slog) CCRC ue Sou eu eee tant language that's used to develop eerie ecu ete us Eau Pen Ce MEU tc) Dee ucts Beer Cee accor equipment and software needed to get up and running with C++ For Windows, Mac and Linux systems. Why C++? eames Cee eae meu Tc] PolecRe tee Meel eyecare Kenan eM ete uc nl the original C language, and is a general purpose object-oriented (OOP) environment. 100 CEVERYTHING Due to both the complexity ofthe language and its power and performance, C++ is often used to develop games, programs, device drivers, and even entire operating systems. Dating backto 1979, the tart ofthe golden era of home cammputing, C+, or ather C with Classes, was the brainchild of Danish computer scientist Bjarne Stroustrup, while working on his Ph.D thesis, Stroustrup plan was to Further the orginal C language, ‘hich hac been widely used since the early seventies C++ proved to be popular among the developers ofthe 80s since itwas a much easier environment with which to get to aris, and, more impartantly, it was 99% compatible wth the orginal C language. This meant that, beyond the mainstream computing labs, regular people who dicn’thave access to te mainframes anc large computing dete centres could use it. Co1'simpact inthe cial word i immense. Many ofthe programs, applications, games, and even operating systems are coded (C+4 code is much Faster than other programming languages. sing C++ For example all af Adobe's majr applications, suchas Photoshop InDesign and so on, are developed in C+. You wil find thatthe browser you use to surf the Internets writen in C+, 25 wellas Windows 10, Mcrasoft Office, and the backbone to Google's search engine, apple's macOS is written largely in C++ (with some ‘other languages mixed in depending on the Function), and the lies ‘oF NASA Spacek, and even CERN use C+ For various applications, programs, controls, and umpteen other computing tasks, As wall asbeing an easier addition to the core Clanguage, C++ is aso extremely efficient and performs well across the board, Ths bigher level of performance over other languages, such as Python, BASICand such, makes ian ideal development environment For ‘madern computing; hence the aforementioned companies using t sowidaly wv bnoubeatons com 6 Microsof’s Visual Studio isa great, free ‘enviconmentin which to learn C++, S C++ puts the developer ina much wider word of cong By ‘mastering C+, you wil find yourself being able to develop code For the tkes oF Micrasot, Apple and so on. General, C++ developers enjoy higher salary than programme of some other languages, and, due tits versal, the C++ programmer can mave between jobs and companies without the need to relearn anything spec You wil discover, 2s you become 3 more advanced coder, that many ofthe developers in various coding jobs around the world tend to use predesigned development engines. For example, when creating ‘games, the likes of Bethesda the team behind Oblivion and Ski, Uilse 3D game engine called The Creston Engine This enables the team to quickly create animations, characters items, terrains, fooms, and ust about everthing else you'd seein the game. The engine sel has been modified to make the most ofthe current ‘graphics card hardware, and computer or console processing ower. These engines are mostly writen in C+, and when making Indeed, the operating system you're using is written in C++ C Why CH? summary Improvements tothe engine, or when creating new game, iF the developers want to add something thatthe engine can-do, they willuse C++ to create the new content a ink between two dlfferent engines. The end result of course, sa game that contains the latest graphical technology, while being seamlessly bound together with some pretty clever C++ coding, Cetting to use C++ is quite easy, llyou need i the ih st of tools inwhich to communicate withthe computer in C+, and you can start your journey. ACe+ IDE is Fee of charge, even the immensely powerful Visual Studio From Microsofts Freely avalable to New > Empty File, This creates anew, blank window for you to type, FERPD) the Fist time CodeBlocks loads it runs an autodetect fer any C++ compilers you may already have installed on your system. you donithave ay, click the Fist detected option: GNU GCC Compiler and click the Default button toset tas the system's C++ compiler. Click OK when youre ready to continue FEED nthe new window, enter the Following #include Int rain { 7Avy first C++ program Std::cout << “Hello World!\n"; ¥ "Notice how CodeBlocks auto-inserts the braces and speech quotes. FRED) the program starts and another message appears informing you that CodeBlocks i currently not the default application For Ce files. You have two options, to leave everything as itis or allow CodeBlocks to associate allC++ ile types. Aga, we would recommend you opt forthe lst choice, to associate CodeBlocks with every supported fle ype PEAITDD cliccFle» Save as and save the code witha AppStore. nthe Search boxenter Xcode and then turs int ‘Install App. Enter your Apple 1D press Return. There willbe mary suagestions filing the AppStore and Xcode begins to download an install. Itmay take some time ‘window but t'sthe fst option, Xcode thet youneed toclickon, depending onthe speed of your internet connection, Tete airomentto brows trough the aps FEEIR inne intataonisconece leon the Open Imad inclu theconpstity oersure tettontoloanh code locagee toe eee youtaetheconectresioet moe ReadereauresmocOs_temsandente your pasword low Kode oak changes vo ecrlertosa nd woe {athe aston Whenyouve doe ace beste sal additional components. EE wvbenpebicaonscom (Howto Set Up C++ on a Mac ea” ESTED With eversthing now installed, including the STEED the next step asis where tocreate a Git Repository additional components, Xcode launches, displaying for all your Future code. Choose location on your the version number along with three choices and any recent projects Mac, ora network location, and cick the Create button. When that you've worked an although for afresh install this shows blank. you've done al that, you can start to code, The left-hand pane etal the Files usedin the C++ program you're coding. Clckon the rmaincpp file inthe list Welcome to Xcode Bisceemseeees, Suttyngencraterinrcde roth ETRERE Youn see tt Xo atti Bae ‘opens a template window From which to choose the Sie completed a basic Hello World program for you. platfrmyou'e developing code fer chk thernacOStabthen the Thedifereceshee are hat theta futon now coins ammand Line Tool option andl, Nexto conto. tule unetions andthe uti shhty ferent. Th sat, cae ng te contents rae a your Mac. PETTSEDD ili the various fields but ensure thatthe BETTSET BD weer youwant to runthe code, clickon Product > Language option atthe bottom is set to C++ Simply Fun. You maybe asked to enable Developer Mode choose it from the dropdown lt. When you'vefille inthe Fields, on the Mac; this sto authorise Xcode to perform Functions without ‘andmade sure that Cvs isthe chosen language, cickon the Next’ needing yout password every session. When the program executes, button to continue the outputs displayed atthe bottom ofthe Xcode window. wmebrecn EP Introducing C++ How to Set Up C++ in Linux Linuxis a great C+ coding environment. Most Linux distros already have the essential components preinstalled, such as a compiler. The text editors are also excellent Ronen Ue Tm epee ge meee cleat reais EYTeetdi artes 110 LINUX++ For this example, we're using afresh installation of Linux Mint, However, these also work if you're using Ubuntu or any other Debian-based Linux 0S. Tefstsepaenensongirucseaeyeror REED anaunty vats teeing sae fru Sue C++ code is check the system and software are Sues to start coding. Here's how to get your first C++ Upto date. Opena Terminal and enter: sudo apt-get update program up and running in Linux Mintthe main text editor i ed '8& sudo opt-get upgrade Press Return and enter your «an be launched by cicking onthe Menu and typing Xedinto the password, These commands updates the entre system and ary __searchbar. Click onthe Text Ealtor button inthe righthand pane to installed software. open Ned File Edit View Search Terminal Help FETTER ost Linux distros come preinstalled with allthe —— BRBVFB in xed, or anyother text eeitor you may be using, necessary components to stat coding in C+ enter the lines of code that make up your C++ Hello However is always worth checking tosee'f everything ispresent, World program. To remind you, ts: ost ithin the Terminal, enter: sudo apt-get instal build-essential and press Return. fyouhave the right components, nothing installed butiFyoure missingsome then int main) they are installed bythe command. 7 #include /Awy first C++ program std::cout << “HelLo World!\n" Li first cos prosram Seat cea RIES Gortanyes vbnpubeatons com PSTD Wren youve entered yourcode, cick File >Save As BRN efor you can execute the C+ fileyouneedto and choose afolder where you want to save your compile. In Linux's common to use g++, an open program. Name the file ashelloworld «pp, or ary other namejust a5 source C++ compiler and as you'e naw in the same folder asthe long asithas.cpp as the extension lick Save to continue Céfile goto the Terminal enter: g++ helLoworld.cpp and press return, davideomi Fle E&t View Search Terminal Help The est thng you can sees that Xe as ED recess ms ie cee co IES) automatically recognised this as a C++ file, since the Bae ‘by g++ and providing there are no mistakes or Fie extanioninowsetto cpp. Tecolur coding spresrtinthe. eorsnthe code ou ne etune oe cormand pomp. The code and if you open up the fle manager youcan also seethat the compiling ofthe code has created anew fle. F you enter Ls into the Fle'siconhas C++ stamped on it. Teaminal you can see that alongside your C++ file sa.0ut Fle Edt View Search Terminal Help ec) foieeaery) FEED with yourcode now saved, drop intothe Terminal ERNFMBS the aovtfile isthe compied C++ code. Torunthe again. You need to navigate tothe location of code enter: ./a.0ut ad pres Return, The words the Crt Fle youvejust saved. Our examples inthe Documents ‘Hell World” appears onthe screen. However, a.cu ist very Friendly Falder, so we can navigate to by entering: ed Documents. Toname it something else post compiling, you can recompile with: Remember, the Linux Terminaliscase sensitive, so ary capitals must g#+ heLLoworld.cpp -o helloworld, Ths creates an output be entered corectly. File called hellowoild which can be run with: “het Lowor ld, File Edit View Search Terminal Help =>) Other C++ IDEs to Install TC Nee ar Mn nC ceese sr Ma ce Nenmag user m in Meret temas Loa eee) AK eI ed Ua a elo 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. PRTG Ecirseisahucety popuiarc++ DEthat offers PPSRETM Codetiteis free and open source DE that's ED cso rit ees: pete a ee, ‘reat, cleaninterface, ic e85yto use and avalableFor Windows, Linuxaand macOS. i ightweight, uncomplicated and extremely Linux and Mac. Head over to wwweclipseorg/downloads/to powerful. You canfind out mare information aswel as how to ‘download the latest version. you're stuck clckthe Need Help ink download and instal tt www.codelite.org/ For more information. ED Me ourrorermnasndo crsinacouets RETINA even sorsartocesnetscrs Ts Gra and intuitive IDE that supports testing, debugging | GEuenS isanother excellent IDE that’s packed with sdcode nai The Community stents fee uetesstne Fetes anda pesuretouse NetaeenIO= nse projec based Froverson ents hover, the CarsmntyEdtionsavlatle for templates or vs Ut cveyou the ity to Bld appcatons wh Windows ac Lnacandeventhe Raspberry PL Youn fide ae panic and atc rates Pout movet wwwetbear og? vr adocore conjaonnioed Featurs/eppfndexhin ( Other C++ IDES to Install ea” RTETINICSTITOD Microsoft's visual studio sa ‘mammoth C++ IDE that allows you ta create applications for Windows, Andro, iOS and the web. The Community versions free to download and install but the other version allow a free rial period, Go to www.visualstudio.com/ to ‘see what it can do fr you. “Thi cose paformIDE designed to Gre@z wea create C++ applications For desktop and mobi envroment. comes with ode edor andintegited too for teting and debugging, 8 wel 2 deploying to your chosen platform. snot re buttherels tal periadon offer before Fequiring purchasing: www. o/at-teaturestibraries-apistools- andide/. ‘The Anjuta DevStuclo is Linuronly DE that features some ofthe more advanced Features you ‘wuld normally find ina paid software development studio. There's {GUI designe, source editor, app wizard, interactive debugger and ‘much more. Go to wwwanjuta.ora/ For more information. pew ‘ee * TES eesaneengeomnine THis efcolent ID alos developers ise steNe? towrite C++ code for desktop and web appiaonsacosal he major lforms. Thet'san advanced teat editor negated debugger anda configurable workbenchto help you create your code. 's availabe for Windows, Mac and Linux and sree to download and use: wwrwamonodevelop. com. BPSVPSMM sloodshed Dev cs, despite its clourfulname, Isan older IDE thats for Windows systems ony However, many users praise its clean interface and uncomplicated | ‘way of cading and compiling. Although there's not been much Updating fr sometime, t's certainiy one to consider if you want something different: www.bloodshed:net/devepp.html Uimatet+ i cross platform C++ IDE that boasts a rapid development of code through the smart and aggressive use of Cr. Fr the novice i's beast oF anDE but behind Itscomplextyisa beauty that would make a developer's knees 90, ‘abby. ing out more at wrwaltimatepp.org/index.htm. wumbampuctatonscon EES C++ Foundations |¥ Within this section, you can begin to Ronen rnc teerer Ea Reo CEU concen g Ce caer ee to Nu em Lc) CeCe Ls ee Pa eng ‘These are the building blocks oF a C++ SCN eon Mena ie eeu sta} the screen and store and retrieve data. ME tn od mastering C++, and learning howto structure your C++ code will help you eed oe Sesto) Structure of a C++ Program eee scatcy ee) Ter Dee Ce on) =P C+ Foundations) Your First C++ Program MeL foe aN nest Cakes section. Let's begin by writing your first C++ program and taking the First small steps ere emer at honn HELLO, WORLD! Its traditional in programming forthe First code to be entered to output the words ‘Hello, Worl to the screen. Interestingly, is dates back to 1968 using a language called BCPL. FETED 2s mentioned, we're usina windows 10 andthe PEED 2% che moment t doesnt look ike 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:Blocks. When open, click _ in due couse, Now dick File» Save Fle s. Create or find 2 ‘on Fle > New > Empty File or press ClileShfteN on the keyboard. suitable locaton on your hard crve and in the Fle Name bo, call ithelloworld.epp. Clckthe Save as type box and select C/C++ les. Clckthe Save Butta, PEPISED) Now you can see ablank screen, with the tab BETTI You censee that Code:Blockshas now changed labelled “Untitled, and the number one inthe top the colour coding, recognising thatthe le isnow left of the main Code:Blocks window. Begin by clicking in the main C++ cade. This means that code can be auto selected from the ‘window, so the cursor isnext tothe number one, and entering CodeBlocks repository. Delete the finclude ine and a reenter it You cansee the auto-elect boxes appearing. wm broscon / (Your First C++ Program ei” \ line 3, then enter int rain Notethere’s no space between the brackets Pinel aa Sine mee. 5 COnthe next ne below int main), entra curt bracket: £ ‘Thiscan be done by pressing Shift and the key tothe ight af Pon an English UK keyboard layout peinwiaieia: blo ‘uto-selection of commands s extremely handy and Cuts out patential mistyping, Press Returnto get to Note again the colour coding change. Press Return at ae) BED esicsccsiniesnese it << “Hello, world!\n"; air eee ces n | nme Bea Just as before, Code:Blocks auto completes the Code you're entering, including placing a closing speech mark as soon as you enter the fist. Don forget the semicolon a the end ofthe ine; this sone ofthe most important elements to.aC++ program and weiltellyou why inthe next section. For now, move the cursor down tothe closing curly bracket and press Retumn. j[xealgalors: lis ie elaaieta «hie ay alewece tue emis Bie = fd Gy BETTER otis thet CodeBlocks has automatically created corresponding closing curly bracket a couple of lines below, inking the pai, as wellas sight indent. This's due to the structure of C++ and ie where the meat of the cade is entered. Now enter: Uy frst C++ program BETET BD thet allyou need todo forthe moment. it may ‘ot look teribly amazing but C++is best absorbed in small chunks. Dont execute the cade atthe mament es you need tolook athowa C++ program sstruetuted st then you can bull and runthe code. For now, click on Save, the single floppy disc icon, =P C++ Foundations) Structure of a ee tele C++ has a very defined structure and way of doing things. Miss something out, even as small as a semicolon, and your entire program will fail to be compiled and executed. ENE noc umiete ae o Meares #INCLUDE Learning 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. an #INCLUDE “Starthere | *helloworld.cpp | The structure of aCe prgeam isqute rece. Every Cr+ code besins witha directive wncude ©The drectve ntuasthe pre pracssorto inde Eectonof the standard Co (C++ wasiovented by Danish include student Bjame Stroustrup in 1979, a5 apart of his PhD. thess.Intially C++ as called C with lasses, which ded Featurestothealeady popular? code. For example: #incude Crogramminglonguese, slostream> inclues the whle making amore iortream header to support User friendyensronment input/output operations E dhrowhanewsivaue Bjarne Stroustrup, inventor INT MAIN() [Starthere | *helloworld.cpp | Int maing initiates the eciration ofa Function, which isa group of code statements under the name ‘mai’ Al C++ code begins at the main Function, regardless of where it actually ies within the code. #include int main() 1 2 3 4 s é BRACES The open brace (cry brackets) s something that you may nothave come across befor, especialy ifyoure used toPithon. The ‘open brace indizates te beginning ofthe ‘main Function and contains all the code that belongs to that Function, include int main() r 2 3 4 5 é EID wvbenpebicatonscom COMMENTS Lines that begin witha double lash are comments, This means they ‘wont be executed in the code and are ignored by the comple. Comments are designed to help you or another programmer looking at your code, explain what's going on. There are two types ‘of comment: /* covers mutiple ine comments, / single line. Lines that begin with adouble lash are comments. The 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 C Structure of a C++ Program ei” << The two chevrons used here are insertion operators, This means that whatever follows the chevronss to be inserted into the stdscout statement. nthis case theyre the words ‘Hello, world, “ich are to be displayed onthe screen when you compile and execute the code, STD ‘hile std stands For something qute different, in C++ it means ‘Standard. spat ofthe Szandara Namespace in C++, which covers ‘anumber of afferent statements and commands. You can leave the ‘dz part out ofthe code but it must be declared atthe stare with: using namespace std; not both. For example: include using nanespace std; Lees COUT Inthis example we're using cout whichis apart ofthe Standard Namespace, ence why its there, asyou'e asking C++to ust from that particular namespace. Cout means Character OUTput, which splays, or prints, something to the screen. we leave std out we have to declare it atthe stat ofthe code, a: mentioned previous 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, as long asi’ inside te quotation marks. The brackets aren needed but some comple insist on them. The \n pat indicates a rewrline isto be inserted. cout << "Hello, world!\n"™ ;AND} Finally you can see that ines within aFuretion 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 lat ine hasthe sing brace to indicate the end of the main Function. ‘Vinclude ‘using namespace std; Ant main () Bc cout nt main() cout << Melia, world!" =P C++ Foundations ) Compile and Execute Nene Ne deet ren Mr een cee on rs structure of one. Let's Meee Eu eesteReatang Nese eet ene ea ais cr 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) ven CodeBlocks if you havent already, and BSTISED Sart by clicking onthe Build icon the yellow cog loadup the previously saved Hello World code you Atthispoint, your code has now been run through created. Ensure that there are no sible errors, such as missing _the CodeBlocks compiler and checked For any errors. Youcansee semicolons at the end of the std:cout ine. the rest of the Build by looking to the bottom window pane. Any messages regarding the qualty ofthe code are displayed here. - Buidlog | Build messages x /) CppcheckVe in “no project” (compiler: unknown) === 5), 0 warning(s) (0 minute(s), 0 second(s)) cies BSTESED | yourcode's looking similar to the one in our BEPEPD Nove cickon the Runicon, the green pay button. screenshot, then look to the ment bar along the top ofthe screen. Under 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, Run, Bulld and Run Functions ‘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. Build Debug Fortran waSmith tmalaaiorsen Pel s<| DING d © ho x X | starthere x *heloworldcpp Tools Took Plug FED wvbenpebicatonscam FETED Pressing anykey inthecommandiine boxclosesit, BRM create a deliberate erorin the cade, Remove the returning you to Code: Blocks. Lets alter the code semicolon from the cout ling, ot ead: slighty, Under the include line, enter Pe using namespace std; Starthere x Then, delete the st: part ofthe Cout ine; tke so: cout << “Hello, norld\n"; 2 using namespace eta 3 BED ine ming tincnee ovecan cB ay meer ; sor maint) 7 1] cout << tHeito, woria!\n" 8 _ Sach poe 2 , =" 10 nh 2 Inorderto appl the new changes tothe code, sou Now ck the Bud and Run ikon again to app the Sree need to re-compie, build, and run it again. This time, Siz) ‘changes to the code. This time: ‘ode:Blocks refuses however you cansimalyclickthe Buld/Run icon the combined to execute the code, due tothe error you putin. nthe Log pane at yellow cog and green play button the bottom ofthe screen you are informed ofthe ecor, this ase: Expected Y before ' token, indicating the missing semicolon, BETTER staswementioned inthe previous pages, you BSMINB replace the semicolon and under the couttine, don't need to ave std:cout I you already declare enter a newline to your code: using namespace sta the beginning ofthe code. We could have easly icked the Buliun ian to begin with buti’s worth going cout << “And greetings from C++!\n"; through the available options You can aso see that by building and The \nsimply adds new line under the last ine of outputted text. running the le has been saved ‘Bull and Run the code, to display your handiwork, sous. Soom 1) eae =P C++ Foundations) Using Comments ON eel urate RCTS aN eked ard combine to make a game, application or even an entire operating system, in actual Fact they're probably one of the most important Factors. THE IMPORTANCE OF COMMENTING Comments inside code are basically human readable descriptions that detail what the code is doing at that particular point. They don sound especially important but code without comments is one oF the mary frustrating areas of programming, regardless of whether youre aprofessional or ust stating out In short, all code should be commented in 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| ‘bout programming can pick up your code and understand what t's {going todo simply by reading your comments Ina professional environment, comments are vital to the success ofthe code and ultimately, the company. an organisation, many programmers workin teams alongside engineers, other developer, hardware analysts and so on Fyou'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 hasto pick up and Follow the tral to pinpoint the issue. Place yoursel'n the shoes of someone whose jb itis to find ot ‘what's wrong with a program. The program hasin excess of 800,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 wien the program hits this line or section, Yousor'tneedto comment on every line. Something | along the lines of ifx=-0 doesnt requiceyouto commentthat Px equals zero then «do something that’s goingto be obvious tothe reader. However, Fx vbnpubeatons com equalling zeros something that drastically changes the program for the ser, such as, they've run outf lives, then it certainly needsto| commented on Evenif the code is your own, youshould write comments asf you ‘were going to publly share it with others. This way you can turn 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 how toad comment where needed, you soon dots if it’s second nature ceEEEEEY peecey: seogees bySps coeggee y ( Using Comments ei” C++ COMMENTS Commenting in C++ involves using a double Forward slas brief examples but this is how they work. BTTEEEDD Usa the Helio world codeas an example, you can ERTESIABB) Ge careful when commenting, especialy with block «easly comment on afferent sections ofthe code comment.’ ery easy to forget to add the dosing Using the double Forward sash asterisk and forward sash and thus negate any code that fallsinside My frst C+ progean the comment block cout << “Hello, world!\n" fr a forward slash and an asterisk, You've already seen some Ttinsiase coarse 2 ine matac) Bap) oe ratte atin, Hower yucnatoaatonnenstotiewe — ERRERE obvaytyor nd dd angencstete Suere of a line of code, to describe in a better way what's Suze code it errors out, complaining of a missing curly sein on bracket tinh off the block of code youve made the ce “HeLToy world! \n"s°//THLS Tine outputs the 7% 2Fedtimes then itcn be time consuming to gobackand fords "Hello, portal" The \n-denotes armen Lines 'et® "Tartu the clourcedngnCode:Stacs haps tenty Note, youdon'thave to puta semicolonat the end ofacomment, ‘Tis is because i'sa in in the code that'signored bythe compile. jl PEPESED You can comment outseverallines by using the STEED |" y0u'e using black comments, it's good practise Forward slash and asterisk InC++ to addan asteriskto each new line ofthe aoe a ‘comment biock. This so helps you to remember to close the SSS comment biock of before continuing with the code without the need to add more slashes */ /* This coment can * cover several. lines _Justrememberto finish the black comment withthe oppaste : “ SS ee without the need to add more slashes */ peso pene is 1 mbinosiciccn =P C++ Foundations) Variables NAG e MCU ere lor niet) simply state that ‘a’ equals 10 and a variable is assigned. However, in C++a variable has Reakesecae het lc igeten ltt 124 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, Coenipanen.binkCorReanderer evs — ETREB ou anbutdndnnine cotter do Sie code headers: Sige much, other than store the values 10 and 5 to the | integers a and b. To outputthe contents ofthe variables, add #include using namespace std; cout << a5 cout << "ns int nang —— . cout << b; ‘ina anceps 2 i The cout e<"W part a simply paces new ine between the output of \ Seiwe > vormthscoy foes ms BETTER Sertsimpleby ceating twovariables,aand6, with BREF naturally you candeclarea new variable, calit fone having value of 10 and the other 5. You can result and output some simple arithmetic: use the datatype intto declare these variables. within the curly 5 brackets enter EEG result = a + bs int 0; cout << result} int bi = = = fren emcee Insert the above nt the code as pr the screenshot. b= 5 vbnpubeatons com BETTE You canassigna value ca variable as soon asyou declare The code youve typed in could ook like this, insteae: int o = 10; int b= 55 int result = a +b; cout << results PD specific to C++, you can also use the fllowing toassgn values toaverable as soon as you declare them: int @ C10); int b (5); hen, fram the C++ 2011 standard, using curly brackets: int result fosb}s BSTTSERD You can create alobal variables, which are variables that are declared outside ary function and usedin any Function within the entice code, What you've used soar are local variables: variables used inside the Function For example include using namespace std; int StartLives = 3; int nain © { stortLives = StartLives = 1; cout << Start ives; BPEIM The previous step creates the variable StartLives, \whichisa global variable. Ina game, for example, player's ives 90 up or down depending an haw wel orhow bed theyre doing, When the player restarts the game, the StartLives return tits default state: 3. Here we've asigned 3 Ives, then subtracted 1 leaving 2 ives lef, BSED the modern c++ compilerisFarmore intelligent than most programmers give credit. While there are numerous datatypes you cand Fact use the auto feature: For varia 5, you canin Binclude using namespace std; auto pi = 3.141593; Ant rain { double area, radius = 1.5; area = pi * radius * radius; cout << area; ‘couple of new ements hete rst auto wot SuzP HD ‘work unless you go to Settings > Compiler and tek the boxlabeled Have Gre fli the Cet SO Co Language Standard (stdecet), Then the new datatype, double, which means covbleprecsion fostng point vse Enable Ces, then Build andrunthe code The res shouldbe 706858. =P C++ Foundations ) Data Types Variables, as we've seen, store information that the programmer can then later call up, PR en tae ieem Ane Cen ea gre arta cele eset Ree cue ee Cn et ceten etter THE VALUE OF DATA “There are many cifferent datatypes avalable forthe programmer In cre, suchas an integer, floating point, Boolean, character and so cn. I's widely sccepted that there are seven basic datatypes often called Primitive Builtin Types: however, you can create your wn datatypes should the need ever arise within your code “The seven basie datatypes are: aada Se?) 3 ii Floating Point Ce on etcnceieas iene No Value “These basictypes can also be extended using the Following modifiers: Long, Short; Sianed and Unsigned. Basically ths means tne mocifiess ‘can expand the minimum and maximum range values fr each data pe. For example, theint datatype has a default value range of 21474836480 2147483647, afairvalve, you would ares, g Now ifyou were to use one ofthe modifiers, the range alters 020 4294967295 2147483648 02147403647 32768 to 32767 £065,535, Signed Shor. int =-32768 to 32767 147493647 to 2147483647 147483647 to 2147483647 £0 4294967295 "Naturally you can get away with using the basic type without the ‘modifier, as there's plenty of range provided wit each data ype. However, is considered good C++ programming practise to use the ‘moifiers when possible. “There are issues when using the modifiers though, Double represents a doublefloating point value, which you can use Fer FED wvbenpubicatonscom incredibly acurate numbers but those numbers are only accurate Uuptothe fifteenth decimal place. There's als the problem wien using nanespace std; double PI = 3.141592653589793238463; int rain { cout << PIs z sing namespace sta [ doubte Pr = 3.141582 3 5 _ tnt mini) 6 a cout << PI e ° 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; Aint rain { cout. precision(22); cout << PI; Again, build and run the code; as you can see fom the command lie window, the umber cepresented by te variable Pis ferent ta the number you've told C++ to use in the variable. The output reads the value of Plas 3.141592653580793115998, withthe numbers going awiy from the ites Calculator = Scientific 15.142857142857142857142857142857 DEG HYP FE Memos sf xi Pisin’ [Ecos | ten v 10* log Exp Mod *. cE c a re ma 7 | 8 | 9 fee rom 4] 5. | 6 fe at. | 2) | 3 ie ¢ d oO : This is mainly due tothe conversion From binary inthe compiler and that the IEE 754 double precision standard occupies 6¢-its| of data, of uhich 52-bitsare dedicated tothe sigrifcan the significant cits ina floating poinerurnber) and rough 35-bit are taken holding the values 009. I you dvide 53 by 3.5, then you ative a 15142857 recurring, which 15-diaits oF precision, Tobe honest, IF you'e creating code that needs to be accurate to ‘mare than fifteen decimal you wouldn't be using C+ you would use some scientific speci anguage with C++ asthe connective tissue between the two languages. You can create your own datatypes using an alastike system called typedef. For example: ood #include using namespace std; typedef int metres; Aint raing { rnetres distance; distance = 15; cout << “distance in metres is: “ << distance; Thiscode when executed creates anew int data metres. ‘Then in the main code block, there's anew variable called dit vihich san integer; sa you're basically telling the compiler tha there's another name for int. We assigned the value 15 to distance and displayed the output: distance in metres 15. Iemightsaunda litle confusing ta begin with but the more you use (C++ and create your own code, t becomes. =P C+ Foundations) Strings Rae ena en eet cea ec aT could have a universal greeting in your code ‘Welcome’ and assign that asa string to be eee Merely ice icam rs STRING THEORY ‘There are different ways in which you can create a string of characters, which historically are ll carried over From the original language, and are still supported by C++. Tocreasrgyouse ech fcton Ooene ETERS outs endnnth code and ween soe Sed new C++ file and begin with the usual header: SUE) ‘onthe screen. While this is perfectly Fine, it's rot astring.Astring isa class, which defines cbjects that can 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 t using namespace std; ' int main © Aajorson 3 t a8 ‘char greet[] = “Welcome”; cout << greet << “\n"; } ESTISED 5 e2syt0 confuse string with an array. Here'san BRIBE in c++ there's also a string Function which works in array, which can be terminated with all character: much the same way. Using the greeting code again, include = using namespace std; i int rain ©. char greet[8] = {'W?, ‘e’, “1, *?, ae te, NOK: string greet = “Welcone”; ‘cout << greet << “\n"; cout << greet << “\n"; } 5 vbnpubeatons com ERED Tere are also many diferent operations that you can apply with the string Function. For instance, to get the length of astring you can use: include using nanespace std; Ant rain ©. { int Length; string greeti = “Hello”; string greet2 =“, world!"; string greet3 = greet + greet2; length = greet3.sizeQ; cout << “The Length of the conbined strings is: * << Length << “\n?s + Uso the avlabe operas that ome th the Siz) ‘string Function, you can manipulate the contents of @ string. For example, to remove characters rom sting you coud ue: #include using namespace std; int nain © { string strg (“Here is a Long sentence in a string.”); cout << strg << ‘\n"s strg.erase (10,5); cout << strg << ‘\n"s strg.erase (strg.begin()+8); cout include using namespace std; int wain © { ¥ Sotiee “Mate getting the square roat ofa number: include include using namespace std; int nain © { float nurber = 134; cout << “The square root of “ << nunber << is: * include using namespace std; int rain © { float nunber = 12; cout << number <<“ to the poner of 2 is “ << onCnunber, 2) << *\n” cout << number << “ to the poner of 3 is * << on¢runber, 3) << “\n"; cout << number << “ to the poner of .08 is << powCrunber, 0.8) << “\n"; t RTI Here we ceated a float called rumber withthe value oF 12, and the pow variable, the calculation happens. OF course, you can ealulate powers and square roots without using variables. For example, pow (12,2) fcutputs the same value as the First cout linein the code, FERED the valuc of Pic also stored in the cmath header Ura. tan be called up withthe M PI Function. Enter cut << M_Pf into 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"; C++ Input/Output There's a satisfying Feeling when you pee ee ete ace aad ere ed Serna eee g ens Dee eee EEO EEE) message, it's a big leap forward. See ee Car om Seen ee) output are all covered in the following Perea me Sr Me nek mace Lees See carte) Prien mnie tg Te meaner Pee) PE eme eee ce Penne Lecee nS File Input/Output ) C++ Input/Output) User Interaction There's nothing quite as satisfying as creating a program that responds to you. This ee esa eet ete geese Mee eee Meet ee hls Noted tem neicdtie mre 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. Anything that you want the user t input into the program needs to be stored somewhere inthe ‘system memory so canbe retrieved and used, Therefore, any input must Fst be declared asa vatabl, soit’ ready tobe used by the user. Start by creating a blank C++ ile with headers. Fincluge int main () ERTS The datatype of the variable must also match the type of inputyou want From the user. For example, toaska user theirage, you would use an integer tke this: include > age; cout <<"\nYou are “ << age << “ years old.\n"; wm broscon EETSEDD Tein command worksin the opposite way from the cout command. With the Frstcoutline you're ‘outputting ‘What is your ag’ to the screen as ndcated with the ‘herons. Cin uses opposite Facing chevrons, indicating an input. The inputs putinto the integer age and called upin the second cout command, Buld and run the code. If you'e asking a question, you need to store the input asa string; to ask the user their name, you would use include using namespace std; int rain © t string none; cout << “what is your name cout << “\nello, “ << nane <<“, I hope you're ‘wel today?\n"; a = Tsaepa eye. ~ sian FETESEM The pxncioal works the same asthe previous code. The usersinput, their name, stored in string, because it contains multiple characters, and retrieved in the second «outline. As longas the variable name’ doesnt change, then you ‘can recallt wherever you like in your code. include > num >> rund; cout << “you entered * << num <<“ and << rund << *\n" Lkewienpttd at can be manus once Siary you have it stored in a variable. For instance, ask the user fortwo numbers and. do same maton them include Using nanespace stds int rain © { float nun, num: cout << “Enter tno numbers: \n"s cin >> num >> num2s cout << num << + uml + rund << “\n"; << numa << * 4 “ userinteraction QRS PEPER wile cin works wellfor most input tas, does havea invtatin, Gn always considers spaces asa terminator, soi’s designed for just single words not multiple words. However, getline takes cinas the ist argument and the variable as the second #include using namespace std; int rain © { string mystr; cout << “Enter a sentence: \n"; getlineCcin, nystr); cout << “Your sentence is: characters. 1ong.\n"; “ ce mystr.sizeQ) < uid andexeete the code, then enterasentence Sui with spaces. When you're done the code reads the numberof characters you remove the gate Ine and replace vith cin» mye and ty again, the esl doy the number oF characters up tothe frst space FETED DD etine is usualy acommandthatnew c++ programmers forget to include. The terminating white spaces annoying when you cant igure out why your code Isnt working. In short, it's best to use getline(cin, variable) in future: #include Using nanespace std; int rain © { string none; cout << “Enter your full mane: \n"; getlineCcin, name); cout << *\nHlello, << name << *\n"; ) C+ Input/Output Character Literals In C++ literalis an object or variable that once defined remains the same throughout fier ae aera etka ee etec eet eta UN nh Peaeneraciierereecucad nine e rn as ESCAPE SEQUENCE When used in something like a cout statement, character literals are also called escape sequence codes. They allow you to Insert a quote, an alert, new line and much more, FETED Cieztca new c++fileand entertherelevant headers: PRISM 1r you wanted to insert speech quotesinside cout statement, you would have to use a backslash asit include int main O using namespace std; { int nain © { i ‘cout << “Hello, user. This is how to use Vequotes\”.*; cov oweuuelil Teesadjooncnette ncaa EERE Towson» cata naga blade placing a new line wherever it’s called. The line: cout Sum alarm. in Windows 10, it’s the notification sound s="Halo\<<"fmaroy using nanespace std; int main © { cout << “\u00A9"; UNICODE CHARACTER TABLE plete list ofthe avaliable Unicode ers canbe found at wwwaunicode- table-com/en/. Hover your mouse over the character to see the unique code to enterin 23s you wll proba it for reference a and indeed chara thing, the From efferent a oo Single Quote Eocene ce ene Sao fiers Unicode (UTF-8) Unicode (UTF-16) hat can byALTAX across % copyright symbol enter: 0049 AltsX. In C+ code, you 2 | C++ Input/Output) Defining Constants eee hen Men ee eis et Peete ect in et rcnsemaahete neta utenti ker mucin) Rea ecient een Ce Cine keer Tea #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. FTE You canusethesdefine preprocessorto define any EATEN Note the capitals fordefined 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 include lets callthern up: using namespace std; #include using nanespace std; int rain © i define LENGTH SO define WIDTH 40 + define HEIGHT 60 x int rain © me Winslade closeream> 1 samen ‘cout << “Length is: << LENGTH << “\n' toe tn 0 cout << “Width is: “ << WIDTH << “\n"; cout << “Height is: << HEIGHT << “\n"; TEED Now let's assume your code hasthree diferent constants: length, width and height You can define them with include using namespace std; ‘#define LENGTH SO define WIDTH 40 ‘define HEIGHT 62 ‘define NEMLINE *\n” int rain © { ‘cout << “Length is: “ << LENGTH << NEWLINE; cout << “Width is: “ using namespace std; ‘define PI 3.14159 int rain © { ‘cout << “The value of Pi is: * << PI << endl; (_ Defining Constants ec BRPETD srother method of defining aconstantis with the 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 you're using const within the main block oF code, youneed to finish the line with a semicolon You can use ether, as long asthe names and values don't lash, but lesworth mentioning that #define requires no memory, sof you're coding toa set amount of memory, Hdefine's your bes bet. Const works in much the same way as #define You can create static integers and even newiines: #include using nanespace std; nt rain { ‘const int LENGTH = 50; ‘const int WIDTH = 40; ‘const char NENLINE Ants ‘int area; ‘orea = LENGTH * WIDTH; cout << “Area isi “ << area << NEWLINE; ) C++ Input/Output) File Input/Output The standard iostream library provides C++ coders with the cin and cout input and Cie tata et ace ne Eu hau Net cd utilise another C+ library, called Fstream. FSTREAMS ‘There are two main data types within the fstream library that are used to opena file, read from itand write tot; these are cofstream and ifstream. Here's how they work. Trefatinkstocenesnewcefiesnsore ETREEB wevercttedconmens nthesceensetot sen ue" with the usual headers you need to include the new SUE?) 2 to help you understand the process. You created Fetream header airing clled name, to store the users inputted name. You also sinudeRctostrens Cceated a text ile called name tt (withthe ofstream newfie and Ainaetstoae rewiile.open tines), asked the user for their name and stored it and then writen the data to the le, Using nanespace std; int rain © Vncine tacieae Toreadthe contetsof fle and output tothe ae me, OH Suze ‘screen, you need to do things slightly differently, L Fist youneedtocrestea string arabe to store the ls contents a {ine byte} then open the fl, ze get to ead hel ine by tne and output those ines tothe screen Final close the ie. Seginby aking ver for their nae and wing string Lines Sie that information to a file, You need the usual string ‘ifstream newfile “name. txt"); tostorethename, and elie to accept telnp om the er include ‘cout << “Contents of the file: “ << endl; ‘include getline(newfle, Vine); using namespace stds Sree aREIN int main © t string nae; ofstrean newfte; henfile.openC*nane. xt”; , cout > ages newfile << age << endl newfile.close(; FEED) the code from step 8 ciffere again but oniy where itcomes to adding the age integer. Notice that we used cin age, instead ofthe previous getinecn, vara The reason For thsi thatthe getline Function handles strings, not Integers: so when you're using a data type other than astring, use the standard cn, BRED ce san exercise: se you can crete code to SHEP HD write several different elements toa text file. You cane ause’sname, ge phone number ete Maye even the tlue of and verousmatheneteaelements al good prac ye ae cn you ene we wombampbtiatonscon Ez ; a Peres ae ad Dee eee ei eu Perens oe teri a program that delivers the desired Pees ee ee Res issues or errors. Ree ee un) See ce ee unZe never be able to offer the user any choice. Tet ened elevates your skills as a programmer and Beet ese Creating a successful loop gives the code Bau a ee eta pee eC cae ced US eee cue Eu eset ym ae - Paty yc ee ae ors ese Cra ees 144 Loops and Decision Making While Loop Awhile loop’s Function is to repeat a statement, or a group of statements, while a certain condi eM Ue ee Laan ten daca) ee eee nance aad alo TRUE OR FALSE? While loops are one of the most popular form of C++ code looping. They repeatedly ru code contained within the loop while the condition istrue. Once it proves False, the code continues as normal Clear whatyoive dane sofaran cesta ew Co ous? a file, There’ sno ‘need for any extra headers at the ‘moment, s0 add the standard headers as per usual: include using nanespace std; int rain O i ¥ Create asi err while loop Enter the code below, bull and run (we've added commentsto the { int nun = 1; while Chum < 30) i cout << "Number: * << nun << endl; pun = num +13 z return 0; ¥ Gee create acondton, 30 We 8 Variable cled num and give tethe vale 1, Now create the wileoop, tating that aslong asrum slesthan 530,te oops tue. Within the loop te value of num is spayed and adds ull iesmore than 30 BEEP vic introducing a few new elements here, The Fist ae the opening and closing braces for the uiile loop. Thisis because cur loop isa compound statement, meaning a group of statements; note aso, there's no semicolon after the while statement. You now aleohave return 0, which fsa dean and preferred way of ending the code EID you did't need to see the continually increasing value of rum, you could have done away with the compound while statement and instead just added num by iselF Lunt itreached 30, and then cisplayed the value { int num = 1; white Crum < 30) cout << “Number: * << num << endl; return 0; ¥ ESTEE ''simportant to remember not to add a semicolon atthe end ofa while statement, Why? Well as you know, the semicolon represents the end of @ C++ Ine of code F you place one atthe end ofa while staternent, your loop wil be permanently stuck untl you close the program PITA | our example, fwewere to execut the value of num would be 1, a5 bythe int statement. When the code hit the while statement reads that while the condition of 1 being less than 30'strue, oop. The semicolon closes the tne, 50 the loop repeats but itnever adds 1 to rum asit won't continue though the compound statement. he code You can manipulate the while statement to display ifferene results depending on what code les within the loop. For example, to read the poem, Cimmeria, word by word, youwould enter include using namespace std; int rain ‘ string word; ifstrean newfle (“C:\\users\david\\ Docurents\\Cinmeria. txt” cout << *Cinmeria, by Robert £ Howard: \a” << endl; while Chewfile >> word) 4 cout << word << endl; ? return 0; ‘ whileLoop QS STEED You cen further expand the cade ta enable each word ofthe poem to appear every second. To do 50, you need to pullin anew library, include windows. using namespace std; int rain © { string word; ifstrean newfie (“C:\\users\\david\\, Docunents\\Cirmeria. txt”); cout << "Cinmeria, by Robert E Howard: \n? << endl while Cnewfile >> word) i cout << word << endl; Steep(1008); return 0; EERIE DD sice0 works io miliseconds, so Sleep(1000) is ‘one second, Seep(10000) ten seconds and so fon. Combining the sleep function along wth te headerit needs) anda while loop enables you to come up with some interesting ‘countdown code. #include include using namespace std; int rain © t int a = 10; while Ca != 0) i cout << a << endl; a=0-1; Sleep(a006: ? ‘cout << *\nBlast OFF!” << endl; return 0; Eq Loops and Decision Making For Loop Teeter Tod ose aE structure is different. A for loop is split into three stag incremental step. Once set up, the loop repeats itselF until the condition becomes False. NEEL Oe Mace tied 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 seeiFits true or False and then the increment is executed. The loop then repeats the second and third stage. Ba include using namespace std; int rain ©. 1 Create anew C++ 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 its, the second and third stages ofthe loop, tadds 1 untithe condhtion<30, Is false. The loop then ends andthe code continues, ending neatly with return 0, ¥ for( int mum 20; mam = num 42) pepe cout << Mamber: * << num << endl rT return Startsimple and create a for loop that counts from 1 t030, displaying thevaluetothescreenwith es ‘each increment ERED or loop is quite a neat package in Crt all { contained within its own brackets, while the other U/For Loop Begins elements outside ofthe loop are displayed below. F you want to forC int num =" num/<)30;inum/SnUMFID ——_eatea 10-econd countdown, you could use: 4 ‘#include cout << “Naber: nunber; sun += numbers ? whileCnunber != 0.0); coutce? Total sum of all numbers: “< Eq Loops and Decision Making IF Statement The decision making statement ‘if’ is probably one of the most used statements in any programming language, regardless of whether it’s C++, Python, BASIC or anything else. It represents a junction in the code, where IF one condition is true, do this; or IF it’s false, do that. IF ONLY IF uses @ Boolean expression within its statement. Ifthe Boolean expression is true, the code within the statement is executed. IF nat, then the code after the statement is execute EPID Firs createannew C++ file and entertherelevant standard headers, as usual Finclaae clostream> ‘using namespace std; include > temp; if Ctenp <= 0) { cout << “\nBrrer, it’s really cold!” << endl + if Ctenp > 0-9 cout Eq Loops and Decision Making IF... Else Statement There is a much better way to use an if statement in your code, with if... else. I... else Pee eu OE een ieee a accion is true, the code within the braces is executed. Else, the code within the next set of Pte ele IF YES, ELSE NO ‘There are two sections of code that can be executed depending on the outcome in anif visualise once you get used tots structure. . else statement. t's quite easy to BETTS DD cesinwithanewce+fileandthestandardheaders: MMM the Fist ine in the code creates the integer called ‘pum and givesit a value of 1. The statement incuneraostrens | check to see the value of num sles than tity and ise Eee cutputsThe number fessthan 30" to the console int rain © : —— ‘ : ee ee 2 a Seer EL BB RBB Ip tre ccecompaniontof cece ithe number EMG (<' cr92ndthe code from the statement onthe EE isgreaterthan 30 andifso, then displays “The ¥ Lats ‘number is greater than 30!” to the console; and finally, the code is t terminated satisfactorily. sine) cout << "The mumber is less than 30!* << endl if Cum < 30) = a —EEeEeEEeeEe ee ee a BER con charge the ote of ruminthe code or couerceTeinunerstsgreatrstnn soit) AMHR youn inrove te coebyxig theses << endl; enterevslve t an ine mm ; cout ce “Enter: a: numbers: if ( num < 30) a cueee "Therma s1essithan 30" ee endl 7 a an a Te LT TEE . fans ~ + return 8; ' BRTESTM The code works the same way, as you would expect but whatf you wantedto display something if the User entered the number 30? Try this: t ‘int nun; ‘cout << “Enter a number: “; if C rum < 30) 4 cout << “The nunber is ess than 301" << endl; 3 else if (num > 30) i cout << “The nunber is greater than 301” << endl; else if (num 4 30) cout << “The nunber is exactly 301” << endl 3 return 0; ¥ FETTER) the new adcition tothe codes what's known asa rested if. else statement This allows you to check Far multiple conditions in his case, ifthe user enters arumber less than 30, greater than 30 or actually 30 sel, 2 ciferent outcome is presented to them, STEED You cn take thisupanotch and cesteatwoplayes umber guessing game, Begin by creating the vale ‘int num, guess, tries = 0; cout << << endl; ‘cout << “\nPlayer One, enter a nunber for Player Two to guess: “ << endl; ‘cin >> num cout << string(S0, “\n"); The cout << sting, ne deasthe screenso Suz Player Two doesn't see the entered number. Now while loop, together withif... else s*¥* Two-player number guessing gane you can create ado, 0 4 cout << “\nPlayer Two, enter your guess: cin >> guess; triest+3 Uf (guess > nun) { cout << “\nToo High!\n"

You might also like