0% found this document useful (0 votes)
448 views198 pages

The Essential Coding Manual November 2019

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

Uploaded by

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

The Essential Coding Manual November 2019

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

Uploaded by

nelu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 198
BDM rs e& & Manual Ser ies The Essential Coding Manual M Step-by-step Guides @ Coding Projects ® Master Coding Discover more of our complete manuals on Readly today... untu inten Manual Manual The Complete en The Complete Photoshop Linux || [ey Elements Manual Manual Gees Instagram Weare . The Complete . The Complete iPhone} iPadOS iOS 13 Manual Manual c Eas Bs soe ‘ BDM's Manual Series The Essential Codes the lifeblood that courses through the veins of ‘our modem digital world. Coding is the power behind nearly everything you interact with, whether it's your TV, washing machine, or even your microwave. Rarer It’s the driving force behind the Internet and it’s err used by NASA and other space agencies; CERN scientists utilise millions of lines of code to make sense of the voluminous data from the Large Hadron Collider, and engineers the world over need code to help design and build everything from two-bed houses to earthquake-proof skyscrapers. The Essential Coding Manual is your gateway to how code works, how you can apply it to your own projects and how you can expand your knowledge and skills Within these pages are tutorials, hints, tips, and ideas that cover Python, C++ and Linux Bash Scripting and which will help build a solid Foundation that you can use to better understand our digital world, or apply to your Future job prospects. Let's start your coding adventure, where the only limits are your own imagination. er Cro inden Ta Picken Being 3 Programmer 10 ABrieF History of Coding 42. Choosing a Programming Language 14 Creating a Coding Platform 46 Using Virtual Machines Equipment You will Need Starting Python for the First Time Your First Code 42 Saving and Executing Your Code 44 Executing Code from the Command Line 46 Numbers and Expressions 48_Using Comments 50 Working with Variables 82 54 coon eed User Input steps nto the Creating Functions Cee) 56 Conditions and Loops ea Pg Ces By aoa of code, save it and 60 Python Errors Cee ey sits (62 Combining What YouKnow So Far [AS eagi Lobia i} youneed, 22_Why Python? 24 What can you do with Python? 26 Python in Numbers 28 How to Set Up Python in Windows 30 How to Set Up Python in Linux 32 Python on the Pi 34. Getting to Know Python Usts Tuples 70 Dictionaries 72. Splitting and Joining Strings 74 Formatting Strings 76 Date and Time 78 Opening Fes 80. writing to Files 82 Exceptions 84 Python Graphies 86 Combining What You know So Far 90 Calendar Module 92 OSModule 94 Using the Math Module 96 Random Module 98 Tkinter Module 100 Pygame Module 104 Basic Animation 106 Create Your Own, Modules 108) Coding with C++ 110 why C4? 112 Equipment You will Need 114 How to Set Up C++ in Windows 116 How to Set Up Cr+ ona Mac 118 How to Set Up Cr+ in Linux 120 Other C+ IDEs to install 2 Mat PR Cre) Og Ital ses eye Tue) cy 124 Your Fist C+ Program 132 Variables 126 Structure ofa» 134 Data Types Program 136 Strings 128 Compile and Execute 439 Cy Maths 130 Using Comments ren 142 User Interaction 146 Defining Constants. 144 Character Literals 148 File Input/Output Fas 152 while Loop eer 154 For Loop beginning, middle, and end. Fema rT 158 IF Statement 160 IF... Else Statement 162) Coding on Linux 164 Getting Ready to Code in Linux 166 Creating Bash Scripts -Part 1 168 Creating Bash Scripts - Part 2 170 Creating Bash Scripts -Part 3 172 Creating Bash Scripts - Part 4 174 Creating Bash Scripts - Part 5 rid Renin cari esc) systems, ecru dees ot ad 178 Creating a 188 Common Coding Loading Screen Mistakes 180 Text Animations 190 Beginner Python 482 Tracking the ISS Mistakes with Python 192 Beginner Cr+ 186 Using Text Files Mistakes For Animation Tee ome ie inn a The World of Code The word oF Coe Where to start learning how to code? COE IL CUA rants iret ta Bm cng ce) ene ees eee unlimited number of tools to help Nr a heey ts where do you begin? The World of Code > 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 Pena ‘Times have changed since programming in the'80s, but the core values stillremain. “It's up to you how far to take your coding adventure!” Being able to follow logical pattern and ‘an end result is one ofthe most valued ski of a programmer. (Being a Programmer ei” MORE THAN CODE For those of you old enough to remember the'80s, the golden era of home computing, the world of computing was avery different scene to how its today. &-bit computers that you could purchase asa whole, as opposed to being in kt Form and you having to solder the parts together, were the stuff ‘of dreams; and geting 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 ist 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 their own content, their ‘own games; or simply something that could help ther with their homework corhome finances. The simplicity ofthe s-bit home computer meant that creating something from a ew lines of BASIC code was achievable and so the frst generation of home-bred programmer was born, From that point on, programming expanded exponentially. It wasn't long before the bedroom coder wasa thing ofthe past and huge teams of esigners, coders, artists and musicians were involved in making a single ‘game. Ths of course led to the programmer becoming more than simply someone who could Fashion a sprite on the screen and make it move atthe press ofakey. ‘Naturally, me has moved on and with tthe technology that we use. However, the Fundamentals of programming remain the same; but what fexactly does ittake tobe a programmer” “The single most common tat of any programmer, regardless of what they'e doing is the abilty to see a logical pattern. By this we mean someone who can logically Fellow something From start 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, it takes time but once you stat to thinkin this particular way you will be able toconstruct and Follow code. Second to logicis an understanding of mathematics. You donit have to be ata genius evel ut you do need to understand the rudiments of maths Mathsis all about being able to solve a problem and code mostly falls under the umbrella of mathematics. Being able to see the big pictures certainly beneficial forthe modern programmer. Undoubtedly, asa programmer, you willbe part ofa team ‘oF other programmers, and more than likely part of an 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 own 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 nteract with it Thereis of course a lot more involved in being a programmer, including learning the actual code itself, However, with time, patience and the pe peant = n and ways in which to ‘talk’ to a computer ats ge eee eaten Eline] Cee aire _Mod.use _z = ee ose ae ee "ob.select= 1 ~_ oe aie =1 cee Mes (aera Selected" + str(modifier, irror_ob.select = 0 » bpy- Pera ab 4 eS ae jects[one.name].sel Coreen Een orantir mainntent a een tes for accessing and manipulating databases. Although SQLis an ANS! ‘(american National Standards Institut) standard, there are different versions ofthe SQL language. However, to be compliant, they all support at least De pean eee ict cece ee en aA Ree oe ena pre borer operates ets See ee er ee ee nny ee aes Sere ena reenter Leeann Citisan elegant objectoriented language that enables developers to Se near tee ee ag Framework. You can use Cito create Windows cent applications, XML Reet eer re eee ees erste aA ea reste ati onan Cree etree cea ee eee ry Features. it was designed witha biss toward system programming and ee ree ne od Beret ee ne See Cet comm” eae e er eet ey Sete re ion state tera Co ae ree year een ern t teeta na Se ee Pee eer recy tatu eats ee eee ee ees Se Cer Features are that's easy to use, supports both procedural and object oriented (oo eee erento ants sage recre Dic Leerars rece eal enter anes The World of Code Creating a Coding Platform Pers Thankful, cading atthe Foundation level doesn't require specialist equipment, for atop of the range quid hydrogen-TO certsccmitasoteocunt stieurger »= 0) Pefresipoutcursor): certTuchataoreracen i j iin Hi poi arog scitontronue) weld, acrayeerL-paine(oras ¥) { eee enn i mea Se! colum.cetcomt) « 9) >= 0) ins j.< colum,cotcnmt()s io) { ‘regen Getrabwa deh) ir environment or users. Operating systems, suchas Windows, macOS ‘andsuch are usually acambination of C++, Ci, assembly and some Form of visuabased anguage. Games generally use C++ whist web pages can use a plethora of avaliable lanquages such as HTML, Java, Python and soon, More generat purpose pragrammingls used to create programs, apps, software or whatever ese you want to call them. Theyre 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 generat purpore language. Python's what's known as a High-Level Language in that it‘talks tothe hardware and operating system using a variety of arays, varlables, objects, arithmetic, subroutines oops and countless ‘more interactions Whist ts not as streamlined as a LowLevel Language, which can dea drety with memory addresses, call stacks and registers is benefit isthat ls universally accessible ‘and easy to learn, vole. java, Jinport java. lang.reflect.*; Jelass_tnvoke { public static void min string () args ) { tye aes ¢ = Class. fornane( ari tbody = Cgpinetbed APL), hw cass Object tee = invoke nu, mull) SySten.out printint Stivoked state wechod: * + args{3] +" of class: " + args[0) e Fc uihte argsltetaltss © pee 3: caceh ¢ Classhoxroindexcepeion e 5. [class fornanet,") cance, Find the’ class ch" ( Nasuchwethodexception e2.) ¢ TT that method. doesn't exist ) kareh tf STlepalaccesstxception 3 2 { Zive don't Rave permission to invoke that inethod atch ( anvocationrargetexception > Fan Sacepeian ocurred wniie invoking that inechod ec Systen.ove printing 7 eshieehod thre sa: * + e8. getTargetexception. ")"3: avaisa powerful language that’s used in web pages, set-top boxes, Tvsandeven cars. ¢ Why Python? em” Python was created over twenty sik years ago and has evolved to became an ideal beainnerslanguage for learning how to program a computer's perfect forthe hobbyist, enthusiast, student, teacher and those who simply need ta create thelr own uniqueinteraction between either themselves ora piece of externa hardware and the computer sel. Python ire to downoad, install and use ands avalable for Linux, Windows, macOS, MS-D0S, 05/2, 60S, IBM series machines, and even RISC OS. thas been vated one ofthe top five programming languages in the word and continually evolving ahead ofthe hardware and Internet development curve. So to answer the question: why Pythor? Simply put i's ree, easy to learn, exceptionally powerful, universaly accepted, effective and 2 superb learning and educational tool BASIC was once the starter language that early ‘sbithome computer users learned. Python sa more modem take on BASIC, i's easy to learn _and makes for an ideal beginners programming language. mines What can you do with Python? .COnS, .rel—has! ee ee E peninres epee ieeereemenind miata gy. ut hes sane perimeter meena tina : oer eee te sii Foci seriabeylarirs eke edocs ean eer sect ets r—) arte ates cat ca a Shame ere rts er eee eee nes sence as ected rr ee ee ee [NASA scientists and engineers are able to get tothe datathey Fant bnly Peete ete reread tc nga eee aes STs Hietioeetcenton tert toe Cree he ee eee tes eee Pee ere ret ee eerie pattems, trends and interactions between humans, socety and technology. OF course, ie’snotjustimited to those areas big data is currently being used ina vanity of ee ee ee eee etn Os Rohe usta Cece rei etter te etter ata eee eer oe eer ea De nee ane Cenc Reasn arte “There are courtles libraries and freely avaiable modules that enable as, secure and See eee ee er erect try Forexample, CERN usesa custom Python module to help analyse the 600 milion colisions pee ane Cc ee eer Ispresent to help sift through the dataso scientists can get tothe content they want. without the need to leam afar more complex programming language. Nate auc == et ets Pelosi ay Ce ae unt? a umbreliaterm used foray computing process wherein the Se ec eer eat Peace ee a) See ee ei es However, lis simply the creation of autonomous robots ee oc er (eer een eet ey ee eter eet eee es Centers paar This model can be applied to Facebook, Google, Twitter, Ce eee erate eeu cure ern) toward similar celebrities? This a prime example of using Al eet ee eee era ‘Although you ent find too many tiple rated game Spotiy, for example, uses Python based code, Pan | a eS ee among other things, to analyse your musical habits and oer playlists based on what youve eee et once tes ‘moving Forward, Python ist the forefront oF the way the intemet wll workin the Future. tran many ofthe highanking madern games rain use of Python n gaming comes inthe Form of scrotin, ner Python srt can aod customisation tothe core game eon Py aves peace ee ances pote DN ee erty wh yer's cents de eer terre ae ee ea a game Python ee ne ee ea) thatcanbe enabling the server eer eae rs srinto ada sages and automa deo Care eer er ee ‘dynamic and highly secure web apps, enabling interaction with ‘other web services and apps suchas instagram and interest eee er ees ener ees PYTHON EVERYWHERE Cee ee ee ue aay Sea a a a able to take you into the next generation of eee ce eet hobbyist. SO eet Proton Coe een) Coding with Python ) nomen There’sa lot to like about Python, but don’tjust take our word for it. Here are some amazing facts and Figures surrounding one of the most popular programming languages of recent years. @® Alexa, Amazon's Virtual Personal Assistant, uses Machine Learning are the ‘Python tohhelp with two most used Python speech recognition. examples. ce Data analysis and PYTHON AND ( LINUX SKILLS ARE THE THIRD ‘Mthonusetiemes’ _ MOSTPOPULAR ictancerarschurre comonnoanases LTSKILLS IN. tooperate between oer coment ‘Porc pecape. THE UK. on, gs —\ on: oes yi | “Cama (OVER 75% OF 90% OF ALL T'S ESTIMATED RECOMMENDED FACEBOOK POSTS. ‘THAT OVER 75% OF ‘CONTENT FROM NETFLIX ‘ARE FILTERED NASA'S WORKFLOW IS GENERATED FROM ‘THROUGH PYTHON: ‘AUTOMATION MACHINE LEARNING ~ ‘CODED MACHINE SYSTEMS ON-BOARD CODED BY PYTHON, LEARNING. ‘THES, USE PYTHON. 16,000 seu? ttitittt 16%: etttiiit “2 Se MOST SOUGHT-AFTER reare over on jobs posted every ixmonths inthe UK. JOBSIN-THE UK. ] | 4 Python Dat Sciences oosle isthe top Data Science, Blockhan New Yorkandsan thoughttabecome the — company forhing python ~~ and machine Leaming Francie are the op inet soughatir in evlopets sly aretheFestst growing Python developer cles the coming eos followed Mcrosoh Pytnon coding hls inthe wort onde ouetbe intycaneuuss naa idetl nt dags eek Python developers enjoy an average salary of eae —— £60,000 (ws) er) V3 i) (3) 19596 OF ALL BEGINNER. 175% OF ALL PYTHON, 79% OF ALL 49% OF WINDOWS CODERS START WITH DEVELOPERS USE PROGRAMMERS 1ODEVELOPERS : AND STILLUSE, PYTHON 3, WHEREAS USE PYTHON USE PYTHONS. PYTHON AS THEIR 25% STIL USE THE REGULARLY, 21% USE AS THEIR MAIN PRIMARY OR OUTDATED PYTHON 2 ITASA SECONDARY PROGRAMMING SECONDARY LANGUAGE. ‘VERSION. LANGUAGE. LANGUAGE. ) Coding with Python ) How to Set Up Python in Windows WVrere etete) sily install the latest vers ea Tree ru Tt PCE Aa Neuse een anita eee eset platform of choice for building their code, it's still an ideal starting point For beginners. INSTALLING PYTHON 3.X Microsoft Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. 's an easy process to follow. ‘Thankfully, Start by opening your web rows to warn python Sie" ‘org/downloads/. Look For the button detailing the ) Coding with Python How to Set Up Python in Linux PYTHON PENGUIN Linus 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 indifferent ways, so For this particular tutorial we will stick to Linux Mint. Fist you need tascertain wich version oF Python ‘Once the update nd upgrade completes ents uid is currently installed in your Linux system. To begin as sython3! ==version again to see if Python 3.x is vith drop nto Terminalsesslon fram your dstzsmenu oF the updated or even sale, as ong a you have Python 3, youre Casale Theys funing the most recent major version the numbers after the 3. dicate patches lus Further updates. Ren they're unnecessary, but they can contain val new elements. davidedavid ine: ~ Fle Eat ew Search Terminal Hep BEESE ex enter:python’==verston into the Terminal screen. You should have the output relating to version 2x oF Python inthe display. Most Linux distr come with both Python 2 and 3 by default, s there's plenty of code out there still avalabe For Python 2. Now enter python ==verssien. davidedavie-mi file Ect View Search Terminal Help orcs eres version, youll need to build Python From source. Ke Start by entering these commands into the Terminal davidedavid-nint:-$ sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev . z * LibncursesnS-dev libssl-dev Libsqlite3-dev tk-dev FETTER | ovr cese we have bath Python 2 and 3instaled, Libgdbm-dev Vibc6=dev Libbz2-dev As long as Python 32xxisinstalled, then the cade in cur tutorials wilwork Is always worth checking to see the dsto has been updated with the lates versions, enter: sudo apt-get update 8& sudo apt-get upgrade to undatethesyster Open up our Linux web browser and goto the SHEE Python download page: https://www.python.org/ ‘downloads. Click on the Downloads, fallowee by the button under the Python Source window. This opens a download dialogue box choose alcation, then sart the downiosd proces, Inthe Terminal goto the Downosds folder suse byentering: ed DownLeads/. Then unzip the contents ofthe downloaded Python source code with: tar =XVF Python-3.Y.¥tan.x2 (replace the Y's with the version numbers \yuve downloaded). Now enter the newly unzipped Foe with: ed Python-3.¥.¥/, on Folder, enter PED wihintne ry “configure Sudo make altinstalt his could take awhile, depending onthe speed of your compute Once finished, enter: python3.7 ==version to check the latest installed version. You now have Python 3.7 installed, alongside older Python 3.xx and Python 2 How to Set Up Python in Linux 9g For the GUIDLE,youlneedto enter the flowing Guz) ‘command into the Terminal: sudo apt-get instoll ‘dled The IDLE can then be started with the command: {d@3. Note, that IDLE runs a ciFferent version to the one you installed from source widedvi in: -/DomlenePthon 3.72 FRET R You aconced PP (Pp installs Packages), which is atoolto help you install more modules and extras Enter: sudo apt-get install python3-pip Once PiPis installed check For the latest update with pip3 install -upgrade pip ‘When complete, close the Terminal and Python 3:cwillbe avalable athe Pragramming section in your dstra’s menu, By PYTHON ON macOS Installation of Python on macoS can be done in much the same way athe Windows instalation. Simply goto the Python webpage, hover your mouse pointer over the Downioads ¥ inkand select Mac 05 x from the options, You wl then be ‘uided to the Python relesces For Mac versions, along with the necessary installers Fr macOS 6 bit For 05x 10.9 and later <-ED Python on the Pi Fr Te Reel Ron ae eens) ERR eee Ee thought to one of the best coding bases available: The Raspberry Pi. The Pi has many. advantages for the coder: it’s cheap, easy to use, and extraordinarily Flexible. THE POWER OF PI While having a far more powerful coding platform on which to write and test your code is ideal, it's not often Feasible. Most of tus are unable to jump into a several hundred-pound investment when we're starting off and this is where the Raspberry Pi can cores ‘while having afar more powerful coding platform on which to Soren er none eet or ae Pes eer eee ite ar ea Seen eet etait neuter ad tg ee ce) pr eet ene cd eee cere Pee een) ete eee et Lenn Se ete a) ee ae rete Firmly pushed tothe Frefront. The Raspberry Pi uses Raspbian eee eee Une 05, orto be more accurate it's a Debiabased distribution eee a ere ners CE ete eet Ce re ae ie aca Raspberry Pi Foundation has gone the extra mile toinclude a vast Fange of Python modules extensions and even examples, out of ee cee es fete eel Saree itanreeee pete ee eee eee eens ee com/tseraspberry+pipost_type=product) and you can stat coding with Python as soon as the desktop has loaded. Rees eee se ee een eceee eee ee erty ee eee eet ener od ee ec Ree eee ae eer a Ce ee eet Sea ee eaten Power socket anywhere in your house within range of your wireless router, Aslong asthe Plis connected, you willbe abe to remotely pera ea eee ats siting in Fron ofthe P with keyboard and mouse. Using thismethod saves lat of money, as you doit need another eu een tee oe) Be eee et eaten ee ete) Cee ee ee) Perens eater Peres Peer etre) eee ces a tee gen Seite eet ne Lente Cees at aE a eer catered Raspberry Pi Foundation has included out ofthe box. The reason for this that the Raspberry P's goalis to help educate the ser, whether thats coding electronics, or some other aspect of eee eC ern ee crs IDEs For the user to comple Python code on; as well as both Python eee ere aac ar es Pare ‘There are other advantages, such as being able to combine Python ‘ode with Scratch (an Object-Oriented programming language PMc meen) being able to code the GPIO connection onthe Pto Further control any attached robotics or electronics projects. Raspbian aso includes Sense HAT Emulator (@HAT isa hardware attached piece of Ce ee te eo pees cree tiaras Coe eee peepee tea er en Lea eee ee en ena Resirentert ater eee eee Pret reeerrieetena ae ere eae ee entree re eter ees CEES acs Everything you need to lear to code with Python is rete at os 2 from the original tosellout eth anew Scie, Gabe, quadeo 4A? procesioranda choice oF 1CB, 268, o¢ tea becoming true desktop computer. addon, the Pi was launch raring decsion to de dua monitor support inthe form of apa oF ro HOMipors.Youlalsofind a pair oF USB 3.0 iuetocth 5.0, anda GPU that's capable of handing ak resolto E530 graphics eee ey Renata Inadtion to releasing the Pi the Raspberry I team ofthe Raspbian operating system, codenamed Buster re mainly intne wth the et of arapical drivers and In short, what you seein this b spberryPiaand Raspbian Buster! en =P Coding with Python Getting to Know Python ne Recetas rd Seno rine cme tcmieleutee anak nen ty to understand. WHAT IS PROGRAMMING? Ithelps to understand what a programming language is before you try to learn one, and Python is no different. Let's take 2 look at how Python came about and how it relates to other languages. ‘programming language isalistof instructions that ‘computer follows. These PROGRAMMING RECIPES S202 Progansareikerecpestorconostes.8 iT —- | ail recipe to bake a cake could go ke this 1b Ie Ete or Sites Goo out 100 grams ofselfasing fourin a bow ‘Add 100 grams of butter tothe bowl, legac aE) ‘Add 100 mililitres of milk ‘or playing a music File, or eae fo el au Se... — seu averd ten isa programming language CODE coeavedn@elie seis: Aotlkesrecbeaproancoviisof stun hte flow byob svete order Apron ot abe sale hun ets een ecanea tora EW ne tort = Oh Netherlands asa successor to a ‘the ABC language. butters 38) ears FS samenecmny opEaeres Peer ar i fabera on PROGRAM COMMANDS ‘You might not understand some of the Python commands, ke bowl append and cake.cook(bow! “The Frsis alist, the second an object; welllook at both inthis book The main thing to know i that’s easy to read commands in Python. Once you learn what the commands do, it’s easy to Figure outhow a program works. sonal wun 19 HIGH-LEVEL LANGUAGES Computer languages that are easy to read are known as high evel This because they fly high above the hardware (also referred toas ‘the metal Languages tht “ly close tothe meta, lke Assembly, are known a5 “low-level. Lowevel languages commands read abit like ths: msg db ,@xa len equ $= msg PYTHON 3 VS PYTHON 2 Getting to Know Python ZEN OF PYTHON Python letsyou access all the power of acomputerina language | that humans can understand. Behind al this an ethos called “The Zen oF Python” Thisisa collection of 20 software principles that influences the design ofthe language. Princilesinclude “Beavtful is better than ugly” and “Simple s better than complex." Type ‘import: this into Python andit wil splay all the principles. ee eee eager ae ge ert Cree ies Cie Mes pene terre Peer are enter Rares Lente PRERPREEER 5 2009 Python 3 area with several new eee ‘These features CO TGs oi Index aut Started with - with Python RS ss) arate cena) Pee RS EC rd steps in the wider world of Python and Neue sais tis piece of code, save it and run itin the Pues Pee) Oe Mem ens eo Peer srs) eae Re rN CO eon ee yeh ede its Emel men ae an Serato) Sr Eetncine Executing Code from the Command Line Pee ee eas oe ee Soe) eran Meas Cetera Pee eed Eee 60 Python Errors Cen ae cere WHAT IS BERG ae PO ee ac Cae CCS! [ao Cer eos Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction All languages Brand new content ol Tesi c) AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu ) Getting Started with Python Starting Python For the First Time ein iioicc cisco acces c sarc mac Net eee Meena oe emetic CM! tere Renmei Rent eas on STARTING PYTHON For those using the Pi4 and new Raspbian, drop into a Terminal and enter: sudo apt-get install idle3. Older versions oF Raspbian already have the official Python IDLE pre-installed, winter deen sedciconte EERE rorcannte sete 2 SUED sen sutonfolowecby Srogrmiming= Python 3} een wi splay the ALE Tis openthe Python 3She Windows and MEClSers <2) aver 4 pac seem terte nent neil spay he find the Python 3 IDLE Shell From within the Windows Start button we scaly Byron nes ne proses rmeny andi Finder Felevant output Tresielawteesoucnencotandaethe EARP Teytonsalacsveymeniien ctr Sieve ‘responses and output of code you've programmed Sus since code is basically a series of mathematical intaPython Thisisakindof sandbox whereyovreabletotyeuk interactions with thesystem.teges, wich are the vite some simple code and processes. sequence of whole numbers can easiy be added, subtracted, ‘multilied and soon Starting Python for the First Time Gal PIR wile that's very interesting, is not particularly PERI the Python DLE a configurable environment. ‘exciting, Instead try this you doi ike the way the colours ae represented, Gaeee then you can always change them va Options > Conigue OLE and a cicking onthe Highlighting tab However we dort recommend that Asperthe code we enteredin Sublime inthe instaling a TextEdltor az you won’rbe seeing the ame az our screenshots. section ofthis book This alle mre since youve st arodvced Justlike mos programs alae reales ofthe sere your first bit oF code. The Print command is Fairly sue ‘operating system there are numerous shortcut selFexplanatory, it prits thing. Python 3 requires the bracketsas _keysavalable. We don'thave room for them allhere but within the well as quote marks in order to output content tothe screen, inthis Options > Configure IDLE and under the Keys tab, you can seea list case the Hello everyone it of the current bindings. p>> print("Hello everyon a everyone! ‘You mayhave noticed the colour coding within ‘The Python IDLE isa power interface, nd one Sup the Python IDLE. The colours represent differen Suit thav’s actualy been witten in Python using one elements of Python code. Theyare of the avalable GU toolkits Fyou want to know the many sand tuts forthe Shel we cacommend you take afew momento view BlackData and Variables __Slve—User Functions recommend youtake afew moments toview Green-Strngs Dark Red Comments vu dcsython crabrayii html which dais many of th Purple Functions Light Red-Error Messages shane Orange Commands —_ IDLE Colour Coding — Purnle ee ee = ieage | comes a an me E ane [eee | ee a Your First Code Sen Ma mde en Gn Cena emirate tel tr ead eon ene eal cles Se ne eu CMe eet ete omctoea cubes PLAYING WITH PYTHON ‘With most languages, computer or human, it’s all about remembering and applying the right words to the right situation, ‘You're not born knowing these words, so you need to learn them. ifyouive dosed Pthon 3I01E,reapenitin Youcanseethatisteadof the umber the Sue whichever operating system version you prefer. In EE ‘output is the 2+2 you asked to be printed to the the Shel enter the Farr flowing screen The quotation atk ar defhing whats beng outputted a tothe DLE Shall to pn the tal of 22 youneedto remove printC*Hello”) tthe quotes: print (212) Justas predicted the word Helo pears in BRED recreates Siere the Shell as blve text, indicating output from a Suz ‘and so on to the Shell, An easier way isto use a String It’s Fart straightforward and doesrferequire too much vatiable, whichis something we will cover in mere depth later. For ‘explanation, Now try: row, enter primtce2i2") me EID cos anuatseris-oiume 19 (Your First Code Gal canter ah ect carere SEP and b two values: 2 and 2. These are now variables, SHEE _and so on for as tong as their numbers stay the same, Try this: . You now have two variables containing Firstname and a surname and you can print them independently, Teouncolvelstsencoastvecsrert | EERAAB \wewcretozpohesanerosine2s before, SMePe values of both a and b individually, as you've asked uae) using the + symbol, the name wouldn't appear them tobe printed separately. Fyeu anttoadathem up.youcan_correlyintheutput in the Shel. Ty use the allowing primtCnanessurnane) a You need aspace between the two, defining them as two separate This code simply takesthe values of aand b,addsthem together values and not something you mathematically play around with. and outputs the resut. Youcnpayarondwandsteetincrervitie EMRE ton oucansepte the over Suary and the Print Function. For example, you could Suerdo with a space using a comma: ‘ssh varables for sommes are : = print(nane, surname) — ‘Alternatively, you an ad the space ourselves: print(nane+” “+surname) ‘The use ofthe comma is much neater, a you can see. Congratulations, you've ust taken your firststeps into the wide world of Python, =D Getting Started Python) Saving and Executing Your Code While working in the IDLE Shell is perfectly Fine for small code snippets, it's not Coser ema cune nan ecu ea ales un ely introduced to the IDLE Editor, where you will be working from now on EDITING CODE ‘You will eventually reach a point where you have to move on From inputting single lines of code into the Shell. Instead, the IDLE Eelitor will allow you to save and execute your Python code, Fist open the Python DLE Shel and when kup, You canseethat these colour coding sin place ua lick on File > New File, This will open a new window ue inthe IDLE Editor as its in the Shell, enabling you withUntidedasits nme. Tisisthe Python IDLE Eto endithink._tobete understand hats ong on wth your cde However Youcanenterthe code neededto create yourfture programs. execute the code you ned to rat save ress FS and you ge 8 Save..Check box open. Te DiEestorsforatimensandounsse.2 RTE clckonteOxtutorin Sve boxand select Sieve ‘simple text editor with Python features, colour Si) destination where you'll save all your Python code. coding and so on; much nthe same vein as Sublime, You enter The destination can bea dedicated Folder called Python or you code 35 you would within the Shel sotaking an example fromthe _canjust dump it wherever you lke, Remember to keep atidy drive previous tutorial enter though, tohelp you autin the future. print¢*Hetlo everyone!" ese pa BED 2 tse vine Saving and Executing Your Code Gal Enter name or your cade, hele'for SIE ‘example, and click on the Save button. Once the Ayton code s save rs exected andthe output wile cetedin the DLEShel nts cae, the words Hello eveyone Tnsthorbevsmay cor gion ct you open he fie lcatoncf te saved Python Siery code, you can see that it ends in a py extension, ‘hts the default Pithonfe name Any code you ees willbe \whatevepy andy code dounlosdd rom the mary erat Fon ecorce tes willbe py list ence tha te codes wrkten foxPython FAIR Lersextend the code and enter few examoles from the previous tutorial: uz bez nane="David” surnanes"Hayward” rint(nane, surname) print Carb) Ifyou ress F now you'll be asked to save the file, again ast’ been ‘macified From before Ifyou clkthe OK button, the fle wil be uae) ‘overwritten with the new code entries, and executed withthe output nthe Shel e's not.aproblem ith ut these few tnesbut you were to edger le overwring can become an issue. Instead, use File> Save As rom within the Editor tocreatea backup. Now create anew fle Cos the Er, nd open Suit ‘anew instance (File > New File From the Shell), Enter thefolowingondsovet as helo a="Python” boris" "cool" print(a, b, You wilusethis code nthe nextutora Getting Started with Python Executing Code from the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py let's see how you can run code that was made inthe GUI at the command line level your operating system, Saeed he Sta 0-2 search For CMO, then click printcay Commang Line returned You can see thatit works exactly the same and macO users can get a to ther command ine by clicking Executing Code from the Command Line Python 3 code fromthe thon The est of run SHE Python 2 command line is quite obvious. Whilst it cer ext to eave the commandll session and return you back othe corm: prompt. Enter the folder where you saved the code from the Coesnterror out in any way, cue to te differences between the previous tutorial andlstthe available files within; hopeFullyyou _wayPython 3 handles the Print command over Python 2, the result Should see the hello fle isnt as we expected. Using Sublime for the moment, open the helo py fe. Bnei TST LEED forsicruncnertnetolowngicctie. — MEMLRAD rye gong totemporrylavetherforche commanding Imoment enduse Sibne as an exalt you do ‘eed to use the Python IDLE. With the hello gy Fle apen, alter itto python3 hello.py Indude the Following his will execute the cod ROE ie reel youl name=input(hat is your name? “) "Python? printC*Hello,”, name) boris” cool!" 7 print@a, bye) Nataly sine thse yon code, uns the Savethe help fle ard crop bck othe Siu ‘syntax and layout that’s unique to Python 3, it only. SUP ‘command line, Now execute the newly saved warisubengovtsethe ythonsconmand Fou ie uytiesame | dei vahythen by ett python3 hello. py python hetlo:py The result wil be the exiginal Python is cool statement, together with te added input command asking you for your name, and ‘splaying it in the command window =D Getting Started wi Python) Numbers and Expressions Ween ecient crue emer ru Mra eas tea ei Meee Leet cohol TROL Sno Lala oman ae RN Cea NR ol LC IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, maths s the driving Force behind the code. ‘pen upthe Gversion of Python 3,5 mentioned You canuse athe usa Mathematical operations Sue ‘you can use either the Shell or the Editor. For the EE divide, multiply, brackets and so an. Practise with a time being, you're going to use the Shelljusttowarm our Maths few, for example: muscle which we believe isa small gland located atthe backof the yp brain (or not. 2 26283 as2ysc3r4) ce? BED ore rcciscrseaces = cna rber myentce oas crfeningponk ote Hone Poured nests SSSSEMBSIZAS opposed toa decimal answer, then you can use a double slash: Segeret oaeuasizt eiensenrphnantindesonegitelryennien Mil Ften sonal wun 19 (Numbers and Expressions Gal You can also use an operation to see the remainder leftover from division For example: 19/3 Wil display 3333333333, whichis ofcourse 33 recurring. Fyou now enter: 103 ‘This wil splay 1, whichis the remainder leftover fram dhiding rointo3. ‘Tis willbe deplayed as OI converting the SHEE integer into binary and adding the prefix Ob to the Front. Fyou want to remove the Ob prefix, then you can se Formats; *b?) “The Format command converts value, the number 3, oa Formatted presentation a5 controlled by the Format specication, the’ part Next up we have the power operator, oF ‘exponentiation if you want tobe techrical To work cut the power of something you cn usea double multiplication symbol or dauble-tar onthe keyboare: Essentially ts 22x2 but we're sure youalteady know the basis behind Maths operators Thisis hw you would work tout in Pthon [Numbers and expressions dont stop there. Python has numerous builtin functions to work out sets cof numbers, absolute values, complex numbers and ahost of ‘mathematical expressions and Pythagorean tongue-twisters. For example, to convert a number to binary, use: bina) FID 2 s0clean xpresionisa losical statement that wil tither be trv o false. We can use these to compare data an test to see F's equalto, less than or greater than. Tythis InaNew File: a=6 b=? print(Ly a= 6) print@2, a = 7) print(3, a = 6 and b = 7) print(4, a == 7 and b = 7) print(S, not a= 7 ond b == 7) print(6, a= 7 or b = 7) print(7, a= 7 or b = 6) rint(B, not (a == 7 and b == 6)) print(9, not a == 7 ond b == 6) Execute the cade from Step9, andyoucan see a sees of True or Fase statements, depending on the resut ofthe two defining values: 6 and 7. I's an extension oF what youve looked at and an important part of programming. Bea ew bampubtiatinscom =D Getting Started Python) Using Comments Wier cece cere iceuk | Pere eae ier setae eae cecmmmeest la nated line by line but over time, it can become difficult to read. #COMMENTS! Programmers use a method of keeping their code readable by commenting on certain sections. Ifa variable is used, the programmer comments on what i's supposed to do, For example. It's just good practise. Stantby creating a newinstance ofthe DLE Editor fesave the code andevecte lt Youcan see tha the Sue (File > New File) and create a simple variable and EE ‘output in the IDLE Shell is still the same as before, print command spite the exta tinesbeing added. Simply put, the hash symbol (#) jaa >> Brine crane + Beant (rome * age) typetrror: Can't convert “int object to ste implicitly SBE rine characters Sse" + rtr(age) 2." years ola." Seb iayara Sescende fron Vakinge eS tars old ola.2) These of Typecastingsakoimportant when uae) dealing with Floating point arithmetic; remember: numbers tht have adcmal pint inher For eampe, enter shirt=19.99 ‘Now enter typaCShiint) and youl se that Python has allocated the number asa float’, because the value contains a decimal pint. Soe Specantre) Another example of ypeCasting when you Suary _ask For input from the user, such as @ name, for vamp ener ‘oge= input C*How old ore you?) ‘Alldta stored from the Input commandisstored as 2 string variable. oe age roa Cn When combining integers and lots Python Suit usually converts the integer to a float, but should the reverse ever be apps worth emebering that Python does return the eactvale, When conve'ting 2 Roattoan integer, ythan il ays rund down tothe nearest integer, Caled ncatng nour cate tendo 1.99 becomes 19, iin 348 ee. Ok ae, TTY ype create” or “case” for nae infomation. =D Getting Started Python) User Input Ween aera nC naeiecuscd eT MMU eT cdetereseM NMC a Cee en ren an cade USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding. For example, @ game may _ask for a character's name, whereas a database can ask for personal details. iis notaleady, open the Python 310 Sel Now that we have the use’ name stored Sue and start a New File in the Editor. Let’s begin with EE ina couple of variables we can call them up Something really simple, enter: whenever we want: printc*Hetto”) printC*Welcone”, firstname, surnane, “. T hope: firstnane=inputC'What is your first mane? *) ‘you're well today.”) print¢*Thanks.") Surnate=inputC*And what is your surmane? *) Sreawercate tease acasoustessiro ETERS fun hecoce ndyoucnseasig ss the Siare doubt suspected, in the IDLE Shell the program will Suz ull stop after the surname follows a blank space. skforyorFist name storing earth varabefisiname,falloned Tosiminate that we cnades plu sign stead of the comme by your surname; also stored in its own variable (surname). in the code: printC*Melcone”, firstrane, surnames. T hope you're well today”) BED 2 sess vine C User Input. Gal SIE tthe input command, For example, you can ask the usertheirname, andhave the input inthe line below: print(*Hello. Whats your nane?”) rramesinput©) Lserinput py -shome/pi/Documents/Python Code/u fie Est Famat fin pions windows Help Printhelle, what's your na hanes input) ? You dar'talways have te include quoted text within what youve createdhere is acondtion, which we SHEE will cover soon. In short, we're using the input from theuser and measuring tag a condition So, the ser enters David astheiename, the guard wil alo them to pass ntinered Ee, they enters name other than Davi, the guard calenges themtoatiahe “The code Fam the previous stp soften regarded SMePe ‘as being alittle neater than having a lengthy {amount of text inthe Input command, butts nat arule that’s imstone so doas you kein these stuation. Expanding onthe cote, yt printC*Holt! Who goes there?") rane=input) 1+ 5 fart tt rp oat ust as you learned previous, ary input froma setae cmamene ons “TypeCat inorder totum t into something eee. This ceates some Interesting addtions to the input command. For example: # Code’ to calculate rate and distance printC"Input @ rate ond a distance”) rate = floatCinput("Rate: ")) W's agoodstartto atext adventure game, perhaps? Sup Now you can expand onit and use the raw input from the user to Flesh out the game a lle: if namess"David": print "welcome, good sir. You may pass.”) else: printC*I know you not. Prepare for battle!") FRPITD 1 firaisethe rateand distance code, we can ade distance = floatCinput¢*Distance: *)) print(*Time:”, (distance / rate)) Saye and execute the code and enter some numbers. Using the Floatfingut element, weve told Python that anything enteredisa Floating point umber rather than a string, =D Getting Started Python) Creating Functions eee arm inaneeieisets Functions. You've already used a few functions, such as the print command but Python enables you to define your own functions. FUNKY FUNCTIONS ‘A function is a command that you enter into Python to do something. It's litle piece of self-contained code that takes data, ‘works on it and then returns the result, tes no js data that afunction work on. They an Sue do all manner of useful things in Python, such as sore data, change ems rom one format to another and check the length or typeof items. Basically, function isashort wor that's Faliowed by brackets. For example, tng), Ust) or type. B ‘You can pas variables trough functionsin much EE ‘the same manner. Let's assume you want the number ofletters ina person's sumame, you could we the Fotwing Code fenterthe text editor forthe example nane=input (Enter your sunane: count=LenCnane) print C*Your sunane has", count, “letters in it." ress and save the code to execate 3 ‘function takes data, usual variable, works on guar! itdepending on what the function is programmed todo and returns the end vale. The data being worked on goes inside the brackets 50 you wanted to knowhow many letters sxe nthe word artdestabishmentaranis then you entr: Ten¢Yantidtsestablishmentartantsn®) av the number 22 would return, SS Set er ra ein BET) 22 tse vine Python has es of Functions ul into a too Suz ‘many to get into in the limited space available here. However to view thet of bitin ution sabe to Paxton 3 raga to waridocs phanorg/3braryuncionhn. These are the predefined Functions, but since users have created many ‘more, they ee nat the only anes available. junction froma module enter the name of ie followed by fulstop, then the name addtional functions canbe added to Python Tous BULGED tscouch modules ychon hes avast range o Buse ‘modules available that can cover numerous programming duties. ofthe function. For instance using the Math module, since youve They add functions and canbe imported as and when required. For just importedit into Python, you can utilise te square root function ‘example, to use advanced Mathematies Funetions enter Toda0, enter: ‘import: math mmath.sartC16) Once entered, youhave rmadule functions. You cansee that the code is presented as module Function(éat) FORGING FUNCTIONS ‘There are many different Functions you can import created by other Python programmers and you will undoubtedly come Pee sete ee ea eee ens ee eee ete) Pret oO) Press FS to save and run the srit, You can see Hello in the Shel eee eee ence STEP 2 pean pte rey es paar, ne eect ei te ee ert ree ee eee ett print CHeT1on nana) Villill FrettoCbavico [eer adda.) This willow acces Perec if =D Getting Started Python) Conditions and Loops reste tence eau cn eo mR Teun Cenc te Case ena TC Ree cata hectic tee oer cre TRUE CONDITIONS Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking if something is TRUE, then doing something else if itis. Lets createanew Python program that wilask Nowyou can useanif statement to check ifthe ‘afourletter word ornot.Startwith File> New File,andbeginwith _frendly conformation it applies tothe rule the input variable word=inputC*Please enter four-letter word: *) wordsinput(“Please enter @ four-letter word: “) __word_Length-Lencword) if word_length == 4: print (word, “is a four-letter word. Well done.”) “The double equal sig something ese. means check ifsomething sequal to Now we an create anew vibe then use helen Te colon atthe end of tele Pthon thai guar! Function and pass the word variable through it to. Suz ‘statement is true do everything after the colon get the total numberof letters the user has just entered that's indented, Next, move the cursor backto the beginning oF wordwinputC“Please enter a four-letter word: “) tre Foto vword_length=lenCword) wordwinput(“Please enter a four-letter word: “) ‘nord_lengthsLen(word) Af word_length = 4: print (word, “is a four-letter word. Welt done”) else: print (word, “is not a four-letter word.") BED 2 sss vine Press Sand svete code to execute it Enter Now expandthe code onc SEP a foursetter word in the Shell to begin with, you SHEDS Eventu mh it could become quite complex. We've ‘ould have the returned message that's the wordis four lee or threedetter words Now press FS again and rerun the program but this time enter a Meee eee ee eal ee beeen hk tore, WOFd=iMPuEC*PLEase enter alfour=Letten words") Sri Geta a 0 Ure eter word Ty gn") | print (word, “is not a four-letter word.”) LOOPS eee ge er na ee ee Cee SMe mee ate se ton cay Cnet De ee eae) STEP.3) kc ate Doge “Uncory print nord) ‘STEP 2 uae weve TT peste) prea a and checks the statement stilt merits Z ie eee ten tener eram So Cone Senter eye eee ey oes 1 partisnt needed here because the range Function r first and last numbers used. Getting Started with Python Python Modules We've mentioned modules previously, (the Math module) but as modules are such a err cusame ea aia eum ete tle eT eC aad them. In this instance we're using the Windows version of Python 3. MASTERING MODULES Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are countless modules available and as we've seen, you can even make your own. though goo, the bul uncon within Pho Theres isnt recognised pip install pygane example on non platforms s the Pygame module, which contains clckthe result then click Run as Administrator. Linux and Mac users ‘mary functions to help create games. Ty-import pygame. can se the Sudo command, with sudo pip install package Clase the command prompt or Teminalané Sia relaunch the IDLE Shell, When you now enter: ‘import pyoaHe the mocks wil be moored int the code ‘tout any probes. You'l find that most code downloaded oF copied Fem the inert wl contain mode maistieam of nie, hese ae usualy he source of ers execton de to Uhembeing sig. [Braet C Python Modules Gal FAIR tiple modules can be imported within your code. To extend our example, use ‘import random import math for I in ranges): ‘printrandom.randint(ay print (nath:pi) Boa ee 25) ‘The modules contain the extra code needed to achieve a certain result within your own code, as ‘we've previously experimented with, For example: ‘import random Brings inthe code from the Random Number Generator module, ‘You can then use tis module to create something tke: for i in range(10): pprint(random.randint(1, 25)) Bom Ee The results astring of random numbers followed by the value of Pas pulled from the Math ‘module using the priat{math function. You can aso pullin certain functions From a module by using the from and impart commands, suchas: from random import randint for i in ranges): printCrandint(l, 25)) Bam rae This ode when sadn erected il platen Sup random numbers from 1 to 25. Youcan play around witha code ta dply more ors and oma geno ler ‘ange. Fr eamole ‘moore rendon for i in rongeC2s): ‘PrintCrandom.randint2, 100)) Trish crate ore steaminesaproachto GA Programming, You can also use Import module*, wich limport eve ing deed win the named modal However is often regarded as waste of resources but it works ronetheles. Finally, modules canbe imported as alases: ‘import nath’asim printcm.pid OF course, adding comments helps to tell others what's going on [a aaa cares ss =D Getting Started Python) Python Errors eee orn erent cm ers Python declares it’s not able to continue due to something being missed out, wrong or ee ene eC cai iae earn cachet ee caic DEBUGGING Errors in code are called bugs and are perfectly normal. They can often be easily rectified witha little patience. The important thing is to keep looking, experimenting and testing, Eventually your code will be bug Free. Codeisrtaefuidasthewriten word,no matter i Thankful Python elu when comes to Sues how goad the programming language is. Python is. EE displaying errar messages. When you receive an certainly easier than mostlanguages bt even tis prone tosome error ined text from the IDLE Shel til define the error itself “annoying bugs. The most common are typos by the user and whilst along with the ine number where the erorhas occurred, Whist in easytofindin simple dozertine code, maginehaving todebug _the IDLE Edltor this is alittle daunting for lots of code; text editors rmult-thousand tne code. help by including tne numbering The most common of erosisthe typo as weve Syntaxerorsare probably the second most Siare mentioned. The typos are often at the command Suz ‘common errors you'll come across as @ programmer, lev metiping te prin commandfor example. However they aso Evenifthe splin correc, che atl emmand te rong ‘occur when you have numerous variables, all of which have lengthy In Python 3 ths often occurs when Python 2 syntaxes are applied names. The best advice sto simply gothrough the cade and check The most annoying ofthese isthe pine function in Python 3 We use your spelling print words") whereas Python? uses print “words” "oe 8 Otin m ie at oh eg Be Yr se rae or “ee fr train es tres age onan fr ice tortie. BOM's Mandal seis olan 19 ( Python Errors Gal Pesky braces are alo ansancen programming Sia5 errors, especially when you have something like: printcbatanced_checkCinout@)) Remember tat for every there must be an equal numberof inert ot An excelent wayto check your code step bytep SHEE isto use Python Tutor's Visualise web page, Found at wrnpythonetorcomsuatizenemismode=ect. Simpy pasteyour code ito the editor and click the Visalie Erection buttonto rn the codeine ine, Te helprto dear bugs and any misunderstanding. ‘There are thousands of online Python resources, code snippets and lengthy discussions across Forums cenhow best to achieve something, Whist 99 per cent ofits goad code, doit always be lured into copying and pasting randam cade Into your ector. More often than not, won't work andthe worst pats that you haven't learnt anything Baa Indes re a nasty pat of Python programming Sup that a lot of beginners fall foul of. Recall the IF loop fram the Condor and oops section, where he lon means everyting indented allowing the statement tobe excited 8 longas true? Missing he indent orhaving too mucha iden, willomeback with ane positrons Purely out of interes, the word debugging in computing terms comes From Admiral Grace Hopper, wha back nthe 40 was working on a monolithic Harvard Markl lectromechanical computer. According to legend Hopper Found a moth tuck n a relay, thus stopping the system from working. Removal ofthe moth was hence called debugging =D Getting Started with Python ») Combining What You Know So Far eee eat iueeee une cena ten ieee we've looked at so far, and apply it to writing a piece of code. This code can then be used Eee ON aes lcd cd toe ee PLAYING WITH PI For this example we're going to create a program that wl calculate the value of ito set number of decimal places as described by the User it combines much of what we've leant, and altle more. Sacbyconraeionadcesnasnenriein TAMIR Te pevinsten deste nists re oe the Editor. First we need to get hold of an equation Sia up the algorithm and creates the string that will thatcanaccurately calcite without renderngthe computer's eventual dipay the valu ofP scoring the Chucowsky (CPU useless For several minutes. The recommended calculation _ brothers algorithm, You have no doubt already surmise thatt Used in such crcumstancesisthe Chudnovsky Algorithm, you. ‘would be handy to actually output the value of Pito the screen To ‘an find more information about tat en.wikipedia orahwiky/ rectify that you can add CChucnovsky_algothm, | Print Ceatect)), ‘You cn utilise the Chudnovsiy Algorithm to create Ne ee ee ee cco ERIE) You cn save and execute te code as point Begin by importing some important modules and Functions within Se eee ance nga ‘ecimal places: 3.141592653589734207668453591. Whilst pretty ee Impressive on its vn, you want some user interaction, to ask the from decimal import Decimal, getcontext Useras to how many places P should be calculated. ‘import math fesensenceeeaeseeeeeaeeaenenceaenees sesensenneeeee This usesthe decimal and getcontext funcionsfromthe Decimal RNB You can insert aninput line before the Picaluation ‘madule, both oF which deal with large decimal place numbers and Def command itneeds to be an integer, asit will naturally the Math module. otherwise default toastring, We can call it numberofdigits and use . the getcontext function FED Nov-youcaninsertthePicalculation algorithm Aber oFdigits"=TInECinput “please ententhe patt ofthe code. Tis is aversion ofthe huber of decimal place to calculate Pi to: “)) Chudnovsky Algorithm: getcontext©.prec = nunberofdigits ef cale(n): ‘t= Decinalco) pi = Decinal(o) den = Decimal (0) k=0 for k in range(n): + = (ecimal(-1)**410*(nath. Factorial (Decimal (6)*1))*(13591409 +545140134°K) ‘deno = math. factorial (3*k)*(aath. Factorial(k)**Decinal(3))*(640320°*(3%)) pi += Decimal t)/Decinal(aeno) pi = pi * Decinal(iz)/Decinal(6403z0"*Decimal(1.5)) Prone pi = I/pi return str(pi) BD 20 tse vine You can execute the code now and asks the user Sieh ‘how many decimal places they want to calculate Pi to, ovtputing the resutin the DLE Shel Try th 1000 paces but dot go too high or ese your computer wil be locked upin calculating Fi Partof programming sbeho Ts Sue able to modify code, making itmore presentable. Let's include an element that times how long it takes our computer to calculate the Pi decimal places and present the information ina diferent colour For this, crop into the commandline and import the Colorama module (RP users already have it installed) pip! install colorana Tofinish our code, we needte intaise the Sue Colorama module and start the time Function at the polnt where the calculation starts, and when it finishes, The end results coloured ink displaying how tong the process took (nthe inal or commandline} From decimal. import Decimal, getcontext ‘import math import time import colorana fron colorana inport Fore colorana.init© runberofdigits = intCinputC“please enter the nunber Of decimal places to calculate Pi to: “)) getcontext©.prec ~ nunberofdigits start_tine = tine.timeQ GeF catecn)! © Oar © Combining What You Know So Far "Now we need to impart the Colorama module (which wil outpuc text in efferent colours) along which dictates the foreground, nk, colour) and the Time module to stata virtual stopwatch to see how long take: import time import colorana from colorana import Fore = Decimat¢a) pi = Decinal(@) deno = Decimal (0) k=0 for k in range(n): £ = (ecinal(-1)**k)*(nath. Factorial Decimal (6)*k))*(135914094545140134"K) eno = math. factorial 3*)*(rath. Factorial (k)**Decimal(3))*(640320°"(3*K)) i += Decimal Ct)/Decimal Cdeno) pi = pi * Decimal (iz)/ Decimal 640320**Decimal(1.5)) pi = Vpi return str¢pi) printceatec1)) rintcFore.RED + “\nTine taken:”, tine.time() = start_time) Working with Data De ead Notes e or Chima c reese nee arc Rees coe ae cL) ee ee Rcd CMM ee a aC PE eee rT PCS BOs AES EL eae ee URL Sean) MEM uke cite iielt Pee chs coding skills to new levels and open De ee 66 List Ca Sec) R 4 7 8 80 Combining What You Knc Lists Lists are one of the most common types of data structures you will comes across in Python. A list is simply a collection of items, or data if you prefer, that can be accessed as a whole, or individually if wanted. WORKING WITH LISTS. Lists are extremely handy in Python. list can be strings, integers and also variables. You can even include Functions i ists, ‘and lists within lst. 5 Atstisa sequence of ata values ced ters You You canaso access oindxthelstitemin abst by ar create the name of your list followed by an equals ued using the minus sign before the item number [-1], sign, then square brackets and the tems separatedby commas; _orthe second to last item with f2] and so on Trying to reference an note that strings use quotes: item thatisnt inthe is, suchas [10] wll retun an error: numbers = [1, 4, 7, 21, 98, 156] runbers[=1] inythical_creatures ~ ["Unicorn”, “Balrog”, snythical_creatures[-4] “Varpire™, “Dragon”, “Minotaur”} SEE orcsoccrncircimsonctcas ERE hrgssntoto nace seyevonsevee Seceereteeererseceseruece, — EEED Sscectownttrsoans ore Geamuehilicnssyadtlocliyi tien winston Forexample: uberst139 numbers Will output the 4 and 7, being iter numbers 1and 2.Note thatthe ‘ocalluptheentie contents of the Uist. Feturned values dont include the second index postion as you rumbers(3] Tocallthe third from zero item inthe st 21 inthis case) ‘would numbers[:3]to retuin 4,7 and 21), BT) 2s sts sane You can update items within an existing list, remove items and evenjoinlststogether For example, to Join two tists you can use: everything = nunbers + mythicalcreatures ‘Then view the combined lst with everything You canview hatcanbe done wth sts by enering Sia Gir(list) into the Shell. The output is the available Functions, for example, insert and poo are used to add and remove items at certain postions. To inser the number 62 atitem index & numbers insert (4, 62) Toremoveit: runbers.popC4) PRP roms an be added toa ist by entering: runberssnunbers+[201] OcForstrings ythical_creatres-aythical_creaturest{"Grifffr"] (rby using the append function nythical creatures. append(“Nessie”) umber .append(278) Pe ae acer wont tiny ‘You alto use thet function to break string down uae) into its components. For example: Vistc“pavier) ‘xeaks the name David into toanew st ane=List(*David Hayward”) 14, 7,6. This can then be passed rane ege=[44] user = nane + age user Removal ofitems can be donein two ways. The First isbythe item number: ‘del nunbers(7] ‘Alternatively, by item name: mythical creatures. renoveC"Nessie”) Eee dt Based on that, you can create a program to store someone'sname and age as alist: rane=input(“What"s your name? “) UnaneslistCname) ‘age=intCinputC*How old are you: “)) Lage=Lage] user = Inane + lage “The combined name and age ist called user, which canbe called byentering ser int the Shell Experiment and see what you can do, ) Working with Data Tuples Tuples are very much identical to lists. However, where lists can be updated, deleted or changed in some way, a tuple remains a constant. This is called immutable and they're perfect For storing fixed data items. THE IMMUTABLE TUPLE Reasons For having tuples vary depending on what the program is intended to do. Normally, a tuple is reserved for something special but they're also used for example, in an adventure game, where non-playing character names are stored. 5 ‘tuple createdthe some woyasatst bt nth You can create groupedtuples int its tat conan ar instance you use curved brackets instead of square ue ‘multiple sets of data. For instance, here is a tuple brackets. For example: called NPC (Non-Flayable Characters) containing the character name months=C*Jonuary"ssFebruary”s"March"sisAprivey _ 2ndthelecombat rating for an adventure game "May", “June") NPC=EC*Conan”, 100), (*Belit”, 80), rnonths Valeria”, 957] ie Oh Bon HT SE occ winisinctesuranaronec tec RRP ‘arc noteyscnveacesctos EGD eccscmsmeces BEAD eee cee range,ie. indexed according ta their position NPC[O), You can also index the mmonths{0) indvial tuples within the NPC st: — Neca] (1 However, any attempt at deleting or adding tothe tupewillesult wil splay 100 in an erorin the Shell BE) 2 sess sine » From the norm. You would expect the 95 combatting ofthe ‘character Valeria to be NPC[a[5], but t's rot. ts actuals: nect2]t1) Its wath noting that when referencing mule Sia5 tuples within a list, the indexing is slightly different Now unpack the tuple into two corresponding variables: (rane, conbat_rating)=NPC ‘You can now check the values by entering name and combatting Bea wa 2 20 aa ‘which as you can imagine, getsalitle confusing when you've got 3 lotoFtuple data to deal with PRP This means of couse thatthe indexing Follows thus: Remember, swthlists, youcan also index tuples uae) using negative numbers which count backwards | from the endo the data lt. For our example, using the tuple wth multe data ems, you would erence the Valea characte wth Nect2]¢-0 ples though ube a Feature called unpacking, Sup where the data items stored within a tuple are signed valbes Frat ete the tuple with tote ome and ‘combat rating) ‘NPc=C*Conan”, 100) ‘You an use the maxand min Functions findthe Suit highest and lowest values of a tuple composed of numbers For example: runbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) “The numbers canbe integers and lost. To output the highest and lowes ue: primtCnaxCnunbers)) print CniinCnunbers)) ) Working with Data Dictionaries Lists are extremely useful but dictionaries in Python are by Far the more technical way of dealing with data items. They can be tricky to get to grips with at first but you'll soon PeeSCer acl Metra s DD KEY PAIRS ‘A dictionary is tke a lst but instead each data item comes asa pair, these are known as Key and Value. The Key part must be ‘unique and can either be a number or string whereas the Value can be any data tem you like. 5 Letssay you wanttoceateaphoneookin Python. ‘swith its and tuples, you can checte contents ar ‘You would create the dictionary name and enter ued of a dictionary by giving the dictionary a name: the dataincutybracets epmratngthe ley analy clon _phonebod nts example tii spate as ems youve Key:Value. For example: enteredin similar fashion toa lst, which youre no doubt familar swith by now, Phonebooke{“Enma”: 1234, “Daniel”: 3456, “Hannah”: 6789} SE orcwinvesiscnesoiso sg RBBB ‘ncbrre vnasccersy sau | ster 2 esaaaiee oeaeceeeseeigiema °° + cieteaeseaa tects resevenbstiseramensiicnanircke’ panenaeur torturer one Sigenracminescourseseetee, mmoknansie snavoies: phonebook “Hannah” Phonebook2={"“David"; “0987 654 321} BOM's Mandal seis olan 19 valueiters tke phonebook[*“David"] = “0987 654 321” phonebook ‘Adding toa dictionary seasy too. You can include ‘anew data item entry by adding the new key and Nest youneedto dfethe ser inputs nd SIEES variables: one For the person’s name, the other forthe phone number ets eep simp avid ngthy Python code) rramesinputC“Enter name runber=intCinput"Enter phone nunber: “)) ‘You canals remove ems fram a dcionay by SMePe issuing the del command followed by the item's key; the value will be removed as well, since both work as a pair of dataitems: ‘del. phonebook{“David"] fat ems Ho tis 38) phonebook[nane] = number Taking this te farthehow about cresting a Serv piece of code that will ask the user For the dictionary key and vale items? Greate anew Ecitor instance and start by coding ina new, bank dictionary phonebook={} Now hen ousave detects the code, Python Suerdo will ask for 2 name and a number, it will then insert those etter Into the phonebook dona, whihyou can est entering the hl phonebook pPhonebook[“David"] Ifthe number needs to contain spaces you need to makeit.astring, soremove the int part ofthe input ew bdmpubicatonscm Splitting and Joining Strings ene Ta uN scr Aiea aT Cog come across long sets of strings. A useful skill to learn in Python programming is being able to split those long strings For better readability. STRING THEORIES ‘You've already looked at some list functions, using .insert, remove, and pop but there are also Functions that can be applied tostrings. “The maintoolin the tring Function arsenals pled). Noe thatthe textsplit part asthe brackets, SUED vichicyovreaticrospitapatastingotéata, ada votes, then a space olowed by dosing quotes basedon the argument wthinthe brackets. Far example heresa__andbrackets. The spaceis the separator, inccating that each st string with three items, each separated by a space Item entry is separated by a space. Likewise, Sv (Comma Separated ‘Value content has comma, so you'd use ‘text="Daniel Hannah Emma” ‘text="January, February, March, April May, June” nonths=text. split," rnonths The oppose ofthe spl function & on, where swith the spt function the separator doesn’ SIE ‘you will have separate items in a string and can join SHEE have to be a space, it can also be a. comma, afull themalltogethertoformawordorista combination oFtems, stop, hyphen or whatever sou ike depending one program yoevatng, Fr lstance: Bi phobet=™.joinc“a","",%e", "6", "e")) cola”, ” joinccolours) tiphobet “This wil splay ‘abede' inthe Shell Nou ntierclrespyjontotheszpztedrane RRA) The'ssonerceing nconsyouzpp oa SMePe you made in Step 4, combining the letters again to uae) ‘string, such as capitalize and Ltitle. For example: Form the name ‘eitLe="conan the cimerian” rrame=”. joinname) title.capitalizeO rane title. titleQ ‘we've joined the string back together and retained thelist called name, passing Itthrough the join Function. BRP 2 c004 example of using the joinfunctionis when ERIIMIMM You can also use losic operators on strings, you have list of words you want to combine into with he‘ and ‘notin Functions. These enable sentence: youto checkf string contains or does not contain) a sequence Liste["Conan”, “raised”, “his”, “mighty”, “sword, °ftavaters “and”, “struck”, “the”, “denon”) message="Have a nice day” texte” “.joinClist) “nice” in message text "bad" not in message Note the space between the quotes before the join function (where “day” not in message there were no quotesin Step 6 join). “night” in message ED Working with Data Formatting Strings Rec eee iru eu stn unc eee Mr MMR cn on ee A nea Peta ruta cle keouate aur ces STRING FORMATTING ‘Since Python 3, string formatting has become a much neater process, using the format function combined with curly brackets. It's.a more logical and better Formed approach than previous versions. 5 The basi formatnginPthon toca each You canof couse ance integersinto the mi ar ‘variable into the string using the curly brackets: ued unber=10000 ane="Conan” print(“{} of {} was a skilled mercenary, printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a 1D" format name) mmerchant.”.format(nane, place, nunber)) ‘Remember to close the print Function with two sets ‘There are many different ways to apply string of brackets, as you've encased the variable in one, Formatting, some ae quite simple, as we've shown ‘andthe prin function in another. You can include multiple cases of _youhere;athers canbe significantly more complex. I all depends String Formatting in a single pit Function: ‘on what you want from your program. A qood place to reference Frequently regarding string formatting is the Python Docs webpage, Found at www. docs python.org/2.1/ibrary/string html. Here, you wl fied tons of help. rrame=""Conan” place="Cimeria” printC“{} hailed fron the North, in a cold land known as. {}”.formatCnane, place)) BEEZ) 2 sss sine Formatting Strings Gal Iereitycucactereealatshaihesung ETERS You ans pintouthe coment ausesinpt Sia5 Formatting function. You need to place an asterisk in Sia in the same fashion: frotoF thelist name rane=input("What"s your name? *) runberss1, 3, 45, 567546, 3425346345, print(*Hello {}.”.format (name) PrintCSome numbers: (2, (+, Oh, Oh, (". formatctnunbers)) \whineng ints te saneepestocalings RRR vou 2 oerdthsiolcate nolo da STEP 6 Ti using string formatting, You can index each item SUED nest ictter ina person's entered name: _2ccording tots position (from 0 to however many are present) ranesinput(“that’s your name? “) runbers=1, 4, 7, 9 printCHello {}.”.formatnane)) printCMore nunbers: {3}, {0}, {2}, Inane=Listname) {1}.". Format*nunbers)) print(The first letter of your nane is a {0}". format *1nane)) Be i Beg ge rasmoiocibyrunecyucanncton TRAE you cn socal gon sparo sande Suary and integers in a single list to be called in the Suerdo ‘them individually within the same print Function, Format function Looking back the code fom Step 7, you can alter it with: characterss[*Conan", “Gelit", “Valeria”, rrames=[“Conan”, “Belit”, “Valeria”) 19, 27, 20) ages=[25, 21, 22] print C*{0} is {3} years old, Whereas {1} is {4} years old.”. format(*characters)) Creating two ists. Now you can call each st, an individual tems: printC*{0[0]} ts {201} years old. Whereas {0011} is {1012} years old.”.fornat(nanes, ages)) E> Working with Data Date and Time PER Renee a eel a ec CRT eee eee aCe ism eet eee ee aCe Rte Mee nae Gaon la actu ce TIME LORDS ‘The Time module contains Functions that help you retrieve the current system time, read the date from strings, Format the time and date and much more. 5 Fist youneedtolmpotthe Te module. 'sone You canseethe sructre of how tines presented ar that's built-in to Python 3 so you shouldn't need to ued by entering: drop nto command prompt and pip install. Once R’Simported, —gewgtoea time) you can cal the current time and date with a simple command: a ‘he outputs dsplayed assuch: “time, struct-timeCtm ee yeor=2017, tmmon-9, tmnday=7, tmhour=9, “ ‘tmmina6, tm_sec=13, tmnday=3, tmyday=250, tm ‘isdst=9)'; obviously dependent on your current time es opposed tothetime this book was written rete hi catericeme eae Thee wenongsforirani ere Rocircmesice sassy EEE mssowycecenearect: Ten mcnoninbetoen detbine Teieadwaht ul itopoat sue gel eaeens eee ves time, strftimeC*KA”) ten tot (oor et we epson) 0:96 (0 Monday) 12026 cut dy) ETD 2 sees sane ‘This naturally means you can incorporate various Sia5 Functions into your own code, such 3s: time.strftimeC*¥a") ‘time.strftime(“B") time.strftimeC“%") ‘time.strftimeC4") time.strftimeC“M0s") ( (Date and Time Gal You sawatthe end ofthe previous section, inthe Sia code to calculate Pi to however many decimal places thesers wanted, youcan tine apart evetin Python. Take the code fom above and ater slighty by including start _timextime.time) ‘Then there's: endtimestime.tine()-stort_time ‘oprirayyarapiioconaPyneslagearepy ea = em 6 tam Be Ss td Not the ast bo ene wah Hand HRM, peng _you can see these are the hours and minutes and as. the lst entry indicates entering them as %HGM doesnt display the time carecly inthe Shell You can easy recy this with ‘time. steftine CHP) Theuanguiclonte oases Lsteaeceevepernranirin etait sccatege eg ries Fee epic This means you're going to be able to display either BALD tye csrenctime or the te when something cccurted, such asa user entering their name. Try this code in the Editor: import time rrame=input(“Enter Login name: “) printC*Melcone", nane, “\d") printC*User:”, nane, “Logged in at”, time. strFtimeM:2M")) ‘Trytoextenditfurthertoinclude day, manth,yearandso on, Theres alotthat can be done withthe tne Suerdo module; some of it is quite complex too, such 35, ) Working with Data Writing to Files The ability to read external files within Python is certainly handy but writing to a File is PCM MeCN testator Terie Pinaceae (erent a eens WRITE AND CLOSE ‘The write() Function is slightly more complex than read!). Along with the filename you must also include an access mode which determines whether the file in question isin read or write mode. ESTEE %2"tby opening ILE and enter the folowing: PRED However, the actual text leis stil blank ou can ee check by opening itup). This is because you've i vate the tine of textto the file objectbut nat committed itt the text txt, 7w") Fleitsel Part of che write Functionis that you need to commit the ‘Change the destination from /home/ai/Documentsto your own changes the ile; you can dothsby enterin: system. This code wil create atert fe called text.txt in write mode ‘sing the variable. If there's nile ofthat name in the location it vill create one. Fone aleady eis, it wil overwrite so be careful t.closeO) SEE crconwicwericntcsnrte we), SEP, iscoronsenetenennstoneser rahe cs ees ED ee ee een possiblities perhaps the creation oF your own logfile or eventhe beginning oF an adventure game. t.writeC*You avake ina small, square room. A. single table stands to one side, there is @ locked ‘door in front of you.") Note the 109. k's the number of characters youve entered. BT) 2 sets sine Toexpandthiscode you can reopenthefieusing SIE ‘a’, For access or append mode. This will add any text atthe end ofthe orga ine stead ot ping tefl andcreaing Snewone For exemple ‘teopenC/hone/pi/Documents/text.txt,"a") ‘tewnitece\n") t.writeC You stand ond survey your surroundings. (On top of the table is sone meat, ond a cup of water.\n") L (writing to Files [ You an pas variables to file that you've created in ython, Peshaps you want the value of Pi to be ‘written toa, You can cal Pi fromthe Math madule, create 8 new File and pass the output of Pint the new ile: ‘import math printC"Value of Pi is: “,rath.pid PrintC*\nliriting to a file now.) You can keep extending the tex tine by ie, ending SMePe ‘each with a new line (\n). When you're done, Finish the cade wth tore and open the fe inatextedtorto see the results ‘tunriteCThe door is mode oF solid oak with iron strips. It's bolted from the outside, locking you in. You are a prisoner!.\n") eetoseO, Nowlascrete avr caled land asin the pisath. pi ‘You also eed to create anew file in which to write Pt ‘t-open("*/home/pi/Documents/pi.txt”,"w") Remember to change you le location to your own particular system setup, There are various types of il accessto consider {sina the open( function. Each dependson how the files accessed and even the postion of the cursor. For example, r+opensafilein read and write and places the cursor at the tart ofthefle, Tofinish, you can use string formating to call the variable and write ito the ile, then commit the changes and close the file: t.writeC‘Value of Pi is: {}".formatCpi)) t.close() You can see fom the resuits that youre able to pass any variable toafie. E> Working with Data Exceptions Pe Ne aR eRe cet re aco! assume you ask a user to divide two numbers and they try to divide by zero. This will Ferree eee see EXCEPTIONAL OBJECTS Rather than stop the flow of your code, Python includes exception objects which handle unexpected errors in the code. You ‘can combat errors by creating conditions where exceptions may occur. p You can create an exception ero by sol og UP to divide a number by zero. This will report back with the Zer0DWsionror: isin by zero message, as seen inthe screenshot. The ZeroDivisionError part isthe exception lass, oF vlch there ae mary. BSED Mostexcentions are raised ‘automatically when Python ‘comes across something that's inherently wrong withthe code However, you an create your ‘own exceptions that are dascned to contain the potential error and Feactto it, 35 opposedto letting the coge fall. BEE) 22s tsres sine BSF) ocsccvctncivonsecuonoces erste eats raise Exception(*warp core breach”) SIR rae erro cozyn ncn Hecate aire Soa nant snout caethacnci tear bare Srcucntndnronns secssonte For example use the Givi by 2eo ero Youcan Sia5 create an exception where the code can handle the error without Python quiting due tothe problem: try: ‘asintCinputC“Enter the first nunber: bsintCinput(“Enter the second nunber: print(a/b) except ZeroDivisionError: printC“You have tried to divide by zero!" else: print(*You didn’t divide by zero. Well done!”) ‘You anus exceptions tohandte avait of useful SMePe tasks. Using an example from our previous tutorials, lets assume you want to open a file and wit tot: try: ‘txt = open("/hone/pi/Docunents/textfile.txt™, “r" txt.writeC*This is @ test. Normal service will shortly resune!”) except I0Error: print (*Error: unable to write the file. Check permissions”) else: print (“Content written to file successfully. Have a nice day.) ‘ext close) Natural youcan qui Fixe sue by charging Sia the “r” read only instance with a “w" For write, This, asi already inl create tne nde the conten hen Committe changes tothe fie, Te end esl wl repr a iferent sstof ercumstances inthis cate, asucestul execution ofthe code Ee You can also use analy: block, which works ina similar Fashion but you can'tuse else witht. To use cour example from Step 6: try: ‘ext try: ‘txt.writeCThis is @ test. Normal service will shortly resune!”) finally: print (“Content written to file successfully. Have a nice day.") ‘text .closeQ) except T0Error: print “Error: permissions”) ‘open*“/hone/pi/Docunents/textfile.txt", “r™) unable to write the file. Check Obviously this wont work du tothe Fie texfil tut being opened as read ony (the pat). Soin this case rather than Python tling you that you're doing something ‘wrong, youve created an exception using the IOErrr class informing the user thatthe permissions are incorrect. A before an erorwillaccur as youve used the "read-only permission. Ifyou change itto "Ww, then the code will execute without the error being displayed inthe IDLE Shell Needless to say, canbe a tricky getting the exception code right the fst tie. Practise though, and you will get the hang oft (exceptions GEE ) Working with Data Python Graphics Pose eer eee Cec rec will Sor cetera EL nes Peta TR one eee aoe LMR USI pete ceuit cen GOING GRAPHICAL ‘You can draw simple graphics, ines, squares and so on, or you can use one of the many Python modules availabe, to bring out some spectacular effects, preeereaenierner ere career ak RP ic crnnsecceso suns conve ca norenerensen mani nomics eke a ad ‘beyond; you can draw an arc by entering: turtle. circle(s®, 1180), where the size is 50, but youre telling Python to only draw Sparen Bee import turtle turtle.circle so) turtle. getscreen()._root..naintoop() ‘Asusval press 5 to save the code and execute It. Anew window wil row open up andthe Turtle’ will awa crcl, Lets beain by crawing a simple cir. Start a New Fil, then enter the Following code: BE) 2 sess sine ‘The last part ofthe circle code tells Python to keep the window where the crawingistaking ‘open, sa the user can lick to close it Now, lets Bee place to rem: make a square: ‘import turtle print ("Drawing @ square") for t in rangeC#): ‘turtle. forward(100) turtle. 1eFt(90) turtle.getscreen().—root .nainloop() ‘You canseethat we've inserted aloop to draw the sides of the square. You can adé anew tne tothe square co some colour add turtle.color¢“Red”) “Then you can even change the character to an actual turtle byentering turtle. shopeC“turtte”) ‘You can also use the command turtle. begin 110, and turtLe.end 110 to filinthe square with the chosen colours fed outline yellow filin this case. You can see that the Turtle module can draw out sere ‘some pr joad shapes and become a little ‘more complex as you begin to master the way it works. Enter this example: fron turtle import * color¢*red’, *yellon’) begin A10 hile True forward(200) ef eCA70) if absCpos()) < 1: break end #110) cone lesa diferent method, but very effective impating the Pygame module: FAP ow ets getthecodeby ‘import: pygare Pygare. init, ‘ng = pygane. image. lead(*RP% pra") white = (255, 255, 255) w= 900 h= 450 screen = pygone. display. setnode((n, h)) screen. ALCCwhite)) screen.f1CCuhite)) screen. blitCing,(0,0)) Pygone. display. flip) hile True for event in pygane.event.oet( ‘if event type = pygane.QUT pygane.quit© Inthe peviousstep you partes pyoame, tiated sue the pygame engine and asked it to import our saved RaspbertyPtgo image sovedasRPLpra Next you defined the Darkground colour othe vndow todsploy the mage and the window ease the actual inage mensions Fly youhavea loopte close the window iw = 900 lh = 450 screen = pygame.display.set_mode((m, h)) screen. fill((white)) screen. fill((white)) screen.blit(img, (0,0)) pygame. display. flip() Innile True: for event in pygame.event.get( af event. type == pygane. QUIT pygame.quit() Another way inch you can oly orp SUP ‘by using the Pygame module, There are numerous _ways in which pygame can help you output graphics to the screen but for now ts ino at displaying a predefined image Starthy pening a browser and ining an mage hen save tothe Folder wire you sve your Pthon ode ress FStosave and execute the code and your Suit image will be displayed in a new window. Have @ play around withthe colour, ces nd soon and take time to look Upthe many Functions within the Pygame module oo. se 5 Pi (_ Python Graphics [ ED Working wi Data) Combining What You Know So Far Based on what you've looked at over this section, let’s combine it all and come up with Petter arsenite yen itera aka Coa Pua Reheat ac tuck lta elles LOGGING IN For this example, let's ook to a piece of code that creates user logins and then allows them to log into the system and write the time they logged in at. You can even include an option to quit the program by pressing Begin by importing the Time mache, rating E ‘The loba status statement separates local BALD 3 cicicrarytohandle the useares and SUED ie rom one that canbe called throughout passwords and creating a variable to evaluate the current status of the cade, tis way youcan se the @=qué element without beng the program: changed inside the Function. We've aso referenced some newly pane Youraneestospetyou omioatintrte EEAAA ry ou ees cotusyteckttes tey SIE logins.txt file, since we're using a Raspberry Pi. SHEE hasn't been pressed to exit the program. We can do. Essential ths ads the username ndpasnordinpts fromthe thst userto the existing uses( dictionary, so the key and value structure remains: each user isthe key, the passwords the value while status 1 *a! status = displayMenu() Greatelogin = inputc-create » login name 1 erenatogn in uses PRPPIR row to create the oldser Function: i acl as =: SE LSET cee wire ef olduser: cance sett? ‘login = inputCEnter Login none: *) eR ee mee 2 passw = input(“Enter passnord: *) BESS) Teeesien cata # check if user exists and Login 2S me po mmatches password aa “if login in users ond users[login] == passw: glare sees print (*\nLogin successfuli\n") nade Ee i a Print C*User:", login, “accessed the system *, time.osctimeC)) os, else print C*\elser doesn" exist or wrong : — RaSCCIIN) PEPPPR 2vhovcha seemingly minor two tines, the white rs loopis what keeps the program runing. tthe end BE ere te a eee oe cof every function is checked against the urrent value of status. F that global value isnt ‘then the program continues. F's equal to then the program can qui. while status ! status = displayvlenu() tse ‘You can now create users, thenloginwith her oe: kee BME nes an passnords witnthelogistx fle bing crested to store te login data and succesful logins being timestamped. Now it's up to yout Further improve the code Perhaps you can impor the tof created users from aprevous session and playa graphic upon a sucessful ogi? Theres afar bichappering here. There ar loin Suey and passw variables, which are then matched to the users dcionay theres amatch, then you have asucesfullgin and the time and date ofthe login outputted. Fthey don't match, then you print an error and the process starts again, etisses pes “pega Index * & lee DaUSiare Modules DCE aus ru Pk ud hts. You can create your own Cent Ely Ee Cm Tas PM ne ete Te) EUS ees cn e . r Ea ur ces Reg CCE CEN ced . i] Seu cern Cle UU. U) eR ected - Pee Cea ee ee mes Caen eee Perea Tkinter Module core ees 106 Create Your Own Modules | coro See -2 oat 7 \~ = / , a » j Calendar Module WORKING WITH DATES ‘The Calendar module is built into Python 3. However, if for some reason it's not installed you can addi using pip install calendar as a Windows administrator, or sudo pip install calendar for Linux and macOS.. Launeh Python 3 and enter: import: calendar to Sues ‘all up the module and its inherent Functions. Once Ie'soaded into memory, start by entering ssep=calendar. TextCalendar(calendar .SUNDAY) sep.prmonth(2019, 9) le Est Sh abun Gyo sow He Pyalon 353 [sfett, op 3 218, =) andar (caandar SOY) ‘You can see thatthe days of September 2019 re SUP e Gisplayed in a wall calendar Fashion, Naturally you can change the 2019, 9 partof the secondtne to any year nd month you wan, abirtday For era (197, 6 The ist ine Configures TextCalendar to start ts weeks ona Sunday, yOu Can opt for Monday you prefer. Nery trem coy “There are numerous functions within the Calendar BAD yocietnscmaybeofiterestto you when foxming your own cade. For example, you can depay the number oF teapyears between two specc yeas: eapsecalendar. Leopdays(1900, 2019) printcleaps) The results 2, starting from 1904 onward, Bez import, calendar print(*>>>>>>>>>>Leap Year Calculator Using Modules OS Module INTO THE SYSTEM One of the primary Features of the OS module isthe ability to list, move, create, delete and otherwise interact with Files stored on the system, making it the perfect module for backup code. veuansntiheosabiewihcone sine EERE The vinow- cp watts Sie Functions to see how it interacts with the operating SIE current working directory of Python, as determined Sten envronnentthutrythonsrumingon ye sng ins bytesyseasyounghsuspec. the dapecwe fon corthe Raspberry try this: a6king Python to retrieve the Current Working Directory. Linux users wills something along the same lines as the Raspberry 35 wi import os lle ometing long theses the Rabe asl home=os.getend() printchone) interesting element tothe OS modul Trereunetreutrompininateveaserone ERRAPB yen SUED current user'shome folder onthe: system, aD ts ability to launch programs thet are insta Inour example that’s nome/ti;iewilbe different dependingon _inthe host system. Forinstance iFyou wanted to launch the the username you login as andthe operating system you use. Chromium browser from within a Python program you can use For example, Windows 10 will cutput: C:\Program Files (86) the command Python36-32 peta or browser=os. system("/usr/bin/chroniun-bronser”) OS Module BETES) he 055/stem0 functionis what allows interaction with external programs; you can even call up previous Python programs using this method, You wll obviously need to know the full path and program filename for itto work successfully, However, you can use the following import 0s ‘s.systenC‘start chrome “hetps://mw. youtube. con/ feed/music””) For step 'sexample we used Windows, show sere that the OS module works roughly the same across alipltfoms.inthat case, we apenes YouTube's muse feed page, 20 ile therefore possbe to open specc page: import 0s os. systen('chromium-browser “http:// bbanpubLications.com/”?) Note in the previous step’s example the use oF single and double-quotes. The single quotes encase the entire command and launching Chromium, whereas the double ‘quotes open the specified page. You can even use variables to call, multiple tabs inthe same browser: import os ‘o=C‘chromiun-browsen “http:// btnpubLications.con/”?) bb=C‘chromiun-bronser “http://m.google.co.uk”?) os. systen(a + b) The bly to manipulate directories or folders # Sie you prefer, is one of the OS module's best Features. For example, to create anew directory you can use: ‘import os os.mkdirC*NEW") This creates a new directory within the Current Working Directory, named according tothe objectin the mdi Function import: os os.renameC*NEW", “OLD") Toddlete them: import os os.rndir¢*OLD") You can also renarne any directories youve created byentering Another module that goes together with O5is shut Youcan use the Shuil module together with 05 and time to create atime stamped backup directory, and copy files into it: ‘import os, shutil, time root_src_dir = r?/hone/pi/Documents* root_dst_dir = ‘/hone/pi/backup/” + time.asctime() for sre-dir, dirs, files in os.walkCroot_sre_dir): dst_dir = srcdir.replace(root_src_dir, root_ dst_dir, 1D if not os.path.exists(dst_dir): os.makedirs(dst_dir) for file_ in files: srefile = os.path.Join(src_dir, file) dst ile = os.path.Join(dst_dir, file) Lf 0s.path.exists(ast_file): 0s.renoveCdst_fle) shutil.copy(sre.file, dst_dir) print(‘sssssssesBackup completecceececeee) <> Using Modules Using the Math Module E=MC ‘The Math module provides access toa plethora of mathematical Functions, From simply displaying the value of Pi, to helping yyou create complex 3D shapes. present, ou can import the module's function by simply entering {import math into the Shell or as part of your code in the Ector PER tre ath module ic builtin to Python 3:s0there's ome to PIP install it As with the ather madules ‘As yu wl a doubtbe aware by now ifyou know Size ‘the name of the individual Functions within the mmaduleyou can peccalyimportthem. For stance, the Floor and Cel tunctoneround down 2nd up a Fost from math import floor, ceil floor(1.2) # returns 1 ceil(.2) # returns 2 BPE D pocting the Math module wil ove you accessto the module's code. From there, you can call up any ofthe avalable Functions within Math by using math, followed by the name of the function in question For example, enter: math. sin(2) “This displays the sine of 2 The Math module can aio be renamed as you SHG import it, a5 with the other modules on offer within Paton. This often saves me, but dant forget to make comment toshow someone else loking at your code what youve done ‘import math as m nm.trunc(123.45) # Truncate renoves the fraction C Using the Math Module <> Although ts not common pacts itis possible to For further accuracy, when itcomesto numbesthe SEP import Functions From a module and rename them, Sie ‘exp and expmt functions can be used to compute Inths example, were mpating Fleer Fram Mathand renamingit_preese values: tof although where lengthy cade Sinus, hs process conic from math import exp, expnd can exp(1e-5) = 1 # value accurate to 11 places SS ‘equal to 2.71828 (where the circumference of a circle is divided by community ast takes up unnecessary resources andis't an efficent way of coding. However fit works for you then go ahead PED rt erestinaly, some Functions within the Math PIT the wealth of Mathematical functions avaiable ‘maduleare more accurate orto be more precise re through the Math module suas and covers designed to return a more accurate value, than others For example: everthing from factors to infiney, powers to trigonometry and angular conversion to constants Look up http://docs.python.org/3/ Urary/math html for ast of avaiable Math module Functions. will return the value of 0999999999, whereas: returns the value of 1.0. nnn CD <> Using Modules Random Module RANDOM NUMBERS, “There are numerous Functions within the Random module, which when applied can create some interesting and very useful Python programs. -ustas with other modules you need to import random before you can use any ofthe functions ‘we're going to look atin this tutorial, Let's begin by simply printing a Fandom number From to 5 import randort printCrandoaiint(@,5)) Inour example Sue the number four was returned However ent the pnt union few mere tines andi wl ply dierent integer vals from eset of numbers gen, zt ve. The overalefet though peeudo- fandom adequateforthe average programme to en ther eo For atigersef mabe lag ting os) point values, you can extend the range by using the ‘multilication sign import random printCrandoe.randem() *100) Will cisplaya floating point number between 0 and 100, tothe tune oF around fifteen decimal points FAIR However, the Random module icv used exclusively For numbers. Youcan useit to selectan entry froma Ist rom random, and thelist can contain anything ‘import random random.choice([*Conan”, “Valeria”, “Belit"]) This will dsplay one of the names of our adventurers at random, hich sa areat addition toa text adventure game. You can extend the prevous example somewhat by having random choice) select From alist of mixed ‘atiablesForinstance ‘mort random Ist=["David", 44, “BOM Publications”, 3245.23, “Pi”, True, 3.16, “Python”] ‘d=tandom. choi ceCist) print (rnd) Interestingly, you cen also use function within the SUED andor moduieto suf theitemsinthe i, hus advng alte more andoress into the equation randon. shuffeC1st) printcist) ‘This way you can keep shuffling the lst before displaying arandom item From it. sing shu you can rete an entirely andom st BED rvers For example, within s given ange import random Tste[CU] for I in rangec20)] rendon, shuffleCLst) printcist) ep shufing the lst and you cn haves diferent selection of ie from 01020 every bine ye od Dig ee Bre ‘You canals select random number froma ven BALD 2ncein steps using thestart stop sep oon inport_ random for + in range(i0): printCrandon.randrangeC®, 200, 7)) Results wilvary but you get the generalidea asto how t works. (Random Module <> Let's use an example piece of code which ipsa SUES virtual coin ten thousand times and counts how ‘many times iewilland on heads or tals output={‘*Heads":0, “Tails”:0} coinslistCoutput keys) for i in range(10000): ‘output[random.choiceCcoin)}+=1 printC'Heads:”, output[“Heads”]) print(Tails:”, output[*Tails"]) Here'san interesting pece of code. Using a text fle containing 466 thousand words, you can pluck user generated number of words fom the ile (text Mle found at: vewanithub,com/dwyVengish-words ‘import random print(s>>>s>s>>>Random Nord Finderccexexec<<") Print(*\nUsing a 466K English word text file I can ick any words at random.\n") nds-intCinputC*\nHion many words shall T choose? *)) inith_open(*/home/pi/Downloads/words.txt™, rt") asf: words = f.readlines©) words = [n.rstrip( for w in words] print ") for w in random.sampleCwords, wds): printGn) prints <> Using Modules Tkinter Module GETTING GUI “Tkinter is easy to use but there's lot more you can do with it. Let's stat by seeing how it works and getting some code into it. Before long you will discover just how powerful this module realy is. ‘Tkintoris usually built into Python 3. However, Fits available when youenter: import. tkinter, then youneedto pip install tkinter from the command promot, Wie can starto import modules ifferentl than before, to save on typing and by importing altheir contents: import tkinter as tk Fron tkinter import * The dea approach to ad mailoop into the Size code to control the Tkinter event loop, but we'll get tothat soon Youve ust created ner widget and there ace several mare we can ply aoundvth btneButton() ben.pack( btn["text”]="Hello everyone!” The ist tine Focuses onthe newly created window. Click back into the Shall and continue the other ines It’s not recornmended to import everything From 8 ‘madule using the asterisk butt wont da any harm normally. Lets begin by creating abasic GUI window, enter: windsTkKO ‘This creates smal, basic window. There's not much else todo at this poine but click the Xin the corner to cose the window. Bee FEAR You cen combine the above into a New Fle ‘import tkinter as tk from tkinter import * btneButtonc) btn.pack( btn[“text*]-"Hello everyonel* ‘Then add some button interactions: def click: print*You just clicked me!”) benl[comand”J=click Tkinter Module Saye and execute the code from Step Sanda ‘window appears with Hello everyone! inside. I'you dlckthe Hello everyane! button, the Shell will output the text"You just clicked me's simple but shows you what can be achieved vith a Few ines of code, You can asa depiay both textand maces wrthin sd a Tkinter window, However, only GIF, PGM or PPM formats aresuppotted. Sond an mage and convert before ing the cade, Here's an example using the BoM Publishing ogo fron tkinter import * root = TKO, logo = PhotolnageCfile="/hane/pi/Donnloads/B0M_ ogo.aif") wl = Label(root, root. titleC*B0M Publications”), ‘mage=1ogo).pack¢side="right") content = “""" From its hunble beginnings in 2004, tthe BOM brand quickly grew from a single publication produced by a tean of just two to one of the biggest anes in global. bookazine publishing, for two sinple reasons. Our passion and comitnent to deliver the very best product each ond every volune. While ‘the conpany has grown with a portfolio of over 250 publications delivered by our international. staff, ‘the foundation that it has been butlt upon rentains ‘the sane, which is why me believe BOM isn’t just ‘the frst ‘choice it’s the only choice for the smart w2 = LabelCroot,, justify-LEFT, ade = 10, ‘textecontent).pack(sides" Left") root maintocp( The previous code is quite weighty, mostly ue tothe content variable holding apart of 8DMis About page From the company website. You cn ‘buiously change the content, te roottitle and theimage to suit your needs, RAID vou con create radio buttons to. Try: From tkinter import * root = Tk, v= Intvarc) Lobel (root, root.titleC“Options”), text=”*"Choose @ preferred Language:”””, Gustify = LEFT, pad RadiobuttonCroot, ‘text="Python”, 20).pack() Radiobutton(root, text="Cr", pod = 20, voriable=v, value=2).packConchor=it) ‘maintoop© Yu canals create check boxes, with buttons and cutputto the Salt from tkinter import * root = Tk def var_statesC) printCWarrior: %d,\rMage: %d” % Cvart.get(, var2.getO)) LabetCroot, root.titleC*Adventure Gane”), text=">>>>>>>2>>¥oun adventure roleccceeccece"), gridcron0, stickyeN) vari = TntVarQ Checkbutton(root, text="Narrior”, varicble=vari). aridcronl, sticky-M) are. = IntVarO Checkoutton(root, text="Mage”, variablesvar2). grid(ron2, sticky ButtonCroot, text=’Quit’, comanderoot destroy). aridcrom3, ‘sticky=", pady=4) ButtonCroot, text=’Show’, conandevar_states). aridcrom3, ‘sticky=£, pady=4) ‘maintoop ‘The code From Step 9 introduced some new ‘geometry elements nto Tkinter. Note the and W arguments. These describe the locations ofthe ‘heck boxes and buttons (North, East, South and West) The row argument places them on separate rows, Have a play around and see what you get. <> Using Modules Pygame Module PYGAMING Pygame isn’t an inherent module to Python but those using the Raspberry Pi will already have it installed. Everyone else wil ‘need to use: pip install pygame from the command prompt. Nazcaly you need load un the Pygame modules usa ‘into memory before you're able to utilise them. ‘Once that’s done Pygame requies the user to inialise itpriorto| any ofthe Functions being use: import pygane pygane.initO BSTESED (ciscreste a simple game ready window, and ave itatitle ‘gamewindow=pygane. display.set.nodeC(800, 600)) pygone.display.set_coption(“Adventure Gane”) You can see that after the ist lines entered, you need to click back Into the IDLE Shellto continue entering cade aso, you can change the ttle ofthe window to anything you Uke Sadly you cant clse the newy create ygame Size window without closing the Python IDLE Shell, vic ery practical For thisreasa, you nee to werkin the tector New > Fl) andceatea Tue/Fase while oop import pygane Fram pygane, locals import * pygame.init() ‘gamewindow-pygane..di splay. set_node((800, 600)) Pygane.display.set_coption(*Adventure Gane”) runniing=True while running: for event in pygane.event.cetC: if event..type==QUIT: running-False pygane.quitQ (. Pygame Module <> ifthe Pygame window til wont UDG close don’t worry, it’s just crepancy between he ILE (which wnten ‘ith Tint!) and the Pygame module. you runyour code via the command lin, loses perfectly wll FIR Youre coing toshife the code around abit now, ‘mg=pygane. image. Load(/nome/pi/Downloads/ running the main Pygame code within awhileloop; spritel.png") itmakes neater and easier to Fellow, We've downloaded 3 graphic to use and we need to set some parameters for game ‘acuta: gamenindow.blitcing, (x,y) Ts =(80020,45) pygane. init) jeceoae0.8) ss garewrindon- ALY Cnn te) virile running: spriteCay) ‘ganenindowpyaane.display.set_node((600,600)) _PYGaNe. AsPlay.updateC) ygone. display. set_coption(“Adventure Gane”) for event in pygane.event.get(): black=C0,0,0) “f event. typennpygane. QUIT: writes(255,255,255) running-False PRMD e's vicky gothrough the code changes. We've downloaded image called spritet.png andallocatedit to the defined two colours, lack and white together variable img; and alsa defined a sprite function and the Bt function vith their respective RGB colour values. Next we've loaded the _wllallow us to eventually move the image Using Modules ) ) Now we can change the code around again, ths BALD eine containing armoveren: option within the vile loop, and adding the varables neededto move the sprite ‘around the screen: ‘import pygane from pygane. locals import * pygane. init running-True _ganewindon=pygane di splay .set_mode((800,600)) Pygane.display. set_coption(*Adventure Gane”) black=(0,0,0) white=(255, 255,255) ‘img-pygame. intage.1oad("/home/pi/Downloads/ spritel.png”) def spritetx,y): ‘ganewindon.blitCing, (x,y) x=(800°0.45) ‘y=C600*0.8) xchange=0 imgspeed=0 while running: for event in pygane.event.get(): ‘if event. typen=QUIT: runningeFalse ‘if event -type == pygame.KEYDOHN: ‘Af event. key==pygame.K LEFT: xchange=-5 elif event .key==pygame.K RIGHT: xchange-S ‘if event -type==pygame. KEYUP: ‘if event. key==pygane.K_LEFT or event key==pygame. K RIGHT: xchange=0 x += xchange ‘gamewindon fl UCwhitte) spritecx.y) ygane.display.updatec) pygae. quite) BRI ony the code down and using the left and right arrow keys onthe keyboard you can move your sprite across the bottom of the screen, Now, looks lke you have the makings oF a classic arcade 20 scroller inthe works 2 ot ta bn em mn {ee emt bie ten (. Pygame Module <> ‘You can now implement a few additions and utilise pygame. display. flipC) Sua! ‘some previous tutorial code, The new elements are clock. tick(60) the Subprocess module, of which ene funeinalows us layne 8 continue second Python cp fom witin another edwee going creates break NewFle called pygamebst — import pyomne inport tine import subprocess pygane. init screen = pygae display. set_node((800, 250)) Clock = pygane.tine.CLockQ) font = pygane. font.Font Using Modules Basic Animation LIGHTS, CAMERA, ACTION “The Tkinter module is an ideal starting point for Learning animation within Python. Naturaly, there are better custom modules ‘out there, but Tkinter does the ob well enough to get a grasp on what's needed, Let's make a bouncing bal animation Fist, we SAD i ced to create acania window) andthe ball toanimate fron tkinter import * import time gut = TKO gut .geonetry*800x600") gui.titleC*Pi Anination") Canvas = ConvosCaut, width=800,hetght=600,b-"white") canvas. pack bald = canvas. create_oval(S,5,60,60, fUl="red") gui -raintoop Saveand Run the code. Youle aban window save appear, with a red ball sitting in the upper left corer ofthe window. Whi tis great, snot very anmated Let'sadatheFllowing code o=s b=s for x in ronge(@,100): PIR Uce'ssce fwecananimatethe ballsothattbounces RIM now add che following: {around the window until you close the program, def maint): ygane.init© screen = pygane.display.set_mode((640,480)) ygane .display.set_caption(*Starfeld ‘canvas moveCbal 11, xa, ya) Simulation") pos=convas. coords (bai 11) Clock = pygame.time.ClockO) pas] BT sy Af pos[2] >-800 or pos[2] <0: while True: xa = -xa # Lock the Framerate at 50 FPS gui -update() ‘clock. tick(50) time. sLeepC.025) # Handle events * for event in pygane.event.get(): Remove the code you enteredin Step 2 and insert ‘Lf event. type == pygane.QUIT: BALE ce rom tep sn ts pace aga between the return ball = canvas. create. ovel(5,5,60,60, fills’ red”) ‘sereen:ft16C0;0:0)) and the gut .maiinloop() lines. Save the code and Runt as normal IFyou'we entered the code corectly, then you willse the red ball EST PS bounce of the edges ofthe window until you close the program, COARERET ARETE : . if ane main() Thebouncngarimaton ETT suey takes place within the Wate: True top. ist, we have the volves eimai, of xa and ny before the op, both oF and ESE ofl tpt 10 The posecanvas.coordsCbalL1) ine EXBEC'S“pypane tna: hock) takes the value ofthe bal lacaton inthe window. When itreaches the limits ofthe ssc starascrean) window, 800 oF 609, twill ake the values AA Trt amarate at 20 65 ‘negative; moving the ball around the screen. faetdchey - ° ‘Tor event in. pygase. event -get( ): Pyoame howeve a much better made t Feo a SIEPe ‘producing higher-end animations. Begin by creating = aNen Fle and etrng sees) ay ‘smarty moe aia Hil) From randon import randrange Franenenenearn aint MAXLSTARS = 250 STAR_SPEED = 2 : def, initstarsCscreen): EEEEDD ores oe cetaneenatne “°" Create the starfield “"" Sito simulated starfield code looks quite impressive. lobat stars Imagine tis as the beginning of some game code, or even the start stars = () toa presentation? Using a combination of Pygame and Tkinter, you for % in range(WAX_STARS): Python animations wll ook Fantastic, # A stor is represented as a List with this format: [X,Y] ‘star =" [randrange(0, screen.getwidthO - 1), andrange(®, screen.get_height@ = 13] ‘stars. oppend(star) ef nove_ond_dran_stars(screen): “"" Nove and dran the stars “*"" global stars for star in stars: ‘star[I] += STAR_SPEED if star[1] >= screen.get-height(: stor[i] = 0 star[0] = randrange(0,639) ! screen. set_at(star, (255,255,255)) <> Using Modules) Create Your Own Modules BUILDING MODULES Modules are Python files, containing code, that you save using a py extension. These are then imported into Python using the ‘now Familiar import command. Lev stare rating a sof ase Mathes Sue functions. Multiply a number by two, three and sare ara 2 number tan exponent (ewe). Create New File inthelOLE andenter def tinestwoO0: ‘return x * 2 def tinesthreeOo: return x * 3 def squares): return x * x def poner(x,y): ot sorter returcxssy pean ey "Now you're going to take the Function definitions ‘outof the program and into a separate Me Highlight the Function definitions and choose Edt > Cut, Choose Fle > New File and use Edt > Paste inthe new window. You now have ‘two separate files, ne with the Function definitions the ather with the function calls Lncethe above code, enter Functions to guar! call the code: print Ctimestwo(2)) print Ctimesthree(3)) Print CsquareC4)) print Cpower(S,3)) Save the program as basic math.py and executeit to getthe resis ects reenneetnn | we Hfyounow uy and execte re basic mathoy code Suz” again, the error ‘NameError: name ‘timestwo' is nat defined willbe displayed, The cue tothe code na longer faving access tothe uncton deintions. eturnto Suae the newly ceeatd window containing the function dfntion, and Clk Fle» Save A. Name this minimathpy ane sve in te same locaton asthe original basic math py program. Now dle the mnimathpy window tothebasc math py window teeopen. (Create Your Own Modules <> Baa code enter: From minimath import * “This willimport the Function definitions asa module, Press FSto save and execute the program to seein action, You can now we the code further tome the Sue Program alittle more advanced, utilising the newly created module tots Ful Include some user interaction, Start by reating a basic menu the user can choose From: print("Select operation. \n") printC"L.Times by tno") print(*2.Times by Three”) rint(3.Square") print("4.Poner of”) choice = input("\nénter choice (1/2/3/4 PEPER No we can add the user input to gee the number the code will work on: uml = intCinputC"\nénter number: “)) This willsavethe userentered number as the variable num choice = input(*\nenter choice (1/2/3/4): int = Snecinputcrvnenter rab Backto the basic math py window tthe top ofthe finaly, you cn now crest range of Fstterents BED 22 cetermine natto do with te numberand uve the newly crested inctondefntons: if choice == 11": printCtinestnoCnwnt)) elif chotce = "2: printCtinesthree(runl)) elif choice = 13°: print¢squaretrunt)) Lif choice = “4: runz = intCinput(“Enter second nunber: PrintCponer(numt, nur2)) else: rintC*Tnvalid input”) » Note thator the st avaale options, the Power Siero of choice, we've added a second variable, num2, "Wispasesa second number trough the Funiondeintion caled ower Save and evectethe program tose kinacon “ Coding with C++ eR uC eu) Pee a rs eet Front of you when you power up your computer, regardless of whether STEER Aur Cea o sis Prater c Ceee El Rte eet eae y world for you, in terms of desirable Penne ee eso) Cree ea es eer EU Mec language that's used to develop ST Cu ee Cd Ee ee ete ee engineering, banking, education, and Cie eee Beer er tcc equipment and software needed to get PP sea ae REPEC Eee ee Cn aa) cr rere toecn) to Set Up C+ in Linu Sree Why C++? eae enc mene Pa raniee a Cuetec keene en or ence ket original C language ands a general purpose object-oriented (OOP) environment. CEVERYTHING Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs, ‘device drivers and even entire operating systems. Dating backto 1979, the start ofthe golden era of home ‘camputing, C4, or rather C with Classes, was the brainchild of Danish computer scientist jare Stroustrup while working on his PhO thesis. Stroustrup’ plan wasto further the orginal language, ‘hich was widely used since the early seventies. C++ proved to be popular among the developers ofthe 80s, since twas a much easier environment togetto arips with ang ‘more importantly, was 99% compatible with the orginal C language. This meant that itcould be used beyond the mainstream Gsm aetna computing labs and by regular people who didn’thave accesso the mainffames and large computing datacentres. (C++ impact inthe digital word is immense, Many o the programs, applications, games and even operating systems are coded using C++. For example al of Adobe's major applications, suchas. Photoshop, InDesign and so on, ae developed in C+. You wil Find that the browser you sur the Internet with s written n C+, a5 ‘wells Windows 10, Microsoft Office and the backbone to Google's search engine, Apple's macOS is written largely in C++ (with some BG #include 2 | using namespace std; 2 void main() A |D{char ch; 5 || cout<<"snter a charater to check it is vowel or not"; 6 cin>>ch; 7 switch (ch) aio ( 9 case'a case'A' 10 cout< New > Empty ile, This creates anew, blank window for you to type, FEED nthe new window, enter the Following: #include Int rain { 7Avy first. C++ program Std::cout << “Hello World!\n": ¥ "Notice how CodeBlocks auto-insets the braces and speech quotes FRED tre program starts and another message appears informing you that Code:alecks is current not the default application For Ce fies. You have two options, to leave everything as its or allow CodeBlocks to associate allC++ ile types. Again, we would recommend you opt forthe lst choice, to associate CodesBlocks with every supported Fle ype ITD liccFle» Save as and save the code witha AppStore. nthe Search boxenter Xcode and then turns into ‘Install App. Enter your Apple ID press Return. There willbe mary suagestions filing the AppStore and Xcode begins to download and install. It may take some time ‘window but t'sthe Fst option, Xcode thet youneed toclickon, depending onthe speed of your internet connection, zeeze Take a moment to browse through the app's When the installation is complete, clickon the Open Information, including the compatibility to ensure button to launch Xcode. Click agree to the cence youhave the correct version of macOS, Xcode requires macoS, termsand enter your password to allow Xcode to make changes. 10.12. or laterto install and work tothe system. whenyou've done tat, Xcode bins to install additional components. sonal wun 19 \With everything now installed, including the the version number along with three choices and any recent projects that you've worked an; although for afresh install ths shows blank. a Welcome to Xcade =. Start by clicking on Create New Xcode Project; this ‘opens a template window From which to choose the platform you're developing code For. Click the macOS tab, then the Commang Line Tool option and finally, Next to continue PSTTSEDD ili the various fields but ensure thatthe Language option atthe bottom is set to C+, Simply choose from the dropdown lt. When you've filled in the Feds, ‘and made sure that Cvs i the chosen language, cick onthe Next button to continue ‘The next step asks where to create a it Repository for all your Future code. Choose alocation on your "Mac, ora network location, and cick the Create button, When you've done all that, you can start to code The left-hand pane etal the Fes usedin the C++ program you're cocing.Clckon the rmaincpp file inthe list You cansee tat Xcode as automaticaly Sie completed a basic Hello World program for you. “he diferences here are that theint rain Function now contains tute uncon andthe uti shh ferent. Th sat, cade ising he content that's valle to your Mac \henyouant to unthe code, clon Prodi > SuzEH0 Run. You may be asked to enable Developer Mode onthe Mic thisis to athorae Xcode to petformfuncons without teading our peso every ssn. when te program exes, the output deplayed atthe bottom ote Xcoce window (How to Set Up C++ on a Mac em” BED \g with C++) How to Set Up C++ in Linux Peer eri enn components preinstalled, such as a compiler. The text editors are also excellent for entering code into, including colour coding, There's also tons of extra software available to help you out. LINUX++ We're going tobe using afresh installation o Linux Min for this particular ttoral. There's a coding on Linux section later in the book ‘The first step with ensuring Linuxis ready for your EEp ‘Amazingly, that’ it Everything is allready For you LD or ccsciscnecktnesytemandsotware re — Maal 2 sar coding, eres how to get your fs. crs upto date. pena Terminoland enter sudo apt-get: Update! program upand runing in Linux Mintthe main texters ed 8 sudo apt-get upgrade Press etum and enteryour {anbe launched by clicking on the Menu and ping Hed nto the pessvort. These commends updetes the entesjtem and ary Searchbar lek on te Tet Estrbutonin the ighshand pane to installed sofware open Xed File Edit View Search Terminal Help PEPER ost Linux distros come preinstaled with al the ERFAM in xed, or anyother text editor you may be usin, necessary components to start coding in Cet tenter the lines of code that make up your C++ Hello However is always worth checking tosee if everything is present, Weld program. To remind you, its Sostilluitin the Terminal, enter: sudo apt=get install build-essential. and press Return, fyouhavethe right components, nothing installed butiFyou're mssingsome then int ain) they reinstalled bythe command. 7 - eestor mae /ANy first C++ program oe std::cout << “Hello World!\n"; #include Ran eet ERS aortas EEE) cores anutseris- vane 19 BRTTSED Wren youve entered your code, click le > Save As and choose afolder where you want to save your program. Name the fleas helloworld pp, or ary other name just as long asithas.cpp as the extension lick Save to continue ERTL 1: ist thing you can see is that xec has automatically recognised this as aC Fle since the Fle extension is now set to.cpp. The colour coding is present inthe code and if you open up the fle manager you canals see thatthe Fle'siconhas C++ stamped on it. BETISERD With your code now saved, drop into the Terminal again. You need to navigate tothe location of the Cr Fle youve just saved. Our example isin the Documents Folder, so we can naigate toi by entering: ed Documents. Remember, the Linux Terminals case senstve, so any capitals must be entered correctly. (How to Set Up C++ in Linux BPI before you canexecute the C++ fle youneed to compile. In Linux i's common to use g++, an open source C++ compiler and as youre naw inthe same folder a5 the Cé+file goto the Terminal enter: ge+ helLoworld.cpp and ress return, davideomi Fle e6 View Search Terminal Help re FIR there wil bea briet pause as the code is complied by r+ and providing there ae no mistakes or erorsin the code you ae retuinedtto the command promt. The compiling oF the code has created a new fle. you enter Us into the Tesminal you can see that alongside your C++ files a.out . davide Fle Edt View Search Terminal Help ree att SCT} fou PERITD the south isthe compied C++ code. Torunthe code enter: «/a.out and pres Return. The words Hello World? appears cn the screen. However, aout very friendly. Toname it something else post-compiling, you can recomeale with 94+ heLloworld.cpp 0 helLoworld. Ths creates an output Fle called hellowodld which can be run with: ZheLLowor ld, File Edit View Search Terminal Help Other C++ IDEs to Install IF you want to try a different approach to working with your C++ code, then there are plenty of options available to you. Windows is the most prolific platform for C++ IDEs but there are plenty for Mac and Linux users too. DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or all oF them Ifyou lke, but Find the one that ‘works best For you. RTD cicesemccyenaycs comatose saseeowoen sucess ED insane: tea ee, Taschnaedaecemadiamiernacayts tach forentseenerworsinareclsnet “download the latest version. you're stuck clckthe Need Help ink download and instal at www.codelite.org/ For more information. Tree ner ewener ED Me ourrorermnesndo crsiaconetst REAR even sorsarrocesnetscrs Ts Gear and intuitive IDE that supports testing, debugging | GENES isanother excellent IDE that’s packed with sedcadesnaje The Community Estonis fee unetesstne Fetes anda plesuretouse NetaeonIO= nse project based Froverson cents over, theCrmintyEdtonsavlale for templates or vs tt geyou the ity to Bld appcatons wth Windows ac Lnacand even the asphey PL Youn fide at hpanicand atc irate Pout mort wwwetbear of vv aacore conaonntoad Festurs/eppfndexhin. 120 BOM's Mandal seis olan 19 (. Other C++ IDEs to Install em” STETINIRSTITS Microsoft's visual studio sa PRR The Anjuta Devstudioisa LinuxonlyiDE that ‘mammoth C++ IDE that allows you Features some of the more advanced features you ta create applications for Windows, Andro, iOS and the web. The would normaly find in a paid software development studio, There's, Community versions fee to download andinstall butthe other Ul designer, source editor, app wizard, interactive debugger and versions allow a freetrial period, Goto wwwc.visualstudio.comy to muchmore. Go to wwwanjuta.oa/ for mare information ‘see whatt can do fr you. scosslatomocedegnest> FRRIURRSMTSD thsexete salou cepa rez wea create C++ applications For desktop and CielNenisvetel? towrite C++ code for desktop and mobile erwiconments. comes with acode ector and integrated web applications acrosal the major platforms, There's an advanced tools fo testing and debugging, as well as deploying to you chosen tes ely, inzegrated debugger and a configurable workbench to Platform. Rs not free butthere's atrial period on offer before help you create your code. I's avalable for Windows, Mac and Linux Feajuring purchasing: www.qtio/at-featurestibraries-apistools- and sree to download and use: www.monodevelop.com/. andide/. i | ie FEPPIIR sicisned ev crs, espe ts clout, Utinaors a css plaforn Cos Dethatbeastsa ‘Son oler De thts or Widows yes on. ‘apd development of ode rough thesia ond Vweyr ay ters pasts dean toe andwncoerpbeahed | apresie we of ro, Forte nove sa ess nIDe bt behind woyereodngand comping hough hee'snetbeen much, Romp na beauty ht would nk developers tees go Vocatngfocsonetine itscerany one tocar Fyou ware webby Fda moet wawaltimatepperarngex.emt SSreting diferent wbloodshednet/evepp ent | ; art — —— — =e Within this section, you can begin to Porcine cceerer Ru en Cee ts Court cea To Nee aD ee Ea) CoRR Ete d regu aud Berke tens Pema ue Tua) Nene ene ec Ukt esd Cee aE ee ccm CD Es iota) Ee eet em Tas Re MC eesc A Na Tre Me CE oes ) C++ Fundamentals) 124 Your First C++ Program We're going to be working exclusively in Windows with Code: rer onm ised cel NANT into a larger coding world. HELLO, WORLD! econ I gieseet cease ariiesue ey Its traditional in programming forthe First code to be entered to output the words ‘Hello, Worl to the screen. Interestingly, this dates back to 1968 using a language called BCPL. codein thisbook Begin by launching Code:Blocks. When open, click con Fle New> Empty Fle or press CilsShift+N on the keyboard ‘As mentioned, we'e using Windows 10 andthe Now you can seeablank screen with the tab Bee labelled “Untitled, and the number one inthe top left of the main Code:Blocks window. Begin by clicking inthe main ‘window, so the cursor isnext tothe number one, and entering include latest version of Code:Blocks forthe rest ofthe C++ PED 2% che moment t doesnt look like much, and itmakes even les sense, but well get to that in due course Now dick on File» Save Fle As, Create o Find 2 suitable location on your hard tve and inthe Fle Name box, call ithelloworld.epp. Clckthe Save as type box and select C/C++ ies. Clckthe Save Butta, PETE You ce7see that Code:Blockshas now changed the colour coding, recognising thatthe fle isnow (C++ cade, This means that code can be auto-alacted from the CCodesalocks repository Delete the finlude lin and reenterit You cansee the auto-elect boxes appearing. Z (Your First C++ Program ci BRTEEM 2urcsclection of commandsis extremelyhandy and BRNMIMBM ote again the colour coding change. Press Return at ‘cuts out potential mistyping Press Returnto get to the end ofthe previous step'stne, andthen enter: Std cout << “Hello, world!\n"; line 3, then enter int naino Notethere’s no space between the brackets FPR cnn restlne blowin min. enter acu bracket: PRIMM ust as bere, CodeBlocks autocompletesthe code you're entering, neucng pacing aosing 4 ‘speech mark as soon as you enter the First. Don’t forget the ‘Ths canbe done by pressing Shftandthekeytotherightof onan semicolon athe endo! then: hs one ofthe mos important English Uk keyboard layout tlementsto Cr+ program and welltel you wtyinthe next senpeneeeees sedion or now; ove the cursor down tothe dosing cur bracket eainwidiaisia. nfo and ress Retin [[eee[saJo> so 0mm [ee ieeiagieia ee BETTER otice thet CodeBlocks has automatically created BMI That's allyou need todo forthe moment. it may a corresponding closing curly bracket a couple of ‘ot look teribly amazing but C++is best absorbed lines below, inking the pais wellasasightindent. hiss dueto in small chunks. Dont execute the code atthe mament 2s you need, the structure of Css andie where the meat of the cade sentered, to look at how a Cs+ programs structured fst; then you an build Now enter: and run the code. For now, click on Save, the single floppy disc icon, My fest C+ program ) C++ Fundamentals) Structure of a eee felis ero aera rec aie mance as small as a semicolon, and your entire program will Fail to be compiled and executed. Many a professional programmer has fallen foul of sloppy structure. #INCLUDE LLeatning the basics of programming, you begin to understand the structure of a program. The commands may be different From one language to the next, but you will start to see how the code works ory #INCLUDE *heloworld.epp x The stcture oF9crs progam isgute ree Every Cr code Bevin wthadrective Since the drecive nstustte Repocessrtoindudes Secon ofthe standard Co Cove Foreronple nce ostream indus the iotreamheoderte support include C++ wasiovented by Danish student Bjame Stroustrup in 1979, a5 apart of his Ph. thes. Inially C++ as called C with lasses, which added Featurestothe already popular Cprosramminglanguace, ‘while makingit amore aonene Userfriendyensionment input/output operations. ‘rough anew sructure Bjarne Stroustrup, inventor INT MAIN() Starthere | *helloworld.cpp >< inemainginaesthe Eee declaration of a Function, which 2 a isa group of cde statements 2 under the name mai all 3 | int mini) Get cade begins atthe main a Function ceoorless oF where Jj wtualyieswitin the code 5 i a . BRACES The open brace (cry brackets) something that you may nothave come across befor, especialy ifyoute used to Python. The ‘open brace indicates te beginning ofthe ‘main Function and contains all the code that belongs to that Function, sonal wun 19 include int main() oo eene COMMENTS Lines that begin witha double lash are comments, This means they ‘wont be executed in the code and are ignored bythe comple. Comments are designed to help you, or anather programmer looking at your code, explain what's going on. There are two types ‘oF comment: /* covers muitiple ine comments, fa sngle tne. Lines that begin with adouble lash are comments. Thi means they won't be executed in the code and ‘are ignored bythe compiler. Comments are designed tahelp you, or another programmer ooking at your code, explain what's going on, There are two types of comment: /* covers multiple tine comments, // Singleline I. STD ‘while std stands For something qute different, in C++ itrmeans ‘Standard. ts part ofthe Standard Namespace in C+, which covers ‘anumber of afferent statements and commands. You can leave the stdz part out ofthe code butit must be declared atthe start with: Using namespace std; not both. For example: ES Inths example we're using cout whichis apartof the Standard Namespace, ence why its there, asyoute asking C++to ust from that particuiar namespace, Cout means Character OUTput, which splays, or print, something to the screen. Fwe leave std out we have to declare it atthe stat ofthe code, as mentioned previous Finclude ‘using namespace std; Ant main () Ee cout, ¢ Structure of a C++ Program ci The two chevrons used here are insertion operators This means that whatever follows the chevronsis to be inserted into the stdscout statement. In this case theyre the words ‘Hello, world, “ich are to be displayed onthe screen when you compile and execute the code, OUTPUTS Leading on, the “Hello, worl” part is what we want toappear en the screen when the cade executed. You can enter whatever you lke, a long asi’ inside the quotation marks. The brackets aren needed but some comple insist on them. The \n pat indicates 2 rewrline isto be inserted. My first C++ program cout << "Hello, world!\n" ;AND} Finally you can see that ines within a Furetion code block (except comments) end with a semicolon. This marks the end ofthe statement and ll statements in C++ must have one atthe end or the compiler Failsto build the code, The very last ine has the cesing brace to indicate the end of the main Function. Vincluae lasing namespace st: ant main() cout << Mente, world!\a"7 nnn ) C++ Fundamentals.) 128 Compile and Execute ire minicom eer enka structure of one. Let's actually get things moving and compile and execute, or run if you prefer, the program and see howit looks. GREETINGS FROM C++ Compiling and executing C++ code From Code:Blocks is extraordinarily easy; just a matter of clicking an icon and seeing the result. Here's how i's done, BETTER) Oven CodeBlocks ifyou havent already, and PEPIED Scart by clicking onthe Build icon the yellow cog. loadup the previously saved Hella Word code you Atthispoint, your code has now been run through created. Ensure that there are no sible errors, such as missing _ the CodeBlocks compiler and checked For any errors. Youcansee semicolons at the end of the std:cout ine. the resuits of the Bulle by looking to the bottom window pane. Any messages regarding the qualty ofthe code are displayed here. Buidlog | F Build messages x |) CppCheck/Ve in "no project" (compiler: unknown) === 5), 0 warning(s) (0 minute(s), 0 second(s)) cic++ BRTESEDD | youscode's looking similar to the one in our BRPIID Nove cickon the Runicon, the green play button. screerahat, then look to the ment bar along the top ‘command tne box appears on your screen cof the screen, Under the Fortran entryin the topmost menu you can dsplaing the words Hello, word, Followed by the time ies taken see a group of icons:a yellow cog, green pay button and acog/play to execute the code, and asking you press key to continue. Well button together. These are Build, Run, Bud and Run Functions. dane, youjust compiled and executed your First C4» program. yject Build Debug Fortran wiSmith Tools Took+ Plug teealQaiorseon P| scl el | Qa © bi L finclude int main() Ac ( Compile and Execute QPS Pressngany key nthe commandline boxcloses Create deliberate erorinthe Sua retuming you to Code::Blocks. Let's alter the code Sue semicolon from the cout line, so it reads: ihtly, Under the include in, enter: cout << “Hello, world!\n" Starthere X| *helloworld.cpp x using namespace std; Then delete the st: part ofthe Cout ine; tke so: cout << “Hello, norld\n"; 2 using namespace std; a 4 _ int main() T ficinie corer sot 3 eo enone p ie tet miso 7 1) cont << "e110, worta!\n" : at 5 7 1] cout se suerte, wound ar 8 3 10 Inorderto apply the new changes tothe code, ou Now ich Bud and Runicon againto apo ted crap, bull and un toni. This ne changesto the cage. Thine Code-lecsrefses however, youcan spl cickthe Bule/Ranicon, the contined”toexecite the cde, due tothe eroryou putin. nthe Log pane at yelow cog andareen ply bton the bottom ofthe seen you are normed ofthe ero nth et Expected before token in cating the missing semicolon BETTER staswementionedinthe previous pages, you BRIMBINM replace the semicolon and under the coutine don't need to ave std:cout If you already declare enter a newline to your code: sing namespace ste a the beginning of the code. We could have easly icked the Buin ian to begin with buti’s wath going through the available options You can aso see that by building and The \nsimply adds anew line under the last ine of outputted text. running the le has been saved. ‘Bull and Run the code, to display your handiwork, cout << “And greetings from C++!\n"; ) C++ Fundamentals.) Using Comments Coen Cee ue emer n rg combine to make a game, application or even an entire operating system, in actual Fact Oe Naeem estan cece THE IMPORTANCE OF COMMENTING Comments inside code re basically human readable descriptions that detail what the code is doing at that particular point. They don sound especially important but code without commentsis one oF the mary frustrating areas of programming, regardless of whether youre aprofessional or just stating aut In short, all code should be commentedtin such a manner as to effectively describe the purpose of line, section, or individual elements. You should getinto the habit of commenting as muchas possible, by imagining that someone who daesnit know arything| about programming can pick up your cade and understand what its {going todo simply by reading your comments Ina professional envranment, comments are vital ta the success ofthe code and ultimately, the company. an organisation, many programmers workin teams alongside engineers, other developers, hardware analysts and so on. IFyou're apart ofthe team that’s ‘writing @ bespoke piece of software forthe company then your comments help save alot of time should something go wrong, and another team member has to pick up and follow the trailto pinpoint the sue. Place yourse'n the shoes oF someone whose jb itis tofind ot ‘what's wrong with a program. The program has in excess of 00,000, lines of code, spread across several ifferent madules. You can soon appreciate the reed foralitle help fom the original programmers nthe form oF good comment. The best comments ae always concise and link the code logically, detailing what happens when the program hits this ine or section YYoudor’tneedto comment on every line. Something along the lines of ifxe-0 doesnt requiceyouto comment that ifx equals zero then «do something that's goingto be obvious tothe reader. However, Fx equalling zeros something that drastically changes the program for the user such as, they've run outoflves, then it certainly needsto| ‘commented on. Evenif the code is your own, you should rite comments asf you were goingto publi share it with others. This way you can return| tothat code and always understand whatt was you did or where it was you went wrong or what worked bilan ‘Comments ae gaod practise and once you understand howto adda comment where needed, you soon dota if it’s second nature C++ COMMENTS ‘Commenting in C++ involves brief examples but this is how they work. ESTTE DD Usioa the Helo world code as an example. you can easly comment on different sections ofthe code Using the double Forward slash Uy fest C+ progean cout << “Hello, world!\n": Finclade ‘using namespace stds tne main a cece sitters Pe (Using Comments ci 19a double Forward slash /, ora Forward slash and an asterisk, '/*. You've already seen some Be careful when commenting, especialy with block comment.’ ery easy to forget to add the dosing asterisk and forward slash and thus negate any code that fallsnside the comment block However, you can also add comments tothe end of aline of code, to describe na better way what's going on: cout << “Hello, world!\n"; //This Line outputs the words ‘Hello, world!”. The \n denotes @ new Line. Note, you don't have to puta semicolon at the end oF a comment. Tiss because I's tnein te code that's ignored bythe comple. PEPE You can comment outseverallines by using the Forward slash and asterisk 7/7 This comment. can cover several Lines without the need to add more slashes */ _Justrememberto finish the black comment withthe oppaste ‘asterisk and Forward slash. a BRTEED Ob vousyyityou try and buld and execute the code itertors out, complaining of amissing curly bracket to finish off the black of code. IF you've made the error afew times, then itcan be time consuming to go back and recy. Thankfully the colour coding n CodeBlocks helps identity ‘comments from code, If you're using black comments, it's good practise InC¥+ to addan asterikto each new line ofthe comment block. This alo helps you to remember ta close the comment biock of before continuing with the code: 7 This coment can 7 cover several lines * without the need to add more slashes */ ) C++ Fundamentals Variables Variables differ slightly when using C++ as opposed to Python. In Python, you can simply state that ‘a! equals 10 and a variable is assigned. However, in C++ a variable has to be declared with its type before it can be used. THE DECLARATION OF VARIABLES You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can declare, Here's how It works, (Open up new, blank C+ file and enter the usual You can build and run the code bukit won't do ED oennsces Bee ‘much, other than store the values 1Oand 5 to the ae integers and b. To output the contents ofthe variables, add using nanespace std; cout << a; cout <= "\n?s int main a rE : uit << bs ‘ing nenopece a The cout <<" part as aetar 3 simply placesa new ine between the outbutof I‘ toands. we sme masa () ee BETTER Seertsimpleby eating twovariables, and, with BRIMPBB naturally you can declare a new variable, call it fone having a value of 10 and the other 5. You result and output some simple arithmetic: use the datatype into declare these variables. within the curly ‘ brackets, enter: ima result = a +b; into; cout << result; — ut ats — fren cere Insert the above into the code as per the screenshot bes; BPTI You canassigna value ca variable as soon asyou declare it. The code youve typed in could ook like this, nstecs int @ = 10; int b= 55 int result = a +b; cout << results ED SS crncionteesseine neem int © C10); int 8; hen, fram the C++ 2011 standard, using curly brackets: int result foxb}s FED vou can create alot les, which ae variables that are declared outside ary function and usedin any Function within the entice code, What youve used sofa are local bles used inside the Function For example include using namespace std; int StartLives = 3; int main © t stortLives = StortLives = 1; cout << Start ives; Variables Qos he variable States, able, In game, for ample, FED the previous se whichis global player’ ives 0 up or down depending on how wel or how bad theyre doing, When the player restarts the game, the StartLives return tits default tate: 3, Here we've asigned 3 ives, then subtracted 1 leaving 2 ives lef, BID the modern c++ compilerisFarmore intelligent than most programmers give credit. while there are numerous datatypes you cand you can fi auto Feat efor vari #include using namespace std; auto pi = 3.141593; int rain { double area, radius = 1.5; ‘area = pi * radius * radius; cout << area; FERED 4 coule of new elements here: Fst, auto won't work unless you goto Settings > Compiler and tick the box labeled "Have Ge Follow the C++11 SO Ce* Language Standard [std=c++1Y. Then, the new datatype, double, which le-prcision Floating poin value. Enable C=+11,then bile andrun the code. The result shouldbe 7.05858, ) C++ Fundamentals) Data Types Variables, as we've seen, store information that the programmer can then later call up, and manipulate if required. Variables are simply reserved memory locations that store RSet ees Ue ea Renae lected 134 THE VALUE OF DATA “There are many cfferent datatypes avalable forthe programme In Cre, suchas an integer, floating paint, Boolean, character and so on.’ widely ccepted that there are seven basic datatypes often called Primitive Builtin Types: however, you can create your own datatypes should the need evr arise within your code “The seven basie datatypes are: aade Se?) Gens Coa Double Floating Point Ce iii No Value “These basictypes can also be extended using the Following modifiers: Long, Short Signed and Unsigned Basically his means the modifiers can expand the minimum anc maximum range values for each data type. For example, the nt dat type has a default value range of 2147483648 to 2147483647, fair value, you would agree, Now ifyou were to use one ofthe modifiers, the range alters 020 4294967295 2147483648 102147403647 32768 to 32767 £065,535, Signed Shor. nt =-32768 to 32767 147493647 to 2147483647 147483647 to 2147483647 204290967295 Naturally you can get away with using the basic type without the ‘modifier, as there's plenty of range provided wit each data type. However, is considered good C++ programming practise to use the modifiers when possible. There ae issues when using the modifiers though, Double represents a doublefloating point value, which you can use For incredibly acurate numbers but those numbers are only accurate Upto the fifteenth decimal place. There's als the problem when using nanespace std; double PI = 3.141592653589793238463; int rain { cout << PIS y » 3 | double Pr 5 tnt maint) 6 7 cout << Bs * s 0 Build and run the code and as you can see the autputisonly 3.18158, representing cou’ limitations inthis example, You can alter the code including the aforementioned cout precision Function, fr greater accuracy. Take precision athe way upto 22 decimal places, with the Following code: include using nanespace std; double PI = 3.141592653589793238463; int rain { cout .precision(22); cout <« PI; ¥ Stathere | Oatatypescpp i finciads using namespace std; typedef int metres; Aint waing t metres distance; distance = 15; cout << “distance in metres is: << distance; This code w ‘Then in the main cade block, there's anew variable caled distance, vihich isan integer sa you're basically telling the compiler tha theres another name for int. We assigned the value 15 to distance and displayed the output: distance in metres is 15. Iemightsaunda litle confusing ta begin with but the more you use (C++ and create your own code the easier ie becomes, ) C++ Fundamentals) Strings SS Tee es) eed eWeek ce Une Le RAL ees eel DC Bole) a could have a universal greeting in your code ‘Welcome’ and assign that asa string to be called up wherever you like in the program. STRING THEORY ‘There are different ways in which you can create a string of characters, which historically are all carried over From the original Clanguage, and are still supported by C++. Tocreasngyousse ech factin Ooene ERTIES outs sndnnthe code and ween snes oe new C++ file and begin with the usual header: Sie ‘onthe screen. While this is perfectly Fine, it's natasing sing alas which defines cet that an be represented asa stream of characters and does need to be terminated tke an array. The code can therefore be represented as: #include using namespace std; a #include o using namespace std; ¥ int main © [Qajorson mgsprece, £ [reselisl 21S ¢ bo. ‘char greet] = “Welcome”; cout << greet << \n"; BRTESED 5 e0syt0 confuse string with an array. Here'san BRUNI in c++ there's als a string Function, which works in aay, which canbe terminated with all character: ‘much the same way. Using the greting code again, ‘include aenemn Using namespace. stds include using namespace std; Ant rain © 1 ‘int Lengths string greeti = “Hello”; string greet2 =“, world!"; string greet3 = greeti + greet2; length = greet3.sizeQ; cout << “The Length of the combined strings is: * << Length << “\n"s } Uso the avlable operations that ome wth the BRED oi incon oucon manus theconersofa string. For example, to remove characters rom sting you coud ue: #include using namespace std; int rain © { string strg “Here is a long sentence in @ string cout stra. cout: erase (10,5); << strg C++ Maths PO Puce eri eee tncaied built:n scope for some quite intense maths. C++ has alot to offer someone who CCN arene ue oie a een ede tae relatively simple. ny C++ =MC? ‘The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++ Math Library, you can also calculate square roots, powers trig and more. 14's mathematical operations follow the same patterns a those taught in school, in that muliliation and dision take precedence over addition and subtraction You can aler that though. For now, create anew file and enter #include include using namespace std; int wain © cacy ajar mara sr include include using namespace std; int wain © float nueber = 134; cout << “The square root of “ << number << is: “<< sqrt(number) << “\n?; Herewe rested anew float caled number and Siaru used the sqrtinumber) Function to display the squire oot 34, te vaio thesaiale, number auld andrun (C++ Maths of numbers an be done wi ED ecustna #include include using namespace std; int nain © float nunber = 12; cout << number <<“ to the poner of 2 is * << onCnunber, 2) << *\n" cout << number << “ to the poner of 3 is * << Poncrunber, 3) << “\n"; ‘cout << nunber << “ to the power of .08 is “ << ponCnunber, @.8) << “\n?; PID ese we created afloat called number withthe value oF 12, and the powivarable, power) is where the calculation happens. OF course you can ealulate powers and square roots without using variables. For example, pow (12,2) ‘outputs the same value a the Fist cut nen te code, FERETD he valuc of Pic also stored in the cmath header Library. tan be called up with the M PI Function. Enter cout << M_Pfinto the code and you get 3.14158; or you can se eto calculate: #include include using namespace std; int rain © { double area, radius = 1.5; orea = MPI * radius * radius; cout << area << "\n"; eal Output ie Bee Ee sae es Ran DER os input, then uses that input to produce See nae ee ae Pee oc eis Deere Die eens Se eee eC roe Semen ea ete) output are all covered in the following Perea an hai Rite eee grand Dee Csi Peete tee Te me aoe ) C++ Input/Output) User Interaction SS Cc eect ce a nN em DeSean tea mae Meee AA ERs RRL Re keoM Me Me MULE Re [kee TL HELLO, DAVE You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard Input stream, to prompt a user response, BEER thing that you want the user toinput into the ARES) The cn command works inthe opposite way From program needs t be stored somewhere inthe the cout command. Wth the First coutline you're system memory, soit canbe retrieved and used. Therefere, ary outputting "Whats your age’ to the screen asinicated with the input must Fist be declared as avarable,sot’sready tobe used by _chevrons. Cin uses opposite Facing chewrons indicating an input. The the user. Star by creating a blank C++ ile with headers. inputs putinto the integer age and called upin the second cout command. Buld and run the code Fineluae ‘using namespace sta ane main 0) a ESTEE RD | you're asking a question, you need to store the input asa string; to ask the user their name, you would use i ESTEE) The datatype ofthe variable must ao matchthe using manespace stds type of inputyou want From the user. For example, to.aska user their age, you would use an integer tke this: = — #include > names { cout << “\nHello, “ << nane <<“, I hope you're int age: ‘nell today?\n"; cout << “what is your age: “; + cin >> age; =< iam cout <<"\nYou re“ << age'

You might also like