You are on page 1of 197
The Complete pecing. {var B® pbleRec(a.tve ren ARNDALE Y, the Sens Inte & The: Complete Linux Manual The Complete Coding Manual Engineer your Future; learn to code! Cer OR a aS Te ayyonn car, power up the washing machine, whatever cud Peetu ee cae ue ad yam ey eee ary ocean simply displaying an icon on your iPad, through hero liny orbarchhenest nerd ee ance eters pee Peet cues eet re ornaid Do Sueur RC Cc eo al Cee een Le eed tutorials to help you understand what to enter, and what exactly is happening when you enter the code. The Complete Coding Manual Provides you with a solid foundation, on which to begin learning how: to code, before moving on to introduce more complex techniques and advanced concepts that enable you to create your own unique code, BCU eM t enue e a Coo key OI UUs en eu CUM hes ee fot tee een Being a Programmer Your First Cade Choosing a Programming Language 19 and Executing Your Creating a Coding Platform Executing Code from the Command Line Numbers and Expressions Using Comments Working with Variables User Input \g Functions ditions and Loops les Python Errors. mbining What You Python in Numbers hy Python? Equipment You Will Need uu) aT Dictionaries How to Set Up Py Splitting and How to Set Up Py é Formatting Strings Date and Time Writing to Files Exceptio Python Graphics What ew broeaton om lendar Module (0S Module Random Module Tkinter Module Pygame Module ur Own Modules Equipment You Will Need Set Up C++ in Winds Up C+ ona Mac How to Set Up C+ in Linux Other C++ IDEs to install ariables Data Types: Strings CH Maths | Gr ylennerenestg User interaction Character Literals Defining Constants File Input/Output ex: aN Cee ees Mea While Loop For Loop Do... While Loop IF Statement. Statement, Batch File Programming Loops and Repetition Creating a Batch File Game ‘0 Python en Tracking the 1SS with Python Using Text Files For Animation ‘ommon Coding Mistakes hon Beginner's Mistakes 's Mistakes Pe eee ae Foundations \ Where to start learning how to code? Ceca ess iets ECE Cust eu) PIE eau eal] unlimited number of tools to help you achieve what you want; but Rad In this section, we look at what you will Ree ean e eeu et ures Pee CE eee sso hours, learning how to code correctly ee eo a ace} Tee Res cred and start your coding journey. 8 Brief History of Coding 10 Bein no ew bampubtiatins com A Brief History of Coding Toomer ee CU ere Tce tage toe Pee Cae ae rt ean t that assumption is quite wrong, coding has actually been around For quite some time. Cee TRE M ERROR COR COL RR COOR COLE 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, Sree eae ca aE a eg there significant advances Cee on ert teeta Ce ue Peer ee es een een er ee ee) eet) ee ema ea ey Cy Cer atte ea Oa) Deore caus Cea Rie seen eer eae Ce Seely eatery ae Pope tet ty taf Petre eee Python 7 Peace veshaict eens Perera cemented asain Ly eres Hels See ern Certo ac) etm cd foe raee taeecnen Ree tee erent Cesare eed source ather code to improve thelr own. See ge er aus Pee ee es Peas ees eter Pete ies aco eee a) and ALGOL 58 were developed. Peepers ees eens Storey ee ee pee ero Cee ok cee ees perce erate ete carretera Being a Programmer Programmer, developer, coder, they're all titles For the same occupation, someone w 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 Peart ‘Times have changed since programming in the“80s, but the core values still remain. “It’s up to you how far to take your coding adventure!” Being able to follow logical pattern and see an end resultis one of the 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, as opposed to being in kt Form and you having to solder the parts together, were the stuff ‘of dreams; and getting your hands on one was sheer bliss contained within alarge plastic box, However, it wasnt so much the new technology that computers then offered, moreover It was the fact that fr the Fist time ever you could control 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 ther 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 designers, 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, ime 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 programme? “The single most common tat of any programmer, regardless of what they'e doing isthe 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 mathematic. You donit have tobe ata genius level 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 ableto see the big pictures certainly beneficial forthe modern programmer. Undoubtedly, asa programmer, you willbe part ofa team ‘of other programmers, and more than likely prt ofan even bigger team of designers, allo 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 wn coding cubicle. Finally there's also a level of creativity needed to be a good programmer ‘Again though, you don't 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 = 0) Pefresinortcursor): certTachataoneracend) wold scrayeerL:-paine(oras ¥) { ‘einen Deine SE eeetieet: beet hSStocus = Hasrocusoeep(: Sav oneeineeetoys Int te = "heooer ceterotUO; iar u ee Stersorea 5g <,colum.catcount(); jst) { of ease crab I Yfe'— colum.cetcomt() «1 >= 0) lend(scatartisabled, Scoloreaper): if ‘ibtats © catcount()) stop Seeteiney iil Siteopt stzeey) bs ribsetam = Page ettandoyta)s << column catcaune(): 3+) ( ser Sxttab deh) ‘envronment or users. Operating systems, such as windows, macOS ‘and uch are usually a combination of C++, Ci, assembly and some Form of visua-based language. 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 crete programs, ‘apps software or whatever else you wantto cal them. They're widely used across all hardware platforms and suit virtually 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's known as a High-Level Language, in thats’ 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 learn, /F 82 tawoke. java import java. lang.reflect.*; fiass anvoke ¢ MB NCRG cle void maine string 2 args > ( try Class. fornane( args(0} > ‘pedtethod’ atgeLA0, hw clase Object Pt = meinyokeC mu71, mst Is System out printtnc eethwoked state echo Sepvokel sta + args {al SS args (oi > catch ( Eladshortoundeacepcion e {St % IShafs tarname 3c fond te class 3 Caceh'( iosuchwethodexeeption 2) ¢ } Geek, Fifegeiacensbacencion 63D { fe don't have peraasion to fake that } EgechC xnvocacontargetexception e4 ) { Jian excapeion ocurred while invoking that inethod System. out,printIn¢ Sheehod thren an: " + e8 ‘getTargetexception( “)°); Pe P avaisa powerful language that’s used in web pages, set-top boxes, ‘Tvsandevencars. ¢ Why Python? em Python was created over twenty si years ago and has evolved to became an ideal beginners language for learning how to program a computer's perfect forthe hobbyist enthusiast, student, teacher and those who simply need ta create thelr own uniqueinteraction between either themselves ora piece of externa hardware and the computer isel. Pythons Free to downoad, install and use ands avalable for Linux, Windows, macOS, MS-D0S, 05/2, BeOS, IBM series 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 free, easy to learn, exceptionally powerful, universaly accepted, effective and 2 superb learning and educational tool BASIC was once the starter language that early ‘sbithome computer users learned. Python sa more modem take on BASIC, it's easy to learn _and makes for an ideal beginners programming language. nnn CT =P Introducing Python Equipment You Will Need Se ean Nen a ec em SheMet Cenaies Funes aon catamaran ect eae 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 you're going to need a computer inorder to learn how to program in Python and to test your code. You can use Windaws (From XP onward) on either a32 or 64-bit processor an Apple Macor Linuxinstalled PC. AN IDE ‘AnIDE (integrated Developer Environment) is usedto enter and execute Python code. It enables you to inspect your program code and the values within the code, as ‘well as offering advanced Features. There are many different IDES avalable so ind the one that works For you and gives the best results PYTHON SOFTWARE. ‘macOS and Linux already come with Python preinstalled as part ofthe operating system, as does the Raspberry Pi. However, you need to ensue that youre running the latest version of Python. Windows users need to download andinstall Python, which well cover shorty, TEXT EDITOR ‘whilst tex edtorisan ideal enranment to enter code int, I's not an absolute necessity, Youcan enter and execute code directy from the IDLE but atext eto, ‘suchas Sublime Text or Notepad++ offers more advanced features and colour coding ‘when entering code, INTERNET ACCESS Python i an ever evolving environment and as such newversion often introduce new concepts or change existing commands and code structure to makeit amore efficient language. Having acces tothe internet wil keep you up-to-date, help you ‘cut when you get stuck and give access to Pythor'simmense number of modules. TIME AND PATIENCE Despite what other books may lead youto believe, you won'tbecome a programmer in 24hours. Learning to code in Python takes time, and patience. You maybecome Sstuckat times and other times the code wl lw tke water, Understand youre learning Something ently new, and you wil get there. BE serosticiorcon Eaipmen Youwiliced 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. : PS ‘The Raspberry Pi 4 Model 8s the latest version, Incorporating a more powerful CPU, a choice of 168, 28 oF 448 memory versions and Wil and Bluetooth support, You can pik upa Pi from around €23, increasing Upto £54 forthe 468 memory version, or asa pat of kit For £50, depending onthe kityou're interested in. Rusataolsan The FUZE is alearing environment bul on the latest model ofthe Raspberry Pi. You can purchase the workstations that me with an electronics kt and even a abot arm For you te bull and program. You can Find mere information on the FUZE at wwwfuze.co.uk We have several great Raspberry Piles avaiable via www. ‘bdmpublications.com, Our Pibooks cover how to buy your Fist Raspberry setitupand use ‘The Raspberry P's main operating system is a Debian-based Linux stribution that comes with everyting you need in a simple to use package. t's streamlined forthe Pland isan ideal platform for hardware and software projects, Python programming and even asa desktop computer. Getting to Know Python Caeser Mee eC Cute ee eer language on which to learn how to code, but it’s also powerful enough to be used by Cee eat ees n n PYTHON POWER PE Roce ene uu er ue Berm e eo en ae Lee Ere “The Python Software Foundation, a non-profit organisation devoted Ree eae cats ae eee ‘advance the Python programming language, and to support and ae ren eet eee eee eee eras See eee ee Pe eee ee Pera ae Cee ey Penne ee ees TEER One Racca Se eee ea eed cere sy Se eee ney Cee Sees oer) penne retry ear Petrie eet eek core a Se errr Eee ces Ose ee rece a ern en ne en aon ee’ Pree enn rte et ety Rr aaee te Iet eee eed Sete ere ent ee ee a ee ea ead Soe crs reddened Eee eee ero een te eee teres See ee ee ees cluster, the team then used Python to painstakingly stitch together Se eee eee at poe ec eens es Cea eee eee er ene eeu Pere tite ee rg is eran eng earns ie se) en te ee ee eet ways of interacting with people onlin. For example, when you search for something on the Amazon website you wil usually notice that similar products stat to appear, whether within Amazon sel, PYTHON 3 VS PYTHON 2 Ima typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language: re Lee ears Capote eee ee teenie er pr ee nine ermtecge emery! Crucially although you ca cu Python and Python 2 alongside Ae nt ee ano eget i gece Se eed oe ee ad ee ee De ee eg en a eee eens Core ae oy ee er annie paseo ee rein ee See eee cee ery ene eta rete eer cess pene entree ea arent eta ere ee ti gee eer thinking script that not ony displays items, news stories, books, ther websites and ideas relating to what you've searched for, eer a sere ee eee cen eee Se een eat PUM tater cad Ree ates co eee ee eee eee ua ee tot alldepends on what the developer wants from their AlPython code. Feedforward neural network r Cee nea emmy 9 ta mm-- eeu eies ee erie sens ee ey Ce ees time and as suche Python 2. Ifyou enter Pytnon 2 cadeint the ee ee between the olderversion and thenewer Python 2s good, but ee ee i ei Python 2code nto version 3, but, to begin with ’s bes to make sre eee yas Reet ee eee er ec eee MG eet mens Ce Perera eerie erent ener ae OTe edges Hower support for Python 28 se to end on lruary 152020, bux this doesnt mean lle te last you'see oft Many Linux distros use Python 2ibraries, as does macOS, and to be Fal forthe developers ee oe ee eg Ce ees oe Pee eee ee ZEN OF PYTHON Poets rer area ear Pei Pence thisisan ethos called eta eee) eects Influences the design of od Pores ett Se a Seca Petes non} Femi ine terrae ee ees eee ed ea pecs ere Cee ed anon eer et Ste] ane Rene ete nes Peer eee aes paneer sti eee =P Introducing Python How to Set Up Python in Windows Win este Coe eam ena Iara ee DICE Ae aN sures eat eC eae a reer Meme clam tt Ce taimece Meee ene ecu ae lt aclg nats 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 ww python, CChoasing the Customise option allows youto ‘ora/downloady). Look Fr the button detaling the specify certain parameters, and whist you may Download link for Python 3x. Python is regulary undated, changing stay with the defaults i's a goodhabit to adopt as, sometimes (not the lst dat For each bugfix and update. Therefore, dort worryif with Python, thankfully, nstallers can include unwanted adlitional yousee Python 38, more, aslong as ts Python 3, the code inthis Features. On the First screen avaiable, ensure all boxes are tcked book will work ine and click the Next button, en ie y Optional Features a B fn nm evmoereneree FATED (ckthe Download button for version 3x and ERT Te next page of options include some interesting save the fle to your Download older When the adeiions to Python. Ensure the Associate file with Fleis downloaded, doublecckthe executable and the 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 recommend opting for ticked. These make using Python later much easier. Click install when the Customise instalation link, you're ready to continue, J J advanced options == |= a a puthén ED sorewsctinon BSTESEM You may need to.confim the instalation with the Windows authentication notification. Simply dick es and Python wil begin to install. Once te instalation s complete, te Final Python wizard page wil allow you to view the latest release notes and Follow some online eutorias, Setup was successful a — windows FID) cefore you close the instal wizard window however, it’s best to ik onthe link next tothe shield detailed Disable Path Length Limi. Ths wl 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 FED) 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 launch the command line version of Python when clicked (more on that in amament). Te open the IDLE, type IDLE into Windows star. Fiters oo. @ Best match IDLE Python 3:7 32-bit) Cestop app Search suggestions PD idle - see web How to Set Up Python in Windows BP PPR cicsing onthe OLE Pxton 332i irk wiltaunch the Python Sel where youcan beghyour Phan programming journey, Don’t worry if your versionis newer, slong asi’ Python 3 ur code works inside your Python 3 interface, 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 BERET DD the command ine version of Python wor 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. otsouredtoacetanubicnvesiont then TRIAS) Orcs ne une andupode competes tr Sud is currently installed in your Linux system. To begin Sie python3. ==version again to see if Python 3.x is update, o even stated Aslongasyouhav Python 3x. youre ‘inning the mest recent major version the numbers after he 3 inate patches pls urthe updates ORen theyre nnecesay, SeidsBdaNRES I) bac they canconainvtal new elements. Fle Edt View Search Terminal Help with, dap into a Terminal session From your dstro’s menu, or Mie the CulealteTheys. ee nc RN eso both Python 2 and 3 by default, as there's plenty of code out there stil avalable for Python 2. Now enter python ==verssien. davidedavic-mint: Fle Ect View Help 5 PERI However i youwantthe atest, cutting edge befearten " Start by entering these commands into the Terminal: sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev - sores : os bncursesnS-dev Libssl-dev Libsqlitedodev tk-dev Inourcasewe have bth Python? and 3istaled, ibgdbn-dev Libc6-dev 1ibbz2-dev Sues ‘As long as Python 3.x.x is installed, then the code in. cur ttorwilwor Is aluaye worth checking tee te do tas been updated wth the later versions enter sudo apt-get Update && sudo apt-get upgrade to update the sster snidodavistine~ ‘Open up your Linux web browser and goto the SHEE Python download page: https://www.python.org/ ‘downloads Click on the Downloads, followed by the bu the Python Saurce window. This opens @ download dialogue box, choose a oation, then sart the download proces, @ python ie bouton Inthe Termin gt the Dion older Gey byentering: ed DownLoads/. Then unzip the contersof the domlonea Python sourcecode with at python-3.¥-¥tarsaz ence the swith the ves ramets Youve downloaded, Now eer the nev upped le wi tython 3.7 Within the Python Folder, enter: Ae configure Sudo ake 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, you need to enter the fallowing Suz) ‘command into the Terminal: sudo opt-get install. ‘ale3 ‘The IDLE can then be started with the command: idle Note ha IDLE runs adferent version to the one you installed From source. “tnisedvitn-/DominasPyban 3.72 PERRET BD Youll asoneed PP Pp installs Packages), which is atoolto hela 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 available athe Programming section inyour dstro's menu, Installation of Python on macOS can be dane in much the ‘same way a the Windows instalation. Simply go tothe Python ‘webpage, hover your mouse pointer over the Downloads Uinkand el Mac 05X From the options. You will hen be ‘uidecto the Python relesres For Mac versions long with the ‘necessary installers For macs 64-bit For OS X 10.9 and ater Python Foundations Python Foundations RSE Say Oa atieel ce Rte Oe mS Ns etek Cea tay ER Cath aC le First piece of code, save it and run it in CT ass Rae) Ora a MSU Et as] eS Co) RO eu eens time with Python. Let's start and see Detect et Pra aS 34 Er Er) Po User input eating Functions Teel ets => 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. ete aneM cr 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! ESTED ickon the windows Startbutton,andstarctyping BRMEM For example, in the Shell enter: 242 ‘ile, The result willbe the curently installed After pressing Enter, the nest line wil display the version of Python, IDLE (Python 3.7 32-bit for example. Youcan answer: 4. Basicaly, Python has taken the code’ and produced the Pin t tothe Start fr convenience, otherwise simply clcktheiconto relevant output. launch the Python Shell ESTED) The Shelliswhere youcanentercode andseethe — [ESB the Python hell acts very much ikea calculator, responses and output of code you've programmed since code is basicaly a series of mathematical, into Python. Thisisakind of sandbox iFyou ll where you're able interactions withthe system ncegers, which are the infinite to try out some simple code and processes. sequence of whole numbers, can easly be added, subtracted, rmaltipied, and soon. en Starting Python for the First Time \ PRPEEM wile that's very interesting, its not particularly ESTEEM The Python Lesa configurable environment. ‘exciting, Instead try ths: you dontke the way the colours ae represented, ' a thenyou can always change them vi Options > Configure IDLE, nc SS licking onthe Highlighting tab, However, we dont recommend that Just enteritinto the ILE as you've donein the previous steps. a5 you won't be seeing the same a our screenshots. Thesaltlemoetiondneyaiensinchced ERE swith sogans ane epi e elem your First bit of code. The Print command is Fairly ue! ‘operating system, there are numerous shortcut seFerpunatos tps hogs yen Sreqresthepueniests Keys we dt have oorfor tha alr, bute the Opn aswell as quotes inorder to output content to the screen inthis > Configure IDLE and under the Keystab, youll see alist ofthe casethe Hello everyone! bit current bindings. >>> _print(“Hello everyon a everyone! FERED vou have noticed the colour coding within the BERETD The Pithon OLE ica 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. you want to know the many ins and cuts Forthe Shel we recommend you take a Few moments to view RES aa ces a er htps//docspythonor9/3/ibrary/ile html which detais many oF Green Strings Dark Red ~ Comments Lees Purple—Funcions Light Red— Error Messages range Commands fame IDLE Colour Coding |[-oteur[Usetor [examples os | rea | pee mae tem [ewes | seer | ———— Your First Code sentially, you've already written your First piece of code with the print("Hello Mw eeu cette cl ae eter le-lre hole) eld Se hele Cru Ont hc tome eeateculcd PLAYING WITH PYTHON As 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 bieceopetanes — EERE vert rae tied bene se ole?) did in the previous page. In the Shell, enter the SUE? 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 int (Hello tothe DLE Shell to print the total of 2+2 youl need to remove eepee the quotes: primt(2iz) FETTER predicted, the word Hell appearsin the shell — BREW 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 doesn requretoo much explanation, variable, which something we will coverin more depth later. For Now ery row, enter primtc2i2") oe bez oo Your First Code [ hae youhave donehereisassigntheletersa Nowletsaedasuame: GES and b two values: 2 and 2. These are now variables, Sie surname="Hayward” ‘hich cn be calles upon by Python to output, ada, subtract, divide be called upon by Python to output, add, subtract, div Ee and son, Fors long as their numbers stay the same, Try ths \We now have two variables containing both a first nameand 3 surname, andwe can print them independently. printca) printcb), Teoupeotvetstencsoaevecurere — ERED i wewereto spo nesane routines tore, Bee values of a and b individually, as essentially you've Sie using the + symbol, the name wouldn't appear. aeledthomtobe printed sepaatehyouanetoadthem i, cvredyinthe output nthe Shel. Ty Yuan wie the Following an print Carb) ‘We need a space between the two, defining them as two separate Tis code takes the value of both and b. adds themtogether,and__ values and not something you mathematically play around with. outputs the result. FRED vou can play around 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 sing 8 commar could assign variables for someone's name: print(nane, surname) ‘Alternatively, you can ad the space yourself rrane="Devid” primtnane) print(nane+" “+surnane) As you can see, the use ofthe comma s much neater. Giaiwriseviswsrarasarrar of Congratulations, you've just taken your rststepsinto the wide world of Python, 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 for entering longer program listings. In this section, we'll introduce you to the IDLE Rm uae tac arene ee ka 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 Eltor will allow you to save and execute your Python code, FETED Fist. cpenthe Python DLE Shell when t'sup, click BRINE) as you can see the same colour codingisin place in the IDLE Eeitor asi isn the Shell, 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. cn File > New File ths wil 9pen 3 new window with United asits name. This sthe Python ILE 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 al 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 fromthe previous tutorial, enter just dump t wherever you ke, Remember to keep atid filesystem, print¢*Hetlo everyone!” though itl help you out inthe Future. os “ saving and Executing Your Code [ BETTE) Exteraname or your code, ‘print hell for BSTETD ersextend the code and enter few examales, ‘example, and click onthe Save button. As soon From the previous tutorial: asthe Python codes saved, i's executed and the output will be ‘etal in the IDLE Shel this case the words Hello everyone’. RB bez rane="David” sunanes"Hayward” printCnane, surname) print Carb) you pressF5 now, youllbe asked to save the fle again, asie’s been ‘maxified From before Tiekhowtneasmaayctreunstencad — EEAAE Woucsti oxtutonte eid ten Bee will be conducted. Enter it into the Editor, hit F5, Sie with the new code entries, and executed; with the savethe code andlook atthe output nthe Shel Sometimesthings outputin the Shel. nota reblem vith at thse Few tes, but wil ier depending on whether you've requested separate ypu were toed alarger ie overuriing can become anissve indo, but essential thatthe process, unless otherwise stead use le> Save AS mithin the Eto to crete a bockup. Stated th isthe method we vl se [a pein ceercopetns bs tt ot tn Ops War ESTED) 'vovopenthefilelocaton ofthe saved Python MIN Now create anew file. Close the Ector, and open code, youll notice that it ends in apy extension, anewrinstance Fle > New File from the Shel. ‘hiss the default Python filename, any code youcreate willbe Enter the lowing, andsaveitashello.py- \whateverpy, and any code downloaded From the many Internat aaa ee ect eee tren ERs? ferro 7 print(a, by ¢) ‘We willuse this cade inthe nex tutorial. ere o™ > Python Foundations Executing Code From the Command Line COMMAND THE CODE he code we created in the previous tutorial, the one we line level how we can run code that was made in 1d hellospy, let’ Using the GUlat the com Sie" routine automatically included all the necessary Subs Python using the command python and pressing nec words, the command ine. To begin with,clckon the Shel, with the familia, tee ight art Button, and type: end, ows a the cursor (>>>), er the code you ED occ stores oz printcay susan erminal in macOS, Linux, and Raspberry Pl operating systems Asyou can see, it works exactly the same Now enter @xit@ to leave the command tine ED Pron sesson and return backto tre 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 ttle confused as towhy the Windows version of Python wses the command ine: python instead of python The eason behind this that UND Ike systems such as macOS and Linux, already have Pthan iraries 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 dire consequencesta the system, ‘nc result developers decided thatthe best aparoach For macOS and Linux 3stems would be to leave the command line “ython 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 following nto the commandline python hetlo.py Tis will execute the code we created, which to remind you is ‘="Python” boris” "cool!" printca, by © This an issue with Windows, a doesn use any Python lari other than the anes installed by the user themselves when actually instaling Python. When a Windows user install Pythan, the installation wizard wil auto-ncude the command lie Instance tothe core Windaws PATH variable, which you can view by entering: path into the command tne, Tis points to the python. exe file required to execute Python code from the commandline, 1 dont recommend youinstall bath Python 2and Python 3 within windows 10; natural, you anf 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 nas as they will be installed in iferen folders and both use python.exe asthe commandline executable.’ lite long-winded, so unless there'sadre needto have both versions of Python installed is bet stick to Python 3. => Python Foundati ns) Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the like. Now let's expand on that, and see just how powerful Python is as a calculator. You can work within the IDLE Shel 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. (Open up the GUI version of Python 3, a mentioned you can use ether the Shell or the Ecitor. For the time being, we're going to use the Shell. IFyou've opted touse 3 thiréparty text editor, note that you need to get tothe DLE Shel For this parco the tutoria, Bee Youcanuseall the customary ‘Mathematical operations divide, multiply brackets and soon, Practise with afew, For example [Brmeitosa Fie tot Set Deng Ops Winder Beanies w —— a2 = a — Se ecideludaiietmaea t— [sagan eialar leaden ioe PETER the shell enterthe Foloning: Asyouveno 5 Sai Be oa: usonpodcesdecnl | [Raa nae pene meen phionprobcerodecst | Ren |____ number nPtten esesre Se ‘Asyou can see, Python canhandle some quite large numbers Brenton called floats, or oating point arithmetic however, you reed aninteger as opposed toa sna = Bes eames andsoon ¢ Numbers and Expressions [ Youcanabo use armenian Thswitbe SUED sropcrstionte re car oat one open voy a Gsstayed ss see the remainderleft overfrom cy 3:232 "3-7 enter ‘011, converting the integer vision. For example: EipelTctbytiac, sceeater ox into binary, and adding the prefix Pe ‘Ob to the Front. Ifyou want to _ 2p saseeessons remove the 0b prefs, then you vill display 3333333333, which SS Srseecroegeeas cane: is, ofcourse, 33recurting, you oeiwsitsiissat a nowenter: an ‘he Format ommand comers 108 Bs tale, the numbers 08 Tiswildspiay ynihithe ny formatidrepresentton 2" remainder left over From dividing + ‘as controlled by the format a 10 by 3. ve specification, the ’b’ part. Nextupwe BE, Pat Sawer ‘A Boolean Expressions loical statement that wi SUED etre power Bis wing ERED herve te or fase Wecan use these to compere operator oc exponentinion THM, “rt at, andes ee Fini tlethan or greater han, ry youwanttobeteciical tis ina New ie Towork out the power of ier something you can use a paeeaielaseiiiseae t double multpetionsymbo 2 ie print, ordowestaronteeybou: — 23 ee print, 10°10 bp aaron print, Kcr 52292, buwere ve pranks, Sueyouaiesdseauthe bs un a ssics behind maths operators. > ———— Tesheroimauctt — [Epaoemes Poi AALAND) ‘outin Python. oN print(9, not @ == 7 and b == 6) FEE Nibersand Sang TN I tothe code from step andyoulsee2 ‘expressions don't Sie, oeminen on sitent ‘series of True or False statements depending on stop there thon has ramers the resatfthe two defining elves Gand Tes an exterion of bulla uncon wor ut ‘what un've ooked at and an important part programming sets numbers absolute values, complex numbers, and a host of | Mathematical expesionsand ait St 9 oe ar Pythogarian tongue-twisters. For Ps fat : example, toconvert anumberto © arcs Eevee owe a anaes binca) smb => Python Foundati ns) Using Comments When writing your code, the Flow, what each variable does, how the overall program Pere er ince Una urecary er ea ate ecient kad iene adc 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 i's supposed to do, It's just good practise. STEER) Wiclistartby creating anewinstance of the ioe EBB) resavethe code and execute. Youllsee thatthe Eeitor File» New File, and then reste asimole cutputin the IDLE Shall stilthesame as before, variable and print command cespite the extralines being add. Simolyput, the hash symbol — notes line of text the programmer tans, infor them SHLTeCTHRIVaLURTORIARIEGMSTED and others of what's going on, without the user being aware. ‘Savethe le, and execute the code Brisa a i aie {pang berms 9 3an TOY PEAR a Boren orem eer meee see out EE ccvccscwireuricie newiner | REED) tccosunevaivevoabeswevecesees ESD arose scone ne SIRES Sn See vermeceiionieisiorectacarsometies aesunmeaseeer hematite: normally see within code: routine along the ines of # Set the start value of A to 10 oot ‘on10 printC*You've just lost a Lifel”) 4 Print the current value of A printC*You now have”, a, “Lives left!” print(“The value of A is,”, a) [B “a x Bead Essentially, the new code together with comments could look ike # Set the start value of A to 10 o=10 # Print the current volue of A print("The value of A is,", a) 4 Player lost a Life! ood 4 Inform player, and display current value of A ives) print¢"You've just Lost a life!™) Print(*You now have”, a, “Lives Left!” PRPTSERD You can use comments in different ays 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. Inline Comments are comments that Fllowa section of code. Take our examples from above, instead of inserting the code ona separate ine, we could use o-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! printCYou've just lost a life!) rintC"You now have”, a, “Lives Left!" # Inform player, and display current value of A (lives) a ac ‘Te comment, the hash symbol, can also be used to comment out sections of code you don’t want to be executed in your program. For instance, Fyou wanted to remove the First print statement, you would use: # print(“The value of A'is,”, a) [B “Cones py = Cyto CodeComenetpy B79" Fle Edt Fort Ran Optons Window Help ¥ sev the seazt velue of Rt 10 F Franc che current value of & 4 print ne value of A ae,", a] # Payer tose a uate! WTntorm player, and ateplay current of & (Lives) ryou now haves, ay "ives Lefe!™) You also use three single quotes to comment ‘outa Block Comment, muitine section oF ‘comments For ther to wotk, place thei before and after the areas yyouwant to comment: ‘This is the best gane 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 ecu acura R ae M te eee me ee cys Pe ate ec or i ienaat er en re fete) RV] Cea Rod 2) om 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. BEER some programming languages, you'rerequired — TEER) As we've seen previously, vaiablescan be touse adolarsignto denotea string, which isa concatenated using the plus symbol between the ‘arable made up of multiple characters, such as aname of aperson. variable names. n our example, we can use: print: Chame# s In Python this sntenecessary so, for example, inthe Shelienter: 4 tLe), The middle par. between the quotations, allows rrames"David Hayward?” (use your ownname,unlessyouealso usta adda colon and aspace. As variables are connected without «alled David Hayward) spaces, we need to add them manually You can check the type of variable nuse byissuing We can also Be _ SEED wsncccmcciaettcee ee” EDD site, Be oe on variable inside the brackets. n our example, this would be: ‘within another variable. For ‘=| ‘type Came), Add anew string variable: E1¢Le="Descended! example, tocombine both name - from Celts”. andiitle variables into anew vatable, we use: ine ccharactersnane +: + vee wecoreecarae mer SeEle Semmes ‘hen output the content ofthe ew variable a: print (character) ‘Numbers are stored as cifferent variables: agent ‘Type Cage) ‘Which as we know, are integers. ‘wenn (Working with Variables [ However, you can't combine both strings and integer type variables in the same command as you ‘woulda set of similar variables You need to tun oneinto the ‘ther, o vice versa. When you do tyte combine bath, youll et an ‘error message: print Cname + age) print (character +“ is “+ str(age) + “ years old.") ‘Alternatively, you can use: print (character, “is, age, “years old.) Notice again thatin the last example, you dont need the spaces between the words in quotes, as the commas treat each argument toprint separates. FRE ine core pecan suena com ty Cw old ore yur“ This isa process known as TypeCastng. The Python Bap "3 This presents abit ofa problem when you want toworkwitha number that’s been inputted by the user, for example, as age + 10isboth a string variable and an integer, it won't work. Instead, you need to enter: intcage) + 10 “Thiswill Typecast the age string nto an integer that can be worked wth, a The wef ypeCasting ao imporant when Sie dealing with Floating point arithmetic; remember: umberstathaveadecnalpointinthem Fer rama, er shirt=19.99 Now enter type(shint) and youl se that Python has allocated the number asa float’, because the value contains a decimal pint. BEET BD wen combining integers and oats Python Usually converts the integer toa float, but should the reverse ever be applied,’ worth remembering that Python ovine return the enact value, When converting afloat to an integer, Python wil always ound down tothe nearest integer, alled truncating; in ourcase instead of 19.93, it becomes 18 a —ccncn => Python Foundati ns) User Input MRE Morel ere eo Aol RUE CR Cue earlier, so now would be a good time to Focus solely on how you get information from Rtccm ice rece 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. ETT isnot already, open the Python 31OLE shell ERED Now that we have the user's name stored ina and stata New File nthe Edltor. Let's begin with couple of variables, we cn call them up whenever something really simple, enter: swe want printc*Helto”) printC*Welcone”, firstname, surname, “. hope: firstnane=input“that is your first nane? “) you're well today.") printC*Thanks.") Surnane=input(*And what is your sumnane? “) eestor eae — 33 Bune Frm n a mar s*) Fie_tdt_fomt_Run Opions Wrtow Hep Semenov tm [emecaney OP ‘ornanes ERTGED S2reand execute the code, and, asyounodoust [ERTS Pun the code and you'l notice asoht issue, the suspected, nthe IDLE Shel the program il ask fullstop after the surname Follows @blankspace. foryourfirst name, storing it asthe variable firstname, foloed by To-liminate that, we can adda plus sign instead oF the comma in ‘your surname; also stored ts oun variable (surname). the code: Por print C*Welcone”, firstname, surnames, T hope et mt ney pte you're well today.”) ve ot ert mee ten (a emcee at Sea the input command, For example, you can askthe userthetrname, andhave the input inthe line below: print¢“Hetlo. Whats your nane?") rrame=input © tet: eatin et =a x ‘The code From the previous step i often egarded as being litle neater than having @ lengthy ‘amount of text inthe input command, butit's ot arule that’s setin Stone, so do as youlike in these situations. Expanding onthe code, tiythis print C*Halt! Who goes there?”) rrane=input© Bea inca >a x from the user to Flesh outthe game a ite: if namess"David": printC"Melcone, good sir. You may pass.”) else: printC*I know you not. Prepare for battle!") W's a goodstarto atext adventure game, perhaps? Now we can expand on and use the raw input Dewan Ghar =a x You dar'talways have t include quoted text within ESTED What youve created hereisa condition, based on the user'sinputn short, we're using the input From the user and measuring it against a condition. Therefore, f the ‘ser 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, any input from a user isautomatically a string, so you'll need te apaly a “TypeCat inorder to tur it into something eee The creates ome Interesting addtions to the inout command. For example: # Code to calculate rate and distance printC“Input rate and a distance") rate = floatCinput("Rate: “D) (a eee nce =a x BRTTSET DD 00 tofirasetherate 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 Meu Ato Lieto a ORL EMA eco eee Sascetercanencmmen ni titsc tan 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 ‘and then returns the result. takes data, works on BTTESERD sot ontydatathata function works on. Functions ando all manner of useful things in Python, suchas, sort data, change items from one Format to another, and check the length or type of tems. Basically, function isashort wor folowed bybrackets. For example, tend, list) or typed) od aad ‘function aes da, sya, works on Gee itdepending on what the function is programmed todo, andretusthe end va, Thedatabenguerted on goes ise the races, sy waned kno how many tes frei the word anteater yo dente Tencrantiaisestablisimentarianisa”, ante umber28 wuld retum ESTES DD You c27 pass variables through functions in much the same manner, Le’ assume you want the ‘rumber of letersin a person's surname, you could use the Following code (enterthe text editor for ths example): ame=input (“Enter your surname: *) count=LenCnane) print C*Your surname has", count, “Letters in sts) Press FS and save the code to executeit Python has tens of functions but into it, far too ‘many to get into inthe limited space available here However, to view thelist of builtin Functions available to Python 3, navigate to https://docs.python.org/3/library/functions.htmL “These are the predefined Functions but since users have created ‘many more, theyre nt the only ones availabe ‘Adonai functions can be addedt Python SUP through modules. Python has a vast range of tTodulesavaloble that can cover numerous programming dues They add Functions and can be imported as and when required, Fo example, to use advanced Mathematies Funetio: ‘import math Once entered, youl have access to allthe Math madule Functions, FORGING FUNCTIONS eer iene) 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 vtise the square root function, mmath.sqrtC16) Asyou can see, the codes presented as module function (data). seated by other Python programmers, which you can import and you'll undoubtedly come Peer e ee tte en Cen ae cee? PRP choose File> New Filet enter the editor, let's ease eee nora aay Pret loO) ete ee ens eaten ort step 2 Jaga fee Hettocnane) | Brint C"Hetto™ a etre Saar Se nn cae BED to moc ie fur eae poereut acre ee BRED wh2: you've ust doneis import the Hello Fun ei eieeer eres Pre arent tera ce ens ee eee rere Ider addCa, DD] => Python Foundati ns) Conditions and Loops COR nee eer an ee nc ee Ce Cee Pea UN ut ei eam ater cuit ort Reem atu ea Cer cates essence Toot on 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 itisnt. BITES letscreateanew Python program that wilaskthe ETE Now weit use anifstatementto check ifthe word_ ser to input a word, then checkittosee i's a length arable is equal to Fou, and print friendly Fourletter word ornot. Start with Fle» New File, and begin with conformation iit applies tothe rule the input variable: word=input(*Please enter a four-letter wor word=input (Please enter a four-letter word: “) _word_Lengthelen(word) if word length = 4: print (word, “is a four-letter word. Well done.” “The double equal sign something ese ) checkif something is equa to aoe FETED Now we cancreste anew arable, thenusethelen PRISM The colon atthe end off tells Python that iFthis Function and pass the word variable through itto statement i true, do everything ater the colon sete total nbe oF letersthe user est entered thats dented News nove the csr bast the begin oF word=input(“Please enter a four-letter word: “) ces word_length-len(word) word=input(“Please enter a four-letter word: “) word_Length=Len(word) = ; 4F word-length = 4: asec Oi as Prints Groed"is aFOUS TORENT aes oe ese: Print: (ord; “is nota Foursletter nord") awd =aaEs ED wvebenpebicaonscom Conditions and L BED Meee tecostomecreiene ERIE rower cote tonite trots 2Fourletter ward inthe Shellto begin with Jou Eventualy could become qute complex Weve shouidhove the retuned messapethat the wordisfourlettes, ad Now press FS again, and rerun the programy, but thistime, enter a Fiveletter word, The Shel wil display thatt'snot a Four letter word, ‘onion for three-letter words: word~input(*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 thelr operation. A loop will run through the same block of code a number of times, usually with the support of a condition, ile statement. Lkeif, EBB the Foro ple. Fo ead eee tere eet: ee Pronds=[Cate SDogn Unicorn] step a ued oe eee coca ener on x t0_ronce C110): iy eee pene ear en antes) Python: Foundations Python Modules een re Mee ete ten eee eee ua ted Pea eet et hate dieu an eae tec et Eile ctRcok MASTERING MODULES Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are countless modules available, and as we've seen, you can even make your own, PEPE 2trovah good, the builtin functions within Python BRPMEM the result isan errorin the IOLE Shel asthe are inited, The use of modules, however allows us Pygare module fntrecognised or installed in tamake mere sophisticated programs, Asyou are aware, modules Python. To installa module we can use PIP (ip installs Package) are Python scripts that are imported, such as impart math, Clase down the IDLE Sell and drop into a command promot 0 Terminal session, At an elevated admin command prompt, enter: Im teat Gre pip install pygane Some modules, especalyon the Raspberry are The PP instalation requresan ee Bee included by default; the Math module is a prime Sie to it installing components at different locations, example. Sed, other modules aren't always available. goed Start with a search For CMD, via the Start button, ight-click the example on non platforms isthe Pygame module, which contains result, and then clickRun as Administrator. Linux and Mac users an ‘many functions to help create games. Try-import pygame. Use the Sudo command, with sudo pip install package. Python Modules gare, the module ill be imported into the cade without any problems. Youll 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 Close the command prompt or Terminal. nd re- launch the IDLE Shell. When you now enter import ‘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 madule to create something Ike: for i in rangecto): ‘print(random.randint(1, 25)) ww ‘Multiple modules canbe imported within your code. ‘mort: random ‘import math for I in rangecS: pprint(random.randint(1, 25)) print (math:pi) (Bsn ce aid The results astring of random numbers followed by the value of, as pulled from the math ‘madule sing the prink(math pi) function. You can also pullin certain functions From a modile 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 Bead random pumbers from 1 to 25, Youcan ply around vith the code to display more or less, and from a greater or lesser range. For example: ‘import random for i in rongeC2s): ‘printCrandom.randint 2, 100)) This helps create a more streamlined approsch to Sw programming, You can also use: import module*, hich willimport everything defined within the named medule. However is often regarded asa waste of resources, butit works onetheles. Finally, modules canbe imported as aliases ‘import math asim printcm.pid OF course, adding comments helps to tell others whats 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 's not able to continue due to something being missed out, wron ieee cas ae aout hand DEBUGGING Errors in code are called bugs, they're perfectly normal and can often be easily rect thing is to keep looking, experimenting, and testing. Eventually your code will be bug free. PPD code lent as luidas the written word,no matter how good the procramming language's. Python Is ‘cettainleasierthan most languages, but even itis prone to some annoying bugs. The most common are typos bythe user, and while ‘sy to find in smple dozerine code, imagine having to debug rmult-thousand tne code. with a litle patience. The ‘Thankful Python is helpful when it comes to displaying error messages. When yourecelve an error inredink from the IDLE Shel twill define the error itself, alongwith the tine number where the error has occurred While in the IDLE Ector this alte daunting for lots of code, textectors| helpby including tne numbering. Asweve mentioned, the mest common of eos Biee the typo, often at the command level, mistyping the print command for example. However, they aleo occur when you've ‘got numerous variables, al of which have lengthy names. The best ‘aduiceisto simply go through the code and check your spelling, (Bromo =e x PEPE Syntax errors are probably the second most Common erors you'll come across a a programmer. Evenif the spellings corcect, the actual command teal 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” (Briesa =a x tt tage te TED Psy 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 online Python resources, Bee code snippets, and lengthy discussions across forumon how best to aleve something Whe 99% fk good code, dart abays be re inte copsng an pasting random coseinto your dtr More afte than ot, Ron warkand Trateatingy, you wont ave earned anything FED misses sven rns from the Conditions and Loops section, where the colon means everything indented Fellowing the statementisto be executed along as t's true? Missing the indent r having too much oF an indent, will come back with an errr, Anexcellent way to check your code step-bystep is touse Python Tutor's Visualse web page, Found at ‘wurw pythontutor.com/visualizehtmlsmode=edit. Simply paste your codeinto 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 a good habit to plan what your code will obefore sting down totypeteout Us the vribes tht lle Used, along with the modules, and write outa serpt for any user Interaction o outputs. 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 amoth tuckin a relay, thus preventing the system from working. Removal of the moth was hence calle: debuosing, (_ Python Errors [ => 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 ese aRrRU ne Anca ce Riel ce 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 litte more. RID starsty opening Python and creating aNewFiein [BABAR 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 Pwithout rendering the computer's wl eventually display the value of Pi according to the Chudnovsky (CPU useless for several nutes. The recommended calculation _brother'sagorithm. As you have ne doubt already surmised, t Lsedin such creumstancesisthe Chudnovsky Algorithm, you would be handy toactually output the value of Pita the screen. To can find more information about at enwikipedia.ora/wik/ rectify that we can ade: Seeman asteen print Cealec1)) ‘We can utilise the Chudnovsky Algorithm to create ° ERED Wc arcttsethe crudnowsty Ago to ceate SERED yo con save ndercitethecoce at this point. f (begin by importing some Important modules and Functions you tke. The output wil print the value of Pito 27 Cale peeled eae STATES cima places: 3.181592653889734207668453591.Vihile pretty within ere modes impressive on is ov, we want some user interaction to askthe from decimal import Decimal, getcontext ‘ser as to how many places Pishouid be calculated. ‘import math ‘This uses the decimal and getcontext functions fromthe decimal EEN) we can insert. an nputline before the Pi calculation ‘module, both of which deal with lage decal place numbers, and, Def command need to be an integer, asi wl raturaly, che math module otherwise default toasting, We can clit numberofdats anduse the getcontexfuncion FETED owwecaninsrtthericalulationalgarthm —_punberoFdigits = intCinputC*please enter the partof the code Thsisa version ofthe rumber of decinal place to calculate Pi to: “D> Chudnosky Algorithm: getcontext©).prec = nunberofdigits ef caite(n): {e = Decinal(o) oe pi = Decimal(o) a ddeno = Decimal (a) k=0 for k in rangeCn): 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**Decimal(1.5)) pi = Upi return str¢pi) ss PRTESERD Wiccan execute the code now, anditllaskthe user tohow many decimal places they wantto calculate ian then output the result inthe IDLE She. Try it with 1000 places, bt don't go too high or else your computer will be locked up freadting Portofprogenminis SEO being able to modify code, making ore eerste ers ice breomert tha tines how ong tales oe Conputrtocalesatethe Sdial pares and preset the nvr atonin serene Stour Forth chopintothe command ine soderpo the colar moe wee aayhave stated vip install colorana Torin our code we need iisie the Sue? AT colorama module, and then start the time Function axthepointwherethe ceases aden tfinshes The end resut oepaysnclaued i wlan the preesstok 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) Combining What You Know So Far PETIT Now we nced to import the colorama module (which wil outpuc text in eifferent colours), along with the Fore Function (which cctates the Foreground, ink, colo, and thetime module to start a virtua stopwatch to see how long ‘ur ealeulations take: import time import colorana From colorana import Fore = Decinatca) pi = Decinal@o) ‘deno = Decinal(@) 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)) pi 4= Decimal (t)/Decimat (deno) pi = pi * Decimal (i2)/ Decimal (640320**Decimal(1.5)) pi = pi return steCpi) printCeale(iy) rintCFore.RED + “\nTine token:”, time.tinec) = start_time) OY NEST : Ble = oe rT J = La rs PSC aac ce y POC eu Rane es cas 7 * eee : @ ied eee aces ~ Cre enya re id Pen Camedia in > é code, you'll need to know how to use it a - Ee cos < ~ Bineeees in Unser eS Tat) dee es aces Rie) 7 ~~ Pens eer aa Perm Cy eer teres -s Pee tetra Preece eur ete tac) \ external files. ‘ fed ia Peco ead eed ; en ee Poe Cy Cy 64 Ca cr) rT) R een er + goer 76 Exceptions _ ’ ceed Combining oe Tree tn eects rt) EAS SNR argon asa whole, or individually if wanted. 9 data if you prefer, which can be accessed WORKING WITH LISTS. Lists are extremely handy in Python. list can be strings, inte: ‘and lists within lst. ETE *istisasequence 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] ‘ythical_creatures ~ [*Unicorn”, “Balrog”, "Varpire™, “Dragon”, “Minotaur™} (Beuitone = x BETES "ce youve defined your list. 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 tem third From zeroin the st 21 inthis case). ‘aie 5, and also variables. You can even include functions in ists, You can also access, or index, the lastitem ina list 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 ‘ker that sntin the ist, such as [10] will return an error: runbers[-1] snythical_creatures[-4] ESEEED Sicnaissimitarto indexing, butyou can retrieve ‘multiple items in aist 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), BRPEIM You can update items within anexsting list, remove BRIBE vou can view what canbe done with sts by entering items, and even join iss together. For example, to list into the Shel The output isthe available join two tists we can us: Functions, for example, insert and poo are used to ad, and remove, everything = nunbers + mythicalcreatures cere oae runbers-insert(4, 62) Inserts the number 62 at tem index 4. Ane: runbers.popC4) il remove ‘Then vew the combined lst wth everything PD tems canbe added toa list by entering FEAT) You alo use the list function tobreake string down EEE into ts components. Far example: reas List*David?) Breaks the name David into‘D, a,‘ This can then be passed nythical_creatres-aythical_creaturest{*Grifffr"] (rby using the append function toanewist: ane=list(*David Hayward”) nythical creatures. oppend(“Nessie”) rane rumbers.append(278) age=[44] user = name + age Removal of tems canbe done n two ays, The Fist used on that, wecan create a program ta store Siery is by the item number: Suz ‘someone's name and age asa list: ‘del nunbers(7] rane=input(that"s your name? “) Anane=1istCnane) jaca ened age=intCinputCHon old are you: “> ythical_creatures. remove Nessie”) oge=Lage] ea aan User = Inane + Lage 3 ee “The combined name and age ist called user, which canbe called a ET byentering userintothe Shell Experiment and se what you can do. —eccnnen CE Aer Mea uel ea ete ce ech eee men ome eta raee) ened meni cek relat Tee eel RUN elo 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, inan adventure game where non-playing character names are stored. ESPTSPB * leis creates the same may asalist,butin this Instance you use curved brackets instead of square brackets For example: nmonths=C*January”, “February”, “March”, “April”, “May”, “June” months Brenton =o # You can create grouped tuples int lists that contain multiple sets of data. For instance, here we have a tuple called NPC (Now Playable Characters) containing the character name, and their combat rating, for an adventure game: NEC=EC*Conan”, 100), (*BeLit”, 80), “Valeria”, 957] a ‘swt ts the tems within a namec tle canbe BARD se) acordngtother postionithe dats ange: sonths (2) tonths(3] ‘And soon, However, any attempt at deleting, or addin, tothe tuple wl result in an errr inthe Shel ESTEE [2h ofthese data items can be accessed asahole byentering NPC nto the Shell or tey canbe indeved 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 mutple ise From the norm. You would expect the 95 combatting ofthe character Valeria to be NPC[a(S], however its not, k's actually wecr2it1 FD this means, of couse, thatthe indexing follows thus: od ° 2 1 20 an ye This, as you can imagine, gts little confusing when you havea lot of tuple datato deal with, STEED Now unpeckthe tupteinto twoc corresponding variables: (Crane, conbat_rating)=NPC ‘You can now check the values by entering name and combat_rating cr Remember, swith lt, you can also index tuples {sing negative numbers, which count backwards From the end ofthe datas. So, forour example, using the tuple with multipe data items, we would reference the Valera character with: Nect2]¢-01) iB BETTER) Terles though, utilsea feature called unpacking, were the data items stored within a tuple are ‘assigned variables Fst, create the tuple with two ers (name 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 oumbers For eames rubers(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) ‘The numbers canbe integers and floats. To output the highestand lowest, use: printnaxcrunbers)) print(min¢runbers)) @ ccm CE EP Manipulating Data Dictionaries eee eeu ee Mae raru eT eae cen of dealing with data items. Although they can be tricky to get to grips with at First, Nem er eee cn emis oe KEY PAIRS ‘A dictionary is tke alist, But instead each data item comes as a pair, the ‘unique and can either be a number or string, but the Value can be any data item you like. RPI evs say you want to create a phonebook in Python, You would create the dionary 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} & ‘are known as Key and Valu ‘The Key part must be ESTED ith sesand tuples, you can check the contents cof adicionary by cain the icionary name; phonebook, in this example. This will display the data tems youve enteredin similar fashion toa list, wichyyouire no doubt familar swith by now, STEED 2 vith most ists, tuples, and soon, strings need tobe enclosedin quotes (single or double), wile integers can be left open. Remember thatthe value canbe ether 3 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 he keytoindex the value, Using the Phonebook example from the previous steps, we can enter: phonebook “Enna” phonebook “Hanna” a = BSTESEM sing to. dctionaryis easy too, ou can include ‘anew data item entry by adding the new key and valueitems as suck: phonebook [“David"] = “0987 654 321” Phonebook rennet =o x ‘and you can also remove items from a dictionary byissuing the del command followed bythe IRem’skey-the value will aso be removed as wel since both ‘work a pair of data items: ‘del. phonebook(“David’ Next, we need to define the usr inputs and variables, one forthe person's name, the other For their phone number (we wil keep i simple to avoid enathy Python code) rrameminputC“Enter name: ) runber=intCinputC“Enter phone nunber: “)) & Note we've kept the number as an integer instead cof astring even though the value can be both aninteger anda string, Now we need toad the user's inputted variabes tothe newly created blank dictionary. Using the same process asin Step 5, we can enter phonebook[nane] = number a FED Sasi ssntwe; encour casas key and vale items? Greate anew Ector instance, and stat by ‘coding in anew, blank dictionary: phonebook={} BETTE Now when we save-snd execute the code, Python wil ask fora name and a number. il 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 ) zy Splitting and Joining Strings When dealing with data in Python, especially from a user's input, you will undoubtedly 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. Tremantstintestingfucionasenls sod. EEEEME retehe nto cntastb ats Sued ‘With it, you're able to split apart a string of data, OG quotes, then a space followed by closing quotes: basedon the argument wahinte brackets For eam hee'sa__ and bracts. The space ste seperate, nacating tat ech st string with three items, each separated by a space: Item entry is separated bya space. Likewise, SY (Comma Separated ‘text="Daniel. Hannah Erma” Value) content hasa comma, owe would se: . text="January, February, March, April May, June” nonths=text. split," Fie by pa toanasne, oe months ea Be ESTED "Now ters turn the sting into alist, andspitthe BITE Vice previouslyseen how, using aname, we can contentaccordinaly: splita string into individual letters asa ist: nomes=text.split(* *) ame=List (“David”) ‘And enter the name ofthe newts, names, tosee the threeitems, PAM : “The returned valeis ‘Dv, 7, While it may seem alitle useless under ordinary circumstances, itcoulé be handy for creating rime aspeling game, for example, a BETEEM the converse ofthe spi function s join, where separate items ina string, canjoin together to form ‘awerd, orjusta combination of items; depending on the program youre wrking, Fr istance: ‘lphabet="". joinC[“a”,"6","c","4","e"]) ‘alphabet ‘This wil splay ‘abede' inthe Shell ‘We can therefore apply join tothe separated name we made in Step 4, combining the letters again to Ferm the name: rame=”. joinname) ‘we've joined the string back together and retained thelist called name, passing Itthrough the join Function. & BSTETD withthe spicfunction, che separator doesnt havetto be a space it can alo be a comma, ora Full stop, ora yphen, or whatever you tke colours-[*Red”, “Green”, “Blue”] cole,” join(edtours) ‘eitLe="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 ‘Agood example of using the join unctionis when you have list of words you want to combine into ‘asentence Liste[“Conan”, “raised”, “his”, “mighty”, “sword”, “ond”, “struck”, “the”, “denon”) texte” “.joinClist) text Note the space between the quotes before the jon function (where there were no quotesin Step 6 joi). BEPTET BD You con aso use locic operators on strings, with the in ad not in function. These enable you to check Fa string cantains (or doesnot contain) a sequence cof characters mnessage="Have a nice day” “mice” in message "bad" not in message “day” not in message “night” in message ew bdmpubcatonscm EP Manipulating Data ) zy 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 Enea cael tediste turers 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. ESPSEB the basic formatting in Python ito all each SED Wiccan, of course, also include integers into the mix: variable nto te string using the cuty brackets: unber=10000 ne="Conan” printC“{} of {} was a skilled mercenary, printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from "format name) mmerchant.”.format(nane, place, nunber)) BSTIEED Remember oclosethe prin¢function with wosets EMEP) there are many cifferent waysto apply string of brackets, 2s you've encased the varabein one, formating. some are aie simple, as we've shown ‘and he print functonin another You anincude muliple cases oF youhere, and otherscan be significantly more comple. tal {2rngfrmattingin single prin Fureion: epends on what you want fom your program. A.good place to feference frequently, regarding sting armating, isthe Python Docs webpage, ound at tps/docs python org/3./ibrary/ String html, Here you wilfind tos of hel, rame="Conan™ place="Cimeria” print(“{} hailed from the North, in a cold land known as {}”.formatCnane, place) Dimi EID iccivsyrcncccxetngoe ciseunncst oe ane rumbers=1, 3, 45, 567546, 3425346345, PrintCSone numbers: 2, Ch, Ob, 0, (". formatctnunbers)) ( Formatting Strings em You can prin avthe conten oF sesinptin the SEG ‘same fashion: ramesinputC“What’s your name? “) printCHello {}.".format (name) ‘swith indexing ints,te same apples tocalinga Bae list using string Formatting. We can index each item cording tos polon from 0 ta however many presen runbers=1, 4, 7, 9 printCMore numbers: {3}, {0}, (2h, {1}. Format(*nunbers)) Py And 3s you probably suspect, you can mix strings BAD sr ctecersina ial isttobe caledinthe Format function characterss["Conan”, “Belit”, “Valeria”, 19, 27, 20) print C“{0} is {3} years old, Whereas {1} is {4} years old.”. format(*characters)) Andyou can extend thi sine code exalt Sie display the first letter in a person's entered name: ranesinput(“that’s your name? “) printCHello {b.”.formatnane)) Inane=Listname) print(The first letter of your nane is a {0}". format*1nane)) You can ab calupon aa of ats ndreference Suz ‘them individually within the same print Function, Looking backat the ade from Step 7, we canal eth rames=[“Conan”, “Belit”, “Valeria”) ages=[25, 21, 22] Creating two ists. Now we can call each list, and individual tems: printC*f0[0]} ts {2101} years old. Whereas {001} is {1[1T} years old.”.format(nanes, ages)) wotinocicioncn CE EP Manipulating Data ) zy Date and Time When working with data it’s often handy to have access to the time. For example, you may PEL en Enea neg eee a ue eg oe el eu ue Lio een mnt ee Meenas cn leet cs 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, Sea First you need tolimportthe Time module. t’sone that’s builtin to Python 3,50 you shouldn't need to rop into a command prompt and pip instal. Once t's imported, ‘we can call the curent time and date with a simple cormmand: import time ‘time.asctimeC) (Beeson =e x ‘The time function is solt nto nine tuples, these are vided up into indexed items, 25 with any other tuple, and shown inthe screen shot below. 8 kage ye os : second 061 (06 me apse) © coyotes 096 (0 Monday) © ape seings “101, 2 means tary dteres DST You can see the structure af howtime is presented byentering: tine. local. time) ‘he outputs dsplayed as such: “time, struct timeCtm. yeor=2019, tmnon-9, tmnday=7, tmhour=9, ‘tmminaG, tm_sec=13, tmndays3, tmyday=250, tm ‘isdst=9)'; obviously dependent on your current time, as opposed tothe time this book was written ‘Tere are numerous functions built into the GUE) Time module. One of the most common of these is.strfeime() witht you're able to presenta wide range oF arguments asi converts the time tuple into a string, For exemple, to display the current day ofthe week we can use: time, strftimeC*KA”) a (Date and Time em Naturally this means you can incorporate various Functions into your own code, suchas time.strftime(“#a") ‘time. strf timeC#8") time.strftime(“#b") time.strftime(“#H") ‘time. strftime CAHN") 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 6M doesnt display the time carecly inthe Shell we can easy rectify this wath time. strftimeC*m 301") o \We can alsouse the Time madulet display the ie) ‘example, taking the above code, we can alter it slightly by including start_time-time.time©) An endtimestime.tine@)-start_time Binney Sitnttnaneshtten ign O78 sa x i a aii ST input statement, as that’s when the variable name being created ~ ‘epending on have ong the user took talogin The length of time then displayed on the last ine ofthe code, asthe endtime variable. The output willook similar tothe screenshot below. The timer Function needs tobe ether side oF the Pod = 3 x ‘This means you'te going tobe abe to display ether thecurene ime, orthe time when something ‘eceurted such asa user entering ther name. Try this code inthe Eto import time rane=input(“Enter Login none: “) printCMelcone”, none, “\d) printCUser:”, nane, “Logged in at”, time. strftimeCH:2")) ‘Trytocextenditfurthertoinclude day, month, year, and s0 on BEPEET BD theres lotthatcan be done with the Time rmadule, some of itis quite complex too such aslsplaying the number of seconds since January 1st 1970. Fyou want to dill down Further inta the Tie medule then inthe Shel enter:he1pCtime to display the curent Python version help ile For the Time module @ ccm CE EP Manipulating Data ) zy Opening Files uel eu ica ne Meme Car) ete en tee Mae ere Ce Ute ene cs ROR rca erin Menace ect an on 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. Sea Startby entering some textinto your system's text editor. The text editor is preferable toa word processor, as word processors include background formatting and ‘other elements. our example, we have the poem The Gimmerian, byRobert E Howard, and we've saved the leas poem. na i Ifyou now enter poem into the Shell you wil get some information egarding the text 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 textrepresents 2 newline, 3s wehave sed previously. You use the open() function to pass the fle intoa variable as an object. You can name the file object anything you like, 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 (\)isbecause Python wil read this _as Unicode Error, thinking you've entered: \U-Thisis Windows-only, LUnux and Mac wortthave tis sue Fy erter pera second ne you GUE) notice that the text has been removed from the Fie, Youvllreesto enter poen-opent"C-\\Users\\Savid\\ Dociments\\poem xt) scant rerestethefie That, however eter print(poem. read()) Now the /nenties ae removed in Favour of new tines and Feadable text. > a P (_ Opening Files em ‘As wth ts, 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) ‘llislay the next ive. Entering (1) wil display one character at atime, & Similarly, you cn display one tine of text.at atime by Bee using the readline) function. For example: PoeropentC:\\Users\\david\ \Docunents\\poem, txt) Poen.readlineC) ‘il display the fst ine of the text. And: Poem.readtineC ‘ll display the nest tine of text. aw Extending this further, you can use readlines) to Bea graballthe lines ofthe text and store them as ‘multiple ists. These canthen be stored as avarable poesopen(“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 the lines coftext backtous: print (Lines) a ‘As you may suspect, you can pass the readline) Function into a variable, allowing youtocallit again, Bead :\\Users\\david\\Docunents\\poem. xt") Line=poen. readline) line PEPET BD [2's imacine that you wanted to prin the text acharacter at atime, as would an old dot matrix printer. We can use the Time madule mixed with what we've looked there. Ty this: import time poer=open(*C:\\Userss\\david\\Docunents\\poem. txt") Lines=poen.read() for lines in Lines: print(lines, end=”) ‘time.sleepC.15) ‘The output isfunto view, and easly incorporated into your own code EP Manipulating Data Writing to Files Being able to read external files within Python is certainly handy, but writing to a file eaten UTM ett tte ot 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 isin read or write mode. Start by opening IDLE and enter the following (ebviously entering your oun username location): ‘teopenC*C:\\Users\david\\Documents\text.txt", “W") ‘Thiscode wil create tent Fle, called textbt in write mode, using the variable IF there's no fil ofthat name inthe acaton, it wl ‘create one. Fone already eis, iwll overmite so be careful However, the actual text fief still blank (you can check by opening itup) This is because youve ‘rtten the line of text tothe fle object, but not committed itto the fle itselt Part ofthe write Functions that we needto commit the changes tothe le, we can dothisby entering: t-closeC) (Brio >a x \We can now write tothe text file 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 =a * trie ae ea oe FIR xen crn wiente wines ED sescscrcssscsiceeersste Fee gerebetgntan one ntoeeey ioe srigaeccuun roe omioheweentetaned Peas (Beene aw i ay mare Hie a at, hw (Writing to Fi q ‘Toexpand this code, we can re-open the fle using 1, For accessor append mode, Thiswill add any text at the end ofthe original ine, instead of wiping the Fe 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 water.\n") aw We can keep extending the text line byline, tending each witha newline (i. When you're one nish 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! tecleseQ) \We can pass variables to 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.pi) PrintC*\nliriting to a file now.") 2 pisath.pi NNowle’s create a variable called pi, and assign itthe value oF i Wie also need to create anew fle to write Pita: ‘teopenC“C:\Wsers\\dovid\\Documents\\pi txt”, “W") Remember to change you le location to your own particular system setup, & Tare ae varoustype of file access to consider Siery using the open() function. Each depends on how the Fielsaccesed, and even the postion ofthe ctor For example, copenes ein read and wie an laces the crsor tthe tat of Dee Tofinish, we can use string Formatting to cll the Suz variable and write it to the file, then commit the changes and close the file: t.writeC'Value of Pi is: {}”.formatCpi)) t-closeC) ‘Asyou cansee from the results, youre abl to pass any variable to afle, EP Manipulating Data Exceptions POM eee EI en ean a etc eee eos s carl circumstances that are mostly out of your control. Let’s assume you aska user to divide 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 «an 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 ZereDivsionError: Division by zero message, as seen in the screenshot. The ZeroDinisionésor parts the exception cass, of leh there ae mary. Doanone \We can use the Functions raise exception to create ‘our awn eror handling code within Python. Lets assume your code has you warping around the costnos, too much, however results ina 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 BEER Mostexcentions are raised ‘automatically when Python ‘comes across something that's inherently wrong withthe code However, we can cieate our own ‘exceptions that are designed to ‘contain the potential ertor and = react tot, 2s opposedto letting = the cage fall. oo wadenpubliatons.com EID ove eros reconne cece FED oerec tines at as Soneeows Lomeorusmiebnortarbers acmssontins oorenrode Do For example, using the divide by zero error, we can Sea 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!) a You can use exceptions to hance a variety of useful tasks, Using an example from our previous tutorials, lets assume you want to open afile and rite to try: ‘txt openc"C:\\Users\david\ \Documents\\textfile. txt”, tr") ‘txt writeC"This is @ test. Normal service will shortly resume!) except T0Error: print C*Error: unable to write the file. Check Permissions”) else: print (“Content written to file successfully. Have @ nice day.”) ‘ext .closeQ) bv this wont work etothe ie tet ue ‘being opened as read only (the "r* part). So in this. caterer than yeonteling were dong someting wrong Move rested an exception, cng he Eo snoring te toe thatthe parmastors seine o Naturally, we can quickly Fixthe issue by changing the "read only instance with a“w' for write This, asyou already know, wil create the Fle and write the content then ‘ommitthe changes tothe le, The end result wll report a different setof circumstances in this case, successful execution ofthe code. You can also use a finally: block, which works ina similar Fashion, butyou cannot use else witht. Hint: You'l need to delete the textile txt le from your Folder. try: ‘txt, = open C:\\Wsers\\david\\Documents\\textfile. ED try: ‘txt.writeC*This is @ test. Normal service will shortly resune!”) fmally: print (“Content written to fle successfully. Have a nice day.”) txt.closeQ) except T0Error: print “Error: permissions”) unable to write the file. Check ‘As before an erorwilloccur as we've used the“ Feacsonly pecmisson.Fwe change ittaa"w",then the code will execute without the error being displayed inthe IDLE 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 i we o oe EP Manipulating Data ) zy Python Graphics PCR ee insta eee eet ne ne acc aint Reem eee ise eosin Ly go amiss. Python 3 has numerous ways in which to include graphics, and they're surprisingly powerful too. GOING GRAPHICAL ‘You can draw simple graphics, in some spectacular effects. Sea ne ofthe best graphical modules to begin learning Python graphicsis Tul. The Turtle module sas the name suggests, based onthe turtle robots used in many schools that canbe programmed to draw something ona large piece of paper on the Floor. The Turtle made can be Imported with: Import turtle. Lets beain by crawing a simple circle. Start a New Bee File, then enter the following code: import turtle turtle.circle so) turtle. getscreen()._root..nainloop() ‘As usual press FS to save the code and execute it. This will open up new window and the Turtle’ wil draw circle. squares and 50 on, or you can use one of the many Python modules available to bring out ‘The command turtie-circle(SO} is what draws the circle on the sceen, with SO being the size. You can play around with the sizes ifyou tke, going upto 100, 150, and beyond; you can draw an arc by entering turtle.circleC50, 1180), where the sizes 50, But you're telling Python to only draw ‘a0 ofthe circ ‘The as part of the ice code tes thon tokeeo Si the window where the drawing és taking place to remain open, sothe user can cco else it. Now let's make a square ‘import turtle print ("Drawing @ square") for t in rangec#): turtle. Formard(100) turtle. 1eFt(90) turtle.getscreen().—root .rainloop() ‘oul notice weve inserted a loop to draw the sides ofthe square, BRTEEM To add some colour we can addanewlineto the square code turtle.color¢“Red”) ‘And we can even change the character to an aclal turtle by entering turtle. shapeC“turtte”) ‘we can also use the command turtle begin Fill, andturtle.end_ Fill to filin the square with the chosen colours in this ase, red outline, and yellow i PETIT) *syoucansee, the Turtle madule can draw out some prety good shapes, and become ate more comple, asyou begin to maser the way wots enter this example: fron turtle import * colorcéred?, ‘yellon’) begin flO while True: Forward(200) 1eFeC170) iF abscpos) <1: break end fU10) done tesa different method, buvvery effective * SPEED ower’ get the code by imparting the pygame module ‘import: pygane pygare. init ‘ing = pygane. image. lead*RP%..prg") white = (255, 255, 255) * w= 900 h= 450 screen = pygone. display. setnode((n, h)) screen. fll CCwhite)) screen.f1¢Cuhite)) screen. blitCing,(0,0)) - Pygane. display. flip) hile True for event in pygane.event.get(): ‘if event type = pygane.QUT ygane.quit© Inthe peviousstep we've imported yaa Sie initiated the pygame engine, and asked it to import cursed Rasberry Plogo mage saved Leng Next ie Getredte baclground colour ofthe wind to delay the mage andthe window se apr the acal mage dmensios Fray we havea oop ta lose te window w= 900 | h = 450 screen ~ pygame.display.set_mode((m, h)) screen. fill((nhite)) screen. fill((white)) screen.blit(ing, (0,0)) pygame. display. flip() while Tru for event in pygame-event.get(): if event.type == pygame. QUIT pygame.quit() FERED other way you can csplay oraphics by using the Pygame module, There are numerous ways in ‘which pygame can help you output graphicsto the screen, but for row let's ook at displaying a pre-defined image. Start by opening 2 browser and finding an image, then save itt the Felder where you save your Python code. as u Bs Ei se FETED ress FS to save and execute the code, and your image willbe displayed in anew window. Have 8 play around with the colours, sizes and so on, and take time to look ‘up the many Functions within the Pygame module to. taspberryPi or: (_ Python Graphics em EP Manipulating Data ) J Combining What You Know So Far CSE Tefen AC Lod cele Mea es Lee ook NN Reo AY LD) piece of code that can easily be applied into a real-world situation; or at the very least, Pou R nek CetReutueen ace iucn eta ileus LOGGING IN For this example, let's look to apiece of code that will create user logins then allow them to log inte the system, and write the time at which they logged in, We can even include an option to quit the program by pressing LecsbeanbyingernatheTine neal ceaira REESE The abl saute septal Sued anew dictionary to handle the usernames and Sie variable From one that can be called throughout passwords and resting avarabletowaintetheciretstatu ofthe cde thsway we can se the cea element without being the progam hangedinsie the uncon. We've ao referenced some newly coport ine detector: ldUser and nena fich wel eto net users = {} status = o PAID the newlserFunctionisnext: deF nenuser(): Nextweneedtodefiesome furctions Wecan_efeateLogin = input"Create’ at Togin names!) Siae ‘begin with creating the main menu, to where, after Selecingthe labia options, al users wal etu if createLogin in users: print C*\nlogin name already exists!\n") ‘def airMenuC): else: global status ‘ereatePassw = input(*Create password: *) status = input(“Do you have a login account? sersfcreateLogin] = createPassn y/n? Or press q to quit.”) printC*\nUser created!\n”) if status = *y": ‘Logins=open(“C:\\Users\\david\\Docunents\\ olduser©) Logins.txt”, “a") elif status == “n”: Logins.write("\n" + createLogin +“ * + rnenUser() ccreatePassn) elif status = “a”: ‘ogins.close() quito “Thiscreates anew user and password, and writes the entries into 3 file called logins txt (combi ing What You Know So Far em Since were using Raspberry, youwill need to specify your on location For the logins tt fle Essentially this ads the username and passwordinputs, From the ser, to the existing users) cctionary. Therefore, the key and value structure remains; each users the key, the passwordisthe value. Creal Shin = upuec 1 ereneatogn in uses eee Se AO atrendy existstar) BRPITD Now to create the olduser Function: ef olduser: ‘login = inputC“Enter Login name: *) ass = inputC“Enter password: “*) # check if user exists and Login matches password “f login in users and users[login] == passw: print C"\nLogin successful!\n") print (*User:”, login, “accessed the system onct, tine. asctineO) print C*\nlser doesn’t exist or wrong Possword!\n”) ‘There's afar bithappening here. Wehave login and pasow variables, which are then matched tothe users dictionary IF there's amatch, then we have a successfllogin ‘andthe time and date ofthe loginis outputted. If they don't match, then we print an error, and the process starts again pape a Finally, we need to continually check thatthe key hasn't been pressed to exit the program. We can do, this wath hile status != "a": status = displayMenu() ‘though seemingly minortwo nes, the while Sie) loop is what keeps the program running. At the end ef every funtion checked agate erent salue of tu F that lob value then the program conns Fs equal 0 ‘then the programcan cut while status status gt mainMenu () You cnnow create users, and then gin th Suz their names and passwords, with the logins.txt Flebeing cesta store the login dita and sxccessd logis bing timestamped, Now ts upto youto further improvethe code Pernaps ou can mpot thei of ceated ses rom a previous seson and spon aaicesullgh, dep gph? Using } Modules Modules are where you can take CM Cu oe Seer NCR Ma ce Caran ue ee eer Eee Com Ras PM nS ete Ae) ECU eee acs Want to see how to make better Pete r ncd Reece ea ee ects urs Meee cue eee ern ia Coca Cee Drea Pree ee oe Create Your Own Modules EP Using Modules ) Calendar Module WORKING WITH DATES ‘The Calendar module is built into Python 3. However, if it's not installed, you can addit using pip install calendar, as 8 Windows administrator or sudo pip instal calendar for Linux and macOS. Launch Python 3 and eter: import eaLendar to ole? ‘all up the module and its inherent Functions. Once itsloaded into memory, start by entering sep=calendar. TextCalendar(calendar .SUNDAY) sep.prnonth(2@19, 9) ‘There are numerous Functions, within the Calendar SUE? S) module, that may be of interest to you when Fortming your own code. For example, you can display the number of leap years between two pectic years: ‘eaps=calendar.Leapdays(1900, 2019) printCleaps) The results 2, starting from 1904 onward, (Pen a785n You can see thatthe days oF September 2019 re Sew displayed ina wall calendar fashion, Naturally you can change the 2019, 9 part of the second line, to ary year and ‘month you want, a birthday for example (1973, 6 The Fist ine configures TextCalendar to star ts weeks ona Sunday you can opt For Monday iFyou prefer ED wrscrostroesson FETED You could even fashion that particular examole into apiece of working, ser interactive Python code: ‘import calendar print(“>>>>>>>>>>Leap Year Calculator File) and create aTrue/False while oop: ‘import pygane from pygane. locals import * ygane. 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.quitQ Preame Nol ESTED che Pygame window stil wont close, dont worry it's justa screpancy between the IDLE (whichis write with Tinter) and the Pygame module. I you runyour code via the command line, wil close perfectly Fine, BPI vice going to shit the code around abt now, ‘mg=pygane. image. Loadc"C:\Wsers\dovieh\ runingthe main Pygamecodewithinawhteloop Domeads\\sprite.pag") ~Temakes treater and easier to follow, Also, we've downloaded» : : Gof spritecs.y) aphic to use and we need to set some parameters for pysame! ae ‘gomewindow.blitCimg, (x99) ‘import: pygane mg =¢80020,45) pygane. init) jrceoae0.8) —s garesrindon.fLYGnnite) white running: spriteCey) ‘ganenindowpyaane.display.set_node((600,600)) _PYGaNe. A.sPlay.updateC) Pyome.display,set_caption(*Adventure Gane") for event in pygane.event.get(): Plack=€0,0,0) “f event. typenepygame. QUIT: wiite=(255,255,255) running-False RTISTD e's quickly gothrough the code changes. We've downloaded image called sprite,png, and allocated i¢to the variable defined two colours, blackand white, together _img, We've also defined a sprite function, and the Bit Function, with theierespective RGB colour values. Next, weve loaded the which wllalow usto eventually move the image. EP Using Modules) FERRER Now wecancungethe code roundagon.ths ingspeeded Gimecontaningamoverentopton thine atte unninge whilelcos.andactingthevarablesneededtomovethesonte MMe running: aroundihescreen ‘f event. type=nQUIT: import pygone runningeFalse from pygane. Locals import * [ ‘ef event: type = pygane KEYDOHN: ‘event mey==pygane.K_LEFT: unningetrue xchange=-5 LF event keyenpygane,K RIGHT: xchange=s ——o ‘fF event: typennpygane: KEYUP: |___ = ‘if event. keyeepygane.KLEFT or event ‘ing-aygane. image. LoodC“C:\\Users\\davigh\ — Downtoads\\sprite.png”) — ef spriteceyyd: — arevindon.LitCimg, Cx,99) ganesrindon. ALT te) x0(800"0.45) |} pygane display update) y=C600"0: 8) Pygane. quit xehange=0 BETTE DD) oy the code down and, using the left and right arrow keys onthe keyboard, you will be able to move your spite across the bottom of the screen. looks like we have the makings ofa classic arcade 20 scrolerin the works. — Fear TED wrrcrostnorsson (_ Pygame Module ea” ESTED Wconnowimplementafew aditons andutiise ygane.display.ffip0 some previous tutorial code. Theneweleents re ‘lock tick(60) inthe Subprocess module, of which one Function alows sto launch ‘continue second Python sit fom within another and we'regoingtocrestea ‘break New Fie cal pygametity — @ BETESET BD When verunthiscode, will clsplaya 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. Overal the effects quite good, but there's always room Forimproversent. —— 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. Lets start crating asetf bis athamatis ole? Functions. Multiply a number by two or three, and square or raise a number toan exponent (power. Create a New File inthe IDLE and enter def timestnoGO: a return x * 2 f a def timesthree(x): = return x*3 = def squareCx): return x * x def poner(x,y): o return x ** y FETTER 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 Now we gong toate function defintons SUE? E) ‘out of the program and into a separate file. Vighightthe function defntons and chose Ea» Cut Choate Fle» New Flan ee E> ast nthe new wincow We now vet separate es one wine uncon cetnton the ceher th he anton as FETIP vou now ty and execute the basic mathoy code again the errorName€rror:name'timestw! is not defined’ wil be csplayed. This is cue to tne code no longer having accesso the Function defintions the newly TER) wscrostnoeson Cceated window containing the Function definitions and : CickFile > Save As. ary this minimath.py and saveitin the same location a the axigial basic math oy program. Now lose the minimathpy window, sothe basi math.py window is lefeopen, Backto the basic math py window, the top ofthe oom ‘This wilimport the Function definitions asa module. Press FS to save and execute the program, and see it inaction. ‘We can naw make the programa little more advanced, by utilising the newiy created module to Itsull.Let'snclude some user interaction, Star-by creating abasic ‘menu from which the user can choose Now we can add the user input to get the number the code will wrk on: ‘runt = imtCinputC*\nEnter number: >) This willsave the userentered number as the variable num, “om mimimacn Gepost © print ("Select operation. \a" Prine ["2.Tames by evs") Prine ("2 Times by Three") Prine ["4_Power of") choice = input (*\ntnter choice (1/2/3/4) pum = ant(anput(*\nenter numer: *)) (Create Your Own Modules ea” Finally, we can now create arange of ifstatements to determine what todo withthe number, and utlsethe newly create function definitions Bea [Batata tame 2" Fie tae fart Rin Ope Window Hep ESTISETBD ote that forthe lst avaliable options the Power of choice, we've added a second variable: num2, This passes a second number through the Function definition called ower, Save and execute the program to see Itin action, Introducing eC Introducing C++ Epes fore en EME rc) language. Most of what you see in Care Nee Sa Cea cea MM MU ots inux, is created using C++. Being able Ree eet eased Pe nme tac) PRO een slog) Cour ue Seu eu erent Peete sk ce) eerie eeu ees PU eam Te PER ene U tc) Deets Bier Cee acy equipment and software needed to get up and running with C++ For Windows, Mac and Linux systems. Why C++? ramus ee ener mec] Polecka tee Meel eye kt ae kena ner eN ete ac nol the original C language, and is a general purpose object-oriented (OOP) environment. ny 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 start ofthe golden era of home cammputing, C+, or ather C with Classes, was the brainchild of Danish computer scientist Bjame Stroustrup, while working on his Ph.D thesis, Stroustrup plan was to Further the orginal language, ‘hich nad 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 importantly, it was 99% compatible with the orginal C language. Tis meant that, beyond the mainstream computing labs, regular people who dicn’thave access to te mainframes an large computing dete centres could use it. Co1'simpact inthe cial word is immense. Many ofthe programs, applications, games, and even operating systems are coded (Co# code ie 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 writen largely in C++ (with some ‘other languages mixed in depending on the Function), and the lites ‘oFNASA Spacek, and even CERN use C++ For various applications, programs, controls, and umpteen other computing tasks As wall axbeing an easier addition to the core Clanguage, C++ is aso extremely efficient and performs wel across the board. Ths bigher level of performance over other languages, suchas Python, BASICand such, makes ian ideal development environment For ‘modern computing; hence the aforementioned companies using it sowidaly wv bnpubeatonscom Microsof’s Visual Studio sa great, Free ‘enviconmentin which to learn C++, C++ puts the developer ina much wider word of caling. By ‘mastering ++, you wil find yourself being able to develop code For the tkes oF Microsoft, Apple and so on. General, C++ developers enjoy higher salary than programmers 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 crete 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++ windows10. debian C Why CH? summary Improvements tothe engine, or when creating anew game, iF the developers want to add something thatthe engine can-do, they willuse C++ to create the new content a ink between two clfferent 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 lh 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

You might also like