0% found this document useful (0 votes)
529 views

Phython and C++ Learning

Object Oriented C++ Programming and Usage of Python Tutorial

Uploaded by

Kayal Vizhi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
529 views

Phython and C++ Learning

Object Oriented C++ Programming and Usage of Python Tutorial

Uploaded by

Kayal Vizhi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 164
Learn Coding “&Python Crystal clear guides to help you discover coding Discover more of our complete manuals on Readly today... The Complete Ubuntu Manual The Complete Photoshop lements Manual gs © TheComplete Ma Manual The Complete Manual a) \’s Definitive Guide Serie Learn Coding: &Python “Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is Fun to program.” — Linus Torvalds (developer of the Linux kernel) We live in a world full of code: the Internet, our cars, phones, kitchen appliances, TVs and more. Everywhere you go and nearly everything you willinteract with on a daily basis has some form of code behind it, driving it and helping us humans manage the countless connected devices that make up our digital lifestyle. Learning to code, therefore, offers us a chance to better understand how everything works and how it’s designed to work with us. Learn Coding: C++ & Python will help you build a solid Foundation on which to expand your knowledge of the digital world. Within these pages, you will discover how to start coding, what coding can do for you and how you can apply code to help you or just to entertain you. Learning code isn’t difficult, but it demands patience and imagination. So let’s begin your coding journey and see how far it will take you. Ellewinows [Eqeonrasiazons a Solace Learn Coding: C++ & Python 8 Why Python? 46 Lists 10 What can You Do with Python? 48 = Tuples 12 Getting to Know Python 50 Dictionaries 14 Equipment You Will Need 52 Splitting and Joining Strings 16 How to Set Up Python in Windows 54 Formatting Strings 18 How to setup Python in Linux and macOS- 56 Dateand Time 58 Opening Files 22 Starting Python for the First Time 64 ~~ Python Graphics 24 Your First Code 26 Saving and Executing Your Code 28 Executing Code From the Command Line 30 Numbers and Expressions Calendar Module 32__Using Comments 79 Using the Math Module 34 Working with Variables 72 OSModule 36 User input 74 Random Module 38 Creating Functions 76 Tkinter Module 40 Conditions and Loops 78 Pygame Module 42 Python Modules 82 Basic Animation 84 Create Your Qwn Modules eek iad 8B Why CH? 90 Equipment You will Need 92 Howto Set Up C++ in Windows 94 Howto Set Up C++ on a Mac 96 Howto Set Up C++ in Linux 98 Other C++ IDEs to Install 102 104 106 108 110 112 114 GoWStieena 120 122 124 126 Your First C++ Program Structure of a C++ Program Compile and Execute Using Comments Variables Data Types Strings C++ Maths User Interaction Character Literals Defining Constants File Input/Output While Loop For Loop Do... While Loop. IF Statement IF Else Statement 142 144 146 148 158 160 Master Python with the help of our Fantastic Code Portal, Featuring code for games, tools and more. Passing Variables to Python Retro Coding Text Animations Creating 2 Loading Screen Tracking the ISS with Python Using Text Files For Animation Common Coding Mistakes Python Beginner's Mistakes C++ Beginner's Mistakes Introductio to Python , Sl J when interviewed by David Letterman é + . “How did you know so much about computers?” q ee Af ” aa el Cel om oat -M alee a | = Admiral Grace Hopper (pioneer programmer) Introduction to Python Cl Why Python? For some years, Python has led the beginner's coding community, thanks to its ease-of-use interface, effective and streamlined code, and the Fact that with just a Few lines you can get some great results fast. Python is more than just another programming language, though. Its community is Full of like-minded coders, from all walks of life and levels of ability, who strive to create great code and drive the future of Python, and coding, to ever-greater things. In this section we look at what you can do with Python, what you will need to get started, and how you can get it on your computer. 8 why 10 What can You Do wit 12 Getting to Know Python 14 Equipment You Will Need 16 Howto Set Up Python in Win 18 How to setup Python in Linux and mact s ED) estrone Why Python? Seu icra ae cu eet SOA m ult ues Peer ee ee nate mse esa qe cutee cs EigoKel-cselarte cel mca Tale en olL Molen eA Romo y] Coleco ULe Rea RUAN Manolo Python out of all the rest? PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. ‘These pioneers of programming carved their way into a new Regardless of whether you use an Android device, iOS device, PC, Frontier, Forging small routines that enabled the letter’ to scroll Mac, Linux, Smart TY, games console, MP3 player, GPS device builtin across the screen. it may not sound terribly exciting toa generation toa car, set-top box ora thousand other connected and ‘smart’ Unat’s used to ultra high-definition graphics and open world, mult appliances, behind them alls programming. player online gaming, However, Forty something years ago It was blindingly brillant Allthose aforementioned digital devices need instructions to tell them what to do, and allow ther to be interacted with, These Naturally these bedroom coders helped form the foundations for instructions Form the programming core ofthe device and that core every plece of digital technology we use today.Somewent onto can be bulltusing a variety of programming languages. become chief developers for top software companies, whereas ‘others pushed the available hardware to ts limits and founded the The languages in use today differ depending on the situation, the billion pound gaming empire that continually amazes us platform, the device's use and how the device willinteract with its old drrayeerssonitdostroces0) itleurgor == 0) efreahoe cursor) cert schtahoatrncust) vold_aprovert: tatnrant 0 ( ‘Size size ~ Getsize fi 2-0: je < column. cetcoune(l: jer ie cy heater cooaeeacal AP CT gees Ssertgrid Um cotum.cescaun() 22) ~ 0) ator fc = slandtscoterbieabled, scolorpaper); Skat 1} Saitek « carcane()) ¢ PB saeco Gace Je ace Berea Rete oso Eieierse Gimeno Siracatece Betton Ssacat Bosca fe Suc tee f carwins (Geatone'se JE cans Gewrwie se Soepes Brtese [Errevesio rmsd Ssh Sreatoe 2 yt Bes BT) 20s cin cseseies-vuess ew verterid (5 <= column Gatcnunt l= 2 environment or users. Operating systems, such as Windows, macOS and such are usually a combination of C++, CH, assembly and some Foim of visuatbased language. Games generaly use C++ whilst web pages can use a plethora of available lanquages suchas HTML, Java, Python and soon, ‘More general-purpose programming is used to create programs, apps, software or whatever else you want to call them. They/re ‘widely used across all hardware platforms and suit vitually every conceivable application. Some operate faster than others and some’ are easier to learn and use than others. Python s one such general- purpose language, Python is what's know as High-Level Language, inthat it tals! to the hardware and operating system using variety of arrays, variables, objects, arithmetic, subroutines, loops and countless more interactions. Whilst its not as streamlined as a Low-Level Language, which can deal directly with memory addresses, cal, stacks and registers, its benefits that t's universally accessible and easy to lear. /FA Te: invoke. java, import java. lang.reflect ‘lass invoke { Dublie static void main( string (7 args ) try L Ble dee I ce ject rat = m.invokeC null, null 2; Systen.out print int *Tnvoked state method: ” + args(1) noe class: © + argstol "with no args\neesults: " + ret): catch ( Classnoctoundexception } { 77 class fornane() can't find the class Catch C siosuchethodexception e2°) { 72 that method doesn't exist Gaceh ¢ TegatAecesstxcention ¢3 ){ 77 pe dione have permission t0 invoke that } Catch ¢ mnvocationTargetexception e4 ) { 7 an exception ocurred wivie invoking that inechod a System.out.printin( Shothed threw an: " + ed. getTargetexception( *)°); Java's a powerful language that’s used in web pages, set-top boxes, ‘Twsand even cars. ( why Python? Cl Python was created over twenty sixyears ago and has evolved to become an ideal beginner's language for learning how to programa ‘computer, tts perfect for the hobbyist, enthusiast, student, teacher {and those who simply need t create their own unique interaction between either themselves or apiece of external harcivare and the: computer itself, Puthanis free to download, install and use ands availabe for Linux, ‘windows, macOS, MS-DOS, 05/2, BeOS, IBM i series machines, and ‘even RISC.O5. It hasbeen voted one of the top Five programing languagesin the wortd and is continually evolving ahead of the hardware and Internet development curve, Soto answer the question: why Python? Simply put, it's Free, easy to learn, exceptionally powerful, universally accepted, effective anda superb learning and educational tool. BASIC was once the starter language that early B-bit home computer users learned. ‘eps = enn san «tet 4) Python is a more modern take on BASIC, it's easy to learn and makes For an ideal beginner's programming language. nowkinotictocn Ci - ie mrt} What can 7 che with Python?" i} enya on Python is an open-source, object-oriented programming language that's simple to understand and write, yet also powerful and extremely malleable. It’s these characteristics that help make it such an important language to learn. Python's ability to create highly readable code, withinasmallset _You'llfind lots of exemples ofthis, where Python is acting behind Cpr ee ee eee ea ener el world, From being an idea first programmers’ choice through to, being able to create interactive stories and games; from scientific Pee eee ue he) applications, the only limit to Python isthe imagination of the 2 Peete its Fee eee a ee ce = Se ens eee eee era Certara et a Brunet eea nin eee ea oie’ Ee a ua RC eee rer eee ee need without having to crass multiple language barriers: Python (ieee ea te esa BIG DATA Coe ee ee eee nt eco eee ree ee eer eee patterns trends and interactions between humans, society and technology. OF course, ‘ot just limited to those areas, big data curently being used in a variety of industries, from social media to health and welfare, engineering to space exploration ea ee ee eau on Poe ered huge chunks ofthe avalable big data and extract specificinformation based on what. Rete tun eau ues ee eee renee ee eee er eres er eee i ea ees Se err es eee eee ary Deen eee een en eet ce RA ee ees ce ie eeu alee aes ceil tur ea aed eee CE the raw data, but Pythons present to help sit through the data so scientists can get to the Pens a tec ten Teor ree ee ee cn ead ete esa at ec ‘umbrella term used for any computing process wherein the Be irene ear De eee tn eet cst) and provides the overall A system with the ability to learn Peers! However, Alisn't simply the creation of autonomous robots Cone ee eee se ie Found in a variety of day-to-day computing applications where the ‘machine’, or more accurately the code, needs to learn fount ete us ey Cet ce Bee emcee eres er (ORCI ee see ec ‘on nstagram and then discovered that your searches within Seen Sones ier) ee an en ene ees neu eM err eee icy Ce ei oe ‘potify, for example, uses Python based code, Sees ee een ener sets listened to inthe past. I'sal eleverstufFand Sc ee oricusa teams otras ee \Web development has moved on considerably since the early days of HTML scriptingin a limited text editor The many Frameworks and web management services available now ‘means that building a page has become increasingly complex. With Python, the web developer has the ability to create 2 python windows Before you close jzard window, nk nexttothe the instal shield detailed Disable Path Length Limi, This wil allow Pythoy to bypass the Windows 260 character limitation, enabling you to execute Python pragrams stared in deep Folders arrangements Again, click Yes to authenticate the process; then you can Close the Installation window. © Disable path lena less Find the installed Python 2 toi 3.xvwithin the Start button Re added section. The Fis link, Python 2,7 (32-bi) wil lunch th comman rsion oF Pythan when clicked (more con that in amoment), To nthe IDLE, type IDLE into Windows start How to Set Up Python in Windows Cl Ea Clicking on the IDLE (Python 3.7 32-bit) link wl launch the Python Shell, where you can begin your Python programming journey. Don't worry iF your version is rewer aslong as it's Pythan 3.x cur code works inside your Python J interfas BED you now click on the Windows Start button aa and this time type: MD, youl be presented onnmand Prompt link. Cickit to ¢ environment, To enter Python with 2: python and press Ent nd tine ed nthe he command tine vers much the seme way as the Step 8;note the three left-facing arrows (>>>), While ine envirarmment, it's not too user-friendly, so leave ine For now. Enter: exi't() to leave and close the Command hon works in ellyouopenedin ‘sa perfectly fal Introduction to Python) How to setup Python in Linux and macOS PYTHON PENGUIN Linuxis such a versatile operating system that it's often difficult to nail down just one way of doing something. Different distributions go about installing software in different ways, so For this particular tutorial we will stick to Linux Mint. ESTISEDD First younced'to ascertain which version of Python EMMI) Once the usdate and upgrade completes, en currently installed in your Linuxsystem, To begin python. ==version again to see IF Python 3's with, repintoa Terminal session From your dstro's menu, or hiethe updated, oreven installed. As long as you have Python 3.x, youre CerleAlt+T keys running the most recent major version, the numbers after the 3. indicate patches plus further updates. Often they/re unnecessary, Aovidedavid ating ~ but they can contain vital new elements. Terminal Hep Next, enter: python ==versiom into the Terminal screen, You should have the output relating to version 2.x of Python in the dsplay, Most Linux distro come with both Python 2 and 3 by default, as there's plenty of code out there stil avaliable For Python 2. Now enter: python3. ==ver'sion. enviar ° wate FETED However, if youwant the latest, cutting edge version, youll need to build Python From source, Start by entering these commands into the Te oeccase sti pxehion 2 “ica, Sudo apt-get install build-essential checkinstell LEED ics minondxasinssled.tntectenn $400 obt=get install Ubreceline-gplva-dev DIRE slasunte * LibncurseswS-dev Tibssl-dev Libsqlite3-dev tk-dev ‘our tutorials will work. t's always worth checking to see ifthe distro es hasbeen undated with the atest versions, enter: sadovapt=get, VPgdber-dev Tibeb=dev 1ibbz2-de update && sudo apt=get upgrade to update the system. ‘avid ine - DMs Definitve Guide Seves-Voiume 35 How to setup Python in Linux and macos In the Terminal, go to the Downloads Folder byentering: ed) Downlloads/. Then unzio Fe contents of the downloaded Python source code with: tar =XVF Python-3.Y:Y.tar.xz (replace the Y's wth the version numbers you've downloaded}. Now enter the newly unzipped folder with: ed Python-3.Y.Y/, Ee Within the Python Folder, enter: configure sudo take altinstall This could take @ while, depending on the speed of your computer. Once Finished, enter: python3.7 ==ver'sion to check the latest installed version. You now have Python 2.7 installed, alongside older Python 3.xx and Python 2. Forthe GUIIDLE, you'll need to enter the Following ‘command into the Terminal sudo apt-get install idle3 The IDLE can then be started with the command: idie3. Note, that IDLEruns @ different version to the one you installed from source, oolong 373 e BESET ou'lalso need Pip (Pip installs Packages), which isa toolto help you install more modules and cetras, Enter sudo apt=get install. python3-pip ‘Once PiPis installed, check forthe latest update with: pip3 install --upgrade pip When complete, close the Terminal and Python 2c wil be avalable via the Programming section in your disto's menw, ‘veda wine roommladenyhen 72 THON ON | } Getting an installation of Python onto macOS can be done in much the same way as the Windows installation. Simply go to the Python webpage, hover your mouse pointer over the DDowmloads ink ancl select Mac OSX from the options, You wi then be guided to the Python releases for Mac versions, along E with the necessary installers for macOS 64-bit for 05 X 10.9 and later wmubcinosblsatonsscon Index Getting Started with Python “The purpose of software engineering is to control complexity, not to create it.” SUPA alae a Me co elena) ( Getting Started with Python Getting started with Python may seem a little daunting at first, but the language has been designed with simplicity in mind. Like most things, you need to start slow, learn how to get a result and howto get what you want from the code. In this section, we will cover the core concepts: saving and executing your cod variables, numbers and expressions, user input, conditions and loops. First Time ing You! Executing Code from the Comma Numbers and Express z= Getting Started with Python ) Starting Python For the First Time The Raspberry Pi offers one of the best all-round solutions on which to learn and code, in particular, Python. Raspbian, the Pi’s recommended OS, come pre-installed with the fEleoriete=le) Reem eee MR oe EU pe keele lien Cece s STARTING PYTHON We're not going to go into the details of getting the Raspberry Pi up and running, there's plenty of material already available fon that subject. However, once you're ready, Fire up your Pi and get ready For coding, ESTED With the Raspbien desktop loaded, click on the BSED forevemple, inthe shellenter: 242 Mew button Followed by Programming > Python After pressing Enter, the next ine displays the [3 (IDLE). This opens the Python 3 Shell, Windows and Mac userscan answer 4, Basically, Python has taken the ‘cade’ and produced the Find the Python 3 IDLE Shell from within the Windows Start button relevant output. via Finder. (Se git We) Bie rs wre BP FETTER The Shelliswhereyou can enter code andseethe — NEWB the Python shel acts very much ike acaleuletor, responses and output of code you've programmed since code is basically a series of mathematical into Python, Thisisakind of sanclox, whereyou'e able to try out interactions with the system. Integers, which are the infinite some simple code and processes. sequence of whole numbers can easily be added, subtracted, ‘multiplied and soon, ana ae ech stat aes Ma me rae DMs Definitve Guide Seves-Volume 35 ( Starting Python for the First Time Cl FST) hile that’s very interesting, t's not particularly BETES The Pithon IDLE isa configurable environment. F ‘excing Instead, try this you donttlike the way the colours are represented, " a then you can always change them via Options > Configure IDLE and FERIA clicking on the Highlighting tab, However, we con't recommend Just enter t into the IDLEas you've done inthe previous steps. that, as you won't be seeing the same as our screenshots. a | = BED This isa litic more ikeit since you've just produced EAN ust ike mos ‘your Fist bit of code, The Print commandis Fairly ‘operating system, there are numerous shortcut selF-explanatry, prints things Python 3 requires the brackets 2s Keysavalable, We dont have room fer tem al here but within the ‘well as quote marks in order to output content to the seen, inthis Options> Configure IDLE and under the Keystab, you can see ast case the Hello everyone! bit ofthe current bindings. >>> print(“Hello everyone!") Hello everyone! precoated >>| ——— BST You rmay have noticed the colour coding wi BSTSE ER The Pvthon IOLE sa power interface and one the Python IDLE. The colours represent diferent that’s actually been written in Python using one elements of Python cade. They are of the available GU! toolkits. IF you want to know the many ins and ck Data \ “Us ‘outs of the Shell, we recommend you take a few moments to view Black -Data and Variables Blue - User Functions psa adap a ycaarp ang Green=strings Dark Red—Comments paler saraaat Purple ~ Functions Light Red ~Error Messages i Orange ~ Commands Habe IDLE Colour Coding ee ees noms) Bick [ats vaister| 70.6 apes Porn | Forcier | ent) print Latte [Ener meseons | _syntaatesoe ZZ ) Getting Started with Python ) Your First Code Essentially, you've already written your First piece of code PY Menem elainld Malka ew Mi near n eae e (elt sd tutorial. However, let's expand that and look at entering your ee eeu ene nme cenit coe 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. PEPE you've closed Python 31DLE, reopen itin ‘whichever operating system version you prefer. in the Shell, enterthe familiar Following: print ("Hello") ESTEEM ses procicted, the word Helo appearsin the Shel as blue text indicating output From ating, Ie Falrlystro'chtForward ane doesnt require too much explanation. Nowtry printc*242") ET) 20st cae soes- ves ‘You can see that instead ofthe number 4, the BD occ istne 212 youashed tobe printed the screen. The quotation marks are defining what's belng outputted tothe IDLE Shell to print the total of 242 you need toremove the quotes: print(2#2) BEER Youcan continue as such printing 242, 464+2343 and so on tothe Shell. An easier wayisto use a variable, which fs something we wil cover in more cepth later. For row, enter: FETTER) hot youhave done here is assign the letters a ‘and b two values: 2 and 2, These are now variables, wich can be called upon by Python to output, edd, subtract, divide {and s0.on for aslong as their aumbers stay the same. Try ths printca) print(b) PETER The output of the last step displays the current values of both aand b individually, asyou've asked them to be printed separately. IFyou want toadd them up, you can usethe following: print (a+b) This code simply takes the values ofa and b, adds them together, and outputs the result. Pg es cr an mn BETS You con play around with different kinds of variables ‘and the Print function. For exemple, you could assign variables for someone's name: nome="Davia” print Crome) rit iss) Your First Code Cl FETED Now lets adc a sumame: surnane="Hayward” print (surname) ‘You now have two variables containing a First name and asurname and you can print them independently be ast oat oops rotor EE we were to apply the same routine as before, Using the + symbol, the name wouldn't appear Correctly nthe output inthe Shell Try its print Chanersurname) ‘You needa space between the two, defining them astwo separate values and not something you mathematical play around wich, ETc ER 12 Pthon 3 you can separate the two varlables: with a space using @ comma printChane, surname) Alternatively, you can add the space yourself print(name+” “+surname) ‘The use of the comma is much neater, as you can see, Congratulations, you've just taken your Fist steps into the wide world of Python, Zz ) Getting Started with Python Saving and Executing Your Code CRM ne Mea OMe Seer N IN olen rll Caele eagle) e eal g designed for entering longer program listings. In this section you're going to be 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 Editor will allow you to save and execute your Python code, STEERED Fi'st.cpen the Python IDLE Shell and wien t’sup, EARESIEWM) You can see that the same colour coding isin place lick on Fle >» New File. This will open a new window Inthe [OLE Editor asitis in the Shell, enabling you with Untitled as itsname. Thisis the Python IOLE Editor and within it tobetter understand what's qoing on with yaur code. However, to ‘youcan enter the code needed to create your Future programs. execute the cade you need to first save't. Press FS and you get a Save...Check box open. ETS eED The IDLE Editor's, forall intents and purposes, a BEE DD ick on the Ox button in the Save box andselect @ simple text editor with Python Features, colour destination where you ltsave al your Python code, coding and so on; muchin the same vein as Sublime. You enter The destination can be 2 dedicated Folder called Python or you code as you would within the Shel, so taking an example from the can just dump it wherever you lke, Remember ta keep a tidy drive previous tutorial, enter. though, to helo you out inthe Future, print (‘Hello everyone!”) pees ET) 20st ce sees- vues BETTS) Enter aname for your code, ‘print helio for ‘example, and click on the Save button. Once the Python code is saved it's executed and the output will be detailed in the IDLE Shell. inthis case, the words Hello everyone'” Tis is how the vast maforty of your Python code will be conducted. Enter it nto the Editor, hit, save the code and look at the autput in the Shel, Sometimes things willeiffer,dependina on whether you've requested a separate window, but essentially chats the process. t's the process we will Use throughout this book, unless otherwise stated. Saving and Executing Your Code Cl 2 be2 nawe="David” surname="Hayward” print(nane, surname) print a+b) \F you press F5 now youll be asked to save the file, agai, as i's been modified From before. Let's extend the code and enter a few examples From the previous tutorial IFyou click the Ox button, the file willbe overwsrleven with the new code entries, and ‘executed, with the output inthe Shell t's nota problem with just these few lines but if you were to edit alarger file, overwriting can become an issue. Instead, use File > Save As from within the Editor to create a backup. FEPTEM vou o0en the file location ofthe saved Python code, you can see that itendsin a.py extension, ‘Thisis the defauit Python Fle name. Any code you create willbe vthatever py and any code downloaded from the many Internet Python resource sites will be py. Just ensue thatthe codeis written far thon 3. ge Now create anew file, Close the Editor, and open SEA anew instance (File > New File from the Shell). Enter the following and save it as helio py ‘o="Python” betis? c="cool print(a, b, ¢) ‘You will use this code in the next tutorial. Teun) nowpiboamenrenoaeynay a 5 Em Fmt Gti rae Se 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 in the GUI at the command line level. DMs Definitve Guide Sere Executing Code from the Command Line Cl Ez Now enter: exit() to leave the command line Python Be The result of running Python 3 code From the session and return you back to the commans Python 2 command ine is quite obvious, Whilst it v, due to the differences between th prompt. Enter the folder where you saved the code from the doesn't er ou way Python 3 handles the Print command over Python 2, the resul Using Sublime for the moment, open the P es within; hopeful should see the hello as the code you're BED nce Sublime Text Isnt available For the Raspberry wing into the Pi, you're going to temporarily leave the Pi for the ed to use the Python IDLE. ito include the Fol ne hellopy File open, python3 hello.py This execute the code we created, which to remind yo nane=inputC"What is your name? “) o="Python” print(‘Hello,”, name) print(a, b,c) Bem * aly, since this is Python 3.code, using the Bie * the hell.py File and drop back to the syntax and layout that's unigue to Python 3, it only ‘command line. Now execute the newly saved smmand. If youlike, try the same code with: rks when you use the pyehor python3 hello. py PESOS, The result will be the exiginal Python is cool! statement, tagethe ne added input command asking yo CJ) cetting started with Python Numbers and Expressions CNTR Meier eaesets ues keaton el ccc elec cde R UE AOL ACTIU 9) (oe: (ello Raa (elt een Woe UTA nab) mei 1m eam ell col MUN nam (ele (Lod IT’S ALL MATHS, MAN You can get some really impressive results with the mathematical powers of Python; as with mest, if not all, programming languages, maths is the driving force behind the code. ‘Open up the Gul version of Python 3, 2s mentioned SALEM 0 cass ether he shoo the Editor Forthe 'bme being, you're going to use the Shell ust to warm our maths muscle, which we believe isa small gland located at the back of the brain (or not Se ee reo: mer tr me Sheen FEED the Shell enter the following: 22 54356+34553245 99867344°27344484221 ‘You can see that Python can handle some quite large numbers. BE) 205 scot case sees- vss ‘oun vel the usal mathematical operations SE divide, multiply, brackets and so on. Practise with 2 Few, For example: ve o2 23293 casz ea") FEE Youveno doubt noticed, division producesa decimal number. In Python these are called Floets, ‘or floating point arthmeti. However, you need an integer as ‘opposed to a decimal answer, then you can use a double slash 10/3 Will display 3333333333, whichis of course 33-recurring you now enter: 1083, This wil Inco ‘You can also use an operation tosee the remainder left over From dlision, For example: isplay 1, whichis the remainder left over from dividing 10, Pere Next up we have the power operator, or ‘exponentiation if you want to be technical To work ‘outthe power of something you can use a double multiplication symbolor double-star on the keyboard: 23, 10*10 Essentially, t's 2x22 but we're sure you already know the basics bbohind maths operators This ishow you would werk t outin Python, ESTED Numbers and expressions don't stop there, Python. has numerous builtin functions to work out sets (of numbers, absolute values, complex numbers and a host oF ‘mathematical expressions and Pythagorean tongue-twisters. For ‘example, to convert a number ta binary, use binc3) (_ Numbers and Expressions PPI this wil be cisplaed as ‘0b1"", converting the integer into binary and adding the prefix Ob tothe Front. IFyouwant to remove the Ob prefix, then you can use: format(3, *b?) The Format command convertsavalue, the number 3,to-2 Formatted representation as controlled by the Format specification, the’b’ part. BETTIE DD coolean Expression isa locica statement that will either be true or False. We can use these to compare data and test to see I i's equal to, less than or greater than. Try this ina New Fie a= b=7 print(l, a = 6) print(2, a = 7) print, a= 6 and b= 7) print(4, ¢ = 7 and b = 7) print(S, not a == 7 and b = 7) print(6, a == 7 or b == 7) print(?, a == 7 or b == 6) print(®, not (a —= 7 and 6 = 6)) print(9, not a == 7 and b = 6) BREED Sxccute the code from Step 9, and you can see 2 series of True or False statements, depending on the result ofthe two defining values: 6 and 7. t's an extension of what you've looked at, and an important part of programming, Zz ) Getting Started with Python ) Using Comments When writing your code, the flow, what each variable does, how the overall program will operate and so ons all inside your head. Another programmer could follow the code 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. fa variable is used, the programmer comments on what it’s supposed to do, for example. I's just good practise. PED sist by creating anewinstanceof the Le editor — BAIBM resave the code anc execute it. You can see that the (Fite > New File] and create a simple variable and utputin the IDLE Shellisstilthe same as before, print command: despite the extra lines being added. Simply put, the hash symbol (#) me denotes a line of text the programmer can insert to inform them, TEEN eR ErE aan ‘and others, of whats going on without the user being aware ‘Save the file and execute the code, E year 12S Cowan hresinnepmoacmrennaay ea] Ml ary BEER Burning the code wil return the tine: The value ofA EMMA Lee's assume that the variable A that we've created is, 10 into the IDLE Shell window, which iswhat we isthe numberof lives in a game. Every time the expected, Now, add some of the types of comments you'd normally player dies, the valve is decreased by 1, The programmer could see withincode Insert a routine along the lines oF: # Set the start value of A to 10 on10 intC“You’ve just lost a life!) # Print the current value of A ‘int("You now have”, a, “Lives left!”) print(The value of A is,” a) ET 20st cae sees- vues ‘whilst we know that the variable Aislives, and that the player has ust lost one, 2 casual viewer or someone checking the code may not know. Imagine for a moment thatthe code istwenty thousand lines long, instead of just our seven. You can see how handy comments are Sia # Set the start value of A to 10 ani0 # Print the current value of A print(The value of A is,”, a) ‘# Player lost a life! 0-1 # Inform player, and display current value of A Gives) print("You’ve just lost a life!”) print(“You now have”, a, “lives left!”) Essentially, the new code together with comments ‘could look tke: Be You con use commentsin different ways, For ‘example, Block Comments ae alarge section of text that details what's going on in the cade, such as telling the cod= reader what variables you'e planning on using # This is the best gone ever, and has been developed by a crack squad of Python experts # who haven't slept or washed in neeks. Despite being very smelly, the code at least # works really well. Using Comments Cl BETS line comments are comments that follow section of code. Take our examples from above, instead of inserting the code on aseparate line, we could use: o=10 # Set the start value of A to 10 print("The value of A is,", a) # Print the current value of A ona-1 # Player lost @ Life! printC"You’ve just lost a life”) printC"You now have”, a, “lives left!”) # Inform player, and display current value of A (lives) FETED The comment, the hash symbol, can also be used to comment out sections of code you don't want to be ‘executed in your program, For instance, if you wanted to remove the first print statement, you would use: # print(*The value of A is,”, a) Ele fot Format Bun Options wedows Heb 7 Sgt te start valin of Ae 10 W prame the current value of & Taform player. and display current value of & (lives) prane(“vYou've just lost 9 Tifel") Fink “Vou now have", a. “Lives Lefe}*) BETTER ov 2650 use three single quotes to comment. ‘out a Block Comment or multiline section of ‘comments. Place them before and efter the areas you wantto ‘comment for them to work This is the best gane ever, and has been developed by a crack squad of Python experts who haven't slept of washed in weeks. Despite being very smelly, the code at least works really well. ED) cna sesvnion Working with Variables Wee seu CU oR Ue CRT sTenelkees eluset gd ee cies eae ater each iueccccu eens crcl 71a cok: BU-1gT101(3 VARIOUS VARIABLES. You'll be working with the Python 3 IDLE Shell in this tutorial. F you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. In some programming languages you'e required to use adollar sign to denote astring, which isa variable made up of multiple characters, such asa name of a person. In Fython this isnt necessary. For example in the Shell enter: eme="David Hayward” (or use your own name, uniess you're also called David Hayward) ‘You can check the type of variable in use by issuing the type 0 command, placing the name of the variableinside the brackets. n our example, ths would be: type name). Add 2 new sting variable: title=” Descended from Vikings”. ET) 20 sont csesoes- vues ‘Youive seen previously that variables can be concatenated using the plus symbol between the variable names. nour example we can use: print Cname + Gite). the middle part between the quotations allows us to add a colon and a space, 2s variables are connected without spaces, so we need to add them manually. “ie Ek Pe) Oy Bins ees Bey en Fiat we TT irs Set ee ti scene PR Youcanato combine vatiables within another variable. For example, to combine both name and title variables into.a new variable we use: charactersnane +: “+ title ‘Then output the content of the new variable as print (character) Numbers are stored as different. variables: oge=44 ‘Type Cage) hich, as we know, are integers. ESTED tovever, you can't combine both strings and integer type variablesin the same command, as you would a set of similar variables. You need to either turn ane into the ‘other or vice versa. When you do try to combine both, you get an error message: print (name + age) a Thisis a process known as TypeCasting. The Python codes: Bisa print (character +“ is“ + str(age) +" years old.) oryou can use! print (character, “is, age, “years old.") Notice again thatin the last exemple, you don't needthe spaces. between the words in quotes as the commas treat each argument to print separately >>> print (name + age) Traceback (most recent call Last): File "". line 1, in cnodule> print’ (name + age) Typetrror: can't convert ‘int object to str implicitly int (character * "ss" + str(age) +" years old Descended fron Vikings is 14 years old. int (character, "is", age, “years old.) Davis Hayward: descended from Vikings is #4 years old > ESTED “nother example of Typecasting is when you ask for input From the user, such as a name. for example, enter ‘age= input C*How old are you? *) Alldata stored from the Input commands stored asa string variable. [PES Foe eae ym ny eh eetise" or “Lean for nore ntomation SS yetage Working with Variables BERD This presents a bit of a problem when you want to werk with a number that's been inputted by the user, as age + 10 won't work due to being a string variable and an integer. Instead, you need to enter: ‘intCoge) + 10 ‘This will TypeCast the age sting into an integer that can be worked with pts a's cers “nays iy SS EER The use of typecasting is also imaortant when dealing with floating point arithmetic remember: ‘numbers that have a decimal point in them. For example, enter shirt=19.99 ‘Now enter typeCshirt) and youllsee that Python has allocated thenumber asa float, because the value contains a decimal pint 2 CGetaule, Oct 19 2074, 132317 or lane cn Meredste” oF “2icanee()* for When combining integers and floats Python BUEN usually converts the integer to a Float, but should the reverse ever be apple's worth remembering tha Python does return the erat value, he converting oat oan integer Futon il aways ound down foe neering, Caled tuneaingynourcasesteado!1933HCoscomes 3 Python 3.2 (aafoult, et 19 26, feet a.9:41 on Lira type Scortign”. Seedits: or “License for are internation. 3s Sypetan Eclost"fiwat’> ssePtnecehare) CJ) cetting started with Python User Input NTR Merten Ine Ilan eR Raee renee eC e kis eereM oa Ay rele Chol agood time to focus solely on how you would get eu ne a aot ele colds USER FRIENDLY The type of input you want from the user will depend greatly on the type of program you're coding. For example, a game may ask for a character's name, whereas a database can ask For personal details. ETRE "is notalready, open the Python 3 OLE shell, ESTEE RD Xo that we have the user’sname stored ina ‘and start a New File in the Editor. Let's begin with couple of variables we can callthem up whenever somethina really simple, enter we want print ("Hello") printC'Welcone”, firstnane, surname, *. T hope firstnanesinputC“What is your first name? “) you’re well. today.”) printCThanks.") Surname=inputC“And what is your surname? ) STEEP Seve and execute the code, and as you aleadyno REEMA Run the code and you canseea sightissue, the ‘doubt suspected, inthe IDLE Shell the program wl fullstop after the surname follows a blank space, ask for your firstname, storia tas the variable firsiname, folowed Toliminate that we can add a plussign instead of the comma in by your surname; also stored ints own variable surname). the code: printC‘Welcone”, firstnane, surnames. T hope you're well today.”) Bie oy “eg fr er ne ET) 20s cnt case soes-vuess ‘You don'talways have to include quoted text within Bisa the input command. Forexample, you can ask the user their name, and have the input inthe line below. print¢‘Hello. What's: your name?”) rrane=input() tsetinputpy - home/pi/Documents/Fython Code/us) ‘Ble Edt Format Bin Options windows Hap whats your nave?) The code from the previous step is often regarded ‘as being alittle neater than having lengthy ‘amount of text in the input command, buts ata rule that’s sein stone, so do as you like in these situations. Expanding onthe code, teythis print(‘Halt! Who goes there?”) name=input() ESTED) (¢52 coodstarcto atext adventure game, perhaps? Now: you can expand oni and use the raw input From the usertolesh aut the game alittle: if name=="David”: printC‘Welcome, good sir. You may pass.”) else: print(“Z know you not. Prepare for battle!) Uarriatey, Reveppioocureraiyien Coomnpa eyez) = em He Est Famat ash ote nde te User Input Cl What you've created here isa condition, which we _nill cover soon. n short, we're using the input from the user and measuring it against a condition. So ifthe user enters David as their name, the guard will alow them to pass unhindered. Else ifthey enter a name ather then David, the guard challenges them toa fight. PEPIEDD us: 25 you learned previously, anyinout froma Useris automaticallya sting, so you need to apply a Typecastin order toturnitinto something else. Thiscreates some interesting additions to the input command, For example: # Code to calculate rate and distance print(Input a rate and a distance”) rate = floatCinput(*Rate: “)) [Be Est Fara fun Options Yordows tap mae ESTEE 10 finalise the rate and distance code, we can add: distance = floatCinput("Distance: *)) print¢“Time:”, (distance / rate)) ‘Save and execute the code and enter some numbers. Using the Fioat{input element, we've told Python that anything entered is Foating point number rather than a string. C) cetting started with Python Creating Fun ctions Mauer eur cute gr Meters tyeol te functions. You've already used a few functi enables you to define your own functions. ions, such as the print command but Python FUNKY FUNCTIONS ‘A function isa command that you enter into Python to do something. It's alittle piece of self-contained code that takes data, ‘works on it and then returns the result. Isnt just date that» Function works on, They can SE 2 rpanccr of sel things Python such 3s sort data, change items from one Format to another and check the length or type of items, Basically, function isa short word that's Followed by brackets. For example, ten(),list() or type). FTE RD function takes data, usualy averiable, works on it cdepending on what the Function s programmed to do and returns the end value, The data being worked on goes Inside the brackets, soif you wanted to know how many letters are in the word antigisestablish entarianism, then you'd enter: Len(*antidisestablishnentarianisn") and the number 28 would return, DMs Definitve Guide Seves-Voiume 35 ‘You can pass variables through functions in much thesame manner. Let's assume you want the ‘numberof letters ina person's surname, you could use the Following code (enter the text editor for this example): nane=inout (“Enter your surname: *) count=Len(nane) print C*Your surnane has", count, “Letters in ie”) ress FSand save the code to execute it. PETER Python has tens of functions buitinto't, fartoo ‘many to get into in the limited space avaiable here. However, to view the Ist of bulltin Functions avallable to Python 3, navigate to www.docs.python.or9/3/library/Functions html. These ate the predefined functions, bt since users have created many ‘more, they're nat the only ones available, (_ Creating Functions Cl Additional functions can be added to Python Touse a Function from amocule enter the name of the module followed by a full stoo, then the name modules available that can cover numerous programming duties. oF the Function, Forinstance, using the Math mocile, since you've They acd functions ancl can be imported as and when required, For just imported it into Python, youcan utilise the square root Funetion. ‘example, to use advanced mathematics Functions enter: Todoso, enter import math math. sqrt(16) ‘Once entered, you have access coal the Math module Functions, You can see that the cade is presented as module function’data) FORGING FUNCTIONS ee aCe ne rue a ee Rn en tos De re ae se eee ten nee ees PED 15 modity it further, delete the tilio("0 es eee eco ee eee crs File) Enter the Following ross F5 to save and run the scriat You can see Hello in the Sh ee re Ree eee tert meted Be What you've ust done isimport the Hello Function ee STERIA rere ies ee recent import the module then use the Funct et wodkinabitonon CT C) cetting started with Python Conditions and Loops Conditions and loops are what make a program interesting; they can be simple or rather Crue eeu ener ean uraast ascii they could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's star then by checking if something is TRUE, then doing something else ie isnt. Let's create anew Python program that wil ask Now you ca use anf staterentto checkiFthe SMD trcusetoinpstavordtrencheckittosee rts Maal ora ovat varile's eau to four and orine a a fourletter wordar not Start wth Fle> New File, and begin with Fiandly conformation apps tothe rule Ses)onathvadale word-inout(*Please enter a four-letter word: word=input(*Please enter a four-letter word: “) word length=lenCword) Tf word_length = 42 print Gword, “is a four-letter word. Well done.”) ‘The double equal sign something ese ) means checkif something is equal to FETED Now we can create a new variable, then usethe len [ERA The colon atthe end of IF tells Python that if this function and pass the word variable through i to statement is tre do everything after the colon getthe total number o eters te user has ust ercered: thats Indentes, Newt, move the c's backto the Becnning oF word=input "Please enter a four-letter words") “efor ord. lengthelencword) wordainoutC*Please enter a four-letter wo word_LengtheLenCword) if word length == 4: print (ord, “is @ four-letter word. Well ma fri et i et 2 etter) I) 20st case soes- ves ( Conditions and Loops Cl Now press FS again and rerun the program but this time enter a Fiveletterword, The Shell wil splay thatt'snota Fourdetter word: word=inpurt(*Please enter a four-letter word: “) word_length-LenCword) if word_Length print (word, “is @ four-letter word. Well, done.) elif word_length == 3: print (word, “is a three-letter word. Try again”) else: print (nord, “is not a four-letter word.”) LOOPS eed ee ue a ete ae ae eM ene eed block of code @ number of times, usually with the support of a condition. epee ae ee STEP Dear ea an aan STEPS Cu ee mete frords=t-cat™, “og, “Unicorn I Se For_word in words:] erin Cee print (nord) eras r f The Fer loop canalsa be used in the countdown STEP 2 Takeicigedarsacis five STEP 4 ese besepesiereasenes tontea ener eee ees. [for x in range (1, 10):) print (5} eee eee en Neen ea tga See ee eee) ist Getting Started with Python Python Modules 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, h good, the builtin Funct n Python Be * result is an error in the 10! 3 limited, The use of modules, h allows us Pygame modules recognised or inctalled in to make more sophisticated programs, As you are aware, modules Python, Toinstall a module we can use PIP (Pip installs Packages) are Python scripts that are imported, such asimport mat Close cown the IDLE Shell and drop into a command prompt or Tecminal session. At an elevated admin command prompt, enter ip install pygame arent always avalable.Agood Win arch For CMO via the Start button and right: prime example. Sadly, other modul example onan Fi platforms isthe Pyaame module, which contains click the resul Run as Administrator, Linux and Mac users ‘many functions to help create y- import pygame. cause the Sudo command, with sudo pip install packagy DMs Definitve Gude Seres-Volom Close the command prompt or Terminal and felaunch the IDLE Shel. when you now enter: {import pyqame, the module will beimperted into the code without any problems. You'l Find that most-code downloaded! or copied from the Internet will contain armodule, mainstream oF Unique these are usually the source of errrsin execution due to them being missing, ae z ESTED The modules contain the extra code needed to achieve a certain result within your own code, as welve previously experimented with, For example: import random Brings in the code from the Random Number Generator module. ‘You can then use this module to create something like: for i in range(10): printCrandom.randint@2, 259) with the code to display more or less, and froma great ar lesser ‘This code, when saved and executed, will display ten random numbers From 1 to 25. You can play round range. For exemple: ‘import random for’ in range(2s): printCrandom.randint¢1, 100)) ( Python Modules Cl ‘import random ‘inport math for I in range(s): print(random.randint(2, 25)) printGnath.pi) ‘Multiple modules can be Imported within your code, Toextend our exainple, use: ‘The result is a string of random numbers followed by the value of Fi as pulled from the Math module sing the print(math function, You canals pullin cetain Functions from 2 module by using the from and import commands, suchas: from random import randint for’ i im rangecs): print(randint(1, 25)) ERED Thishelps create amore streamlined approach to ‘programming. Youcan also use import module’, ‘which wil import everything defined within the named module However, i's often regarded as a waste of resources but it works ‘nonetheless. Finally, modules can be imported as aliases: ‘import math asm print(m.pi) Of course, adding comments helps to tel others what's going on. (tation: indSicmensiendtenbey OL =~ x poe Index DMs Definitve Guide Seves-Voiume 35. “The most important single aspect of software developmentis to be clear about what you are trying to build.” ~ Bjarne Stroustrup (Developer and creator of C++) ( Working with Data Cl Data is everything. With it, you can display, control, add, remove, create and manipulate Python to your every demand. Over these coming pages, we look at how you can create lists, tuples, dictionaries and multi-dimensional lists, and then how you can use them to forge exciting and useful programs. In addition, you will learn how you can use the date and time functions, write to files in your system, and even create graphical user interfaces that will take your coding skills to new levels and into new project ideas. Lists Tuples Dictionaries 52__ Splitting and Joining Strings 54 Formatting Strings 56 Date and Time 58 Opening Files 60 Writing to Files 62 Exceptions Python Graphics see z= Working with Data ) Lists f Meer ero mesons ogee eetet icy No N TI Keone sa Tee Wa Sue Kee)l renee emo Re eM Mole cme ey erE (eee eRe Mol individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include Functions in lists, and lists within lists. FE ioc oscesianayeaion ies BRR oscssocos sce ventonnnt ERD ese ocetesccscatem talons sian, then square brackets and the items separated by commas; __orthe second to last tem with |-2) and so on. Trying to reference an ote that strings use quotes: item that isnt thelist, such a [10] will return an error: numbers = [1, 4, 7, 21, 98, 156] urbersf=1] mythical_creatures ~ ["Unicorn”, “Balrog “Vampire”, “Dragon”, *Minotaur™] nrythical_creatures{-4] PETER Once you've defined yourlist you can calleach FETED Slicing is simitarto indexing but you can retrieve by eferencing itsname, Followed by @ number Lists ‘mulkiple tems na list by separating item numbers start the Firstitem entry as90, Followed by 1,2, 32nd s0.on, with a colon, For example: Fosesorible: funbers[2:3] aS ‘will output the 4 and 7, being itera numbers 1 and 2. Note that the Tocall up the entire contents ofthe lst. retumed values don't include the second index position (as you ponisars03) would numbers[1:3] to return 4, 7 and 21), Tocall the thitc from zero tem inthe lst (21 inthis case). BI) 205s cnt ce sees-vuess BTS) YoU con update items within an existing list, remove items and even join lists together. For example, to join two lists you can use: everything = nunbers + mythicalcreatures ‘Then view the combined list with: everything FETT (ters con be added toalist by enteric: nunbers=nunbers+ £201] Orforstrings: tiythicalcreatres-mythical creaturess[*Griffin'] (Or by using the append function: mythical_creatures..append("Nessie”) nunbers -append(278) Removal of items can be done in twoways. The first sues isby the item number: del nunbers(71 Alternatively, by tern name: mythical_creatures :nenove(“Nessie”) ee + = Cm You can view what can be done with lst by entering dist) into the Shel. The outputs the available Functions, for example, insert and pop are used to add and remove items at certain postions. To insert the number 62 at iter index 4 nunbers.insert(4, 62) Toremovelt: unberspopC4) BPI vou ato use thelist function to breaka string down intoits components. For example: VistC“Davia"> Breaks the name Davi int st, Vy, This canthen be passed ros new st name=List(“David Hayward”) rane age=[44] User = nane + age user Based on that, ou can create 2 program to store someone's name and age asa list nane=inoutC*Ahat”s your mane? Uname=TistCnane) age=intCinputc"How old are you: “)) ‘Lage=[age} user = Iname + Tage The combined name and age lists called user, which can be called bbyentering user into the Shell. Experiment and see what you can do, | san ne ae ae waco Zz 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. ‘Atuple i created the same way 35a lst but in this al instance you use curved brackets instead of square brackets. For example: months=C"January”, “February”, “March”, “April”; “May”, “June”) months ris" oe “eae ft mae namin. -Justas with lists the items within a named tuple can be indexed according to the'r position inthe data range months] ‘months[5] However, ary attempt at deleting or adding to the tuple will result In an errorinthe Shell BT) 20st ce sees- vues Youcan create grouped tuples it sts thatcontan Sie multiple sets of data. For instance, here isa tuple called NPC (Non Piayable Characters) containing the character name and their combat rating for an adventure game: NPC=[C*Conan”, 100), ("Belit”, 80), (*Valeria”, 95)) FETED £2ch of these dataitems can be accessedasa -uhole by entering NPC into the Shel: or they can be Indexed according to thelr position NPC/0}. You can also index the individual tuples withinthe NPC Ist. WPCC] C1 ‘wil display 100 BETTS) |¢sworth noting that when referencing multiple tuples within alist, the indexingis slightly different From the norm. You would expect the 95 combat rating ofthe character Valeria to be NPC[AI[S], but i's not. R's actually: NPC(2] [1] Be Ese Se tg care ane ae | a ERTS This means of course that the indexing follows th @ ual a0 2 a1 200 1 2a 10 Which as you can imagine, getsa tle canfusing when you've got a lot oF tuple detato deal with, FETTER Tuples thouch utilise a feature called unpacking, ‘where the data tems stored within a tuple are assigned variables Fist create the tuple with two items (neme and ‘combat ratingh NPC=C*Conan”, 100) Now unpack the tuple into two Ss} corresponding variables Chame, combat.rating)=NPC ‘You can now check the values by entering name and combat rating. FETED member as with ists, you can also index tuples using negative numbers which count backwards From the end of the data list For our example, using the wplewith ‘multiple data items, you would reference the Valeria character with: NPCL2IC-0] You can se the max and min functions tofind the SHEA) highest end lowest values of a tuple composed of rhumbers. For example: punbers=(10.3, 23, 45.2, 109.3, 6.1, $6.7, 99) ‘The numbers can be integers and floats. To output the highest and lowest, use: print Gnax(nunbers)> printGmin¢nunbers)) “Be 5 on Ds As 4 » Working with Data Dictionaries Meera aae tt ae ionaries 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 be able to apply them to your own code. KEY PAIRS A dictionary is like a list but instead each data item comes as a pair, these are known as Key and Value. The Key part must be unique and can either be a number or string whereas the Val FETED 22s 527 you want to create a phonebook in Python, ‘You would create the dictionary name and enter te data in cuty brackets, separating the key and value by a colon Key:Value. For example: phonebook={“Enma”: 1234, “Daniel”: 3456, “Hannah”: 6789} ES eeED est aswith most lists, tuples and so on, strings, need be enclosed in quotes (ingle or double, whist integers can be left open. Rememiver thatthe value canbe ether a string or an integer, ou just need to enclose the relevant cone in quotes: Phonebook2={*David”: “0987 654 3217} got Pee in BEIT EE 20m Detntve Guide Series-Volume 3s FTSSEDD swith ists and tuples, you can check the contents of adictionary by giving the dictionary a name: phonebook, in this example. This wil display the data items you've entered ina similar fashion to alist, which you're no doubt familiar with by now, PETER Thebenefitof usinga dictionary that you canenter the key to index the value. Using the phonebook example From the previous steps, youcan enter: phonebook [*Enma”] phonebook[“Hannah"] BETTER) ding toa dictionary is easy too. You can include _anew dataitem entry by adding the new key and value iter ike: phonebook[“David"] = "0987 654 321” FETED Vou canalso remove items froma dictionary by Issuing the del commend Followed by the item's key; the valve willbe removed as wall since both work asa palr of data items del phonebook[“David"] BETTE 12king thisa step Further, how about creating a piece of code that will ask the user for the dictionary keyand value tems? Create a new Eciter instance and start by coding in anew, blank dictionary: phonebook={} ( Dictionaries BETTE DD Next. vounced todefine the userinputs and variables: one for the person's name, the other for their phone numiber (let's keep itsimple to avoid lengthy Python codey awe=inout "Enter name; "*) nunber=intCinputC“Enter phone nunber: *)) Note we've keot the number as an integer instead of astrng, eventhough the value canbe both aninceger ra string, Now you need toad the user's inputted variables tothe newly created blank dictionary, Using the same processasin Step 5, you can enter phonebook(nane] = number ERR "22 when yousave and execute the code, Python will ase for aname and a number. it wil then insert those entriesinto the phonebook dictionary, wiih you can test by entering int the Shel: phonebook phonebook [“David'] ifthe numer needsto contain spaces you need to make ita srng, soremovethe int part of the input z= Working with Data) Splitting and Joining Strings When dealing with data in Python, especially From a user's input, you will undoubtedly come across long sets of strings. Auseful 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 ED te scantcaigtnonsenatc ote. SBR vecoue eas potatoe ERD vococncceessergss ete, gesinrcreemencnsas Value) contenthas a comma, so you'd use: texte"January, February,March, April, May, June” motrths=text. splitC*,") imorrths, FETTER) Now let's turn the string into lst and split the BETS Youve previously seen how you can split a string ‘content accordinaly: Into individual letters asa Us, using a name: namesstextsplitC *) name=List(*David") ‘Then enter the name of the new list, names, toseethe three tems, A"® The returned value is‘Dy, 2, 'v, ", "a. Whilst it may seem alittle useless under ordinary circumstances, it could be handy For eating 2 spelling game For example, ED) 20s cnt ce soes- ves ESTED The opposite ofthe spit Function is join, where ‘you willhave separate itemsin a string and can join them all together to Form a word orjust a combination ofitems, depending on the program you're writing. For instance alphabet="".join(L"a”,"b","c”,"a",7e"]) alphabet ‘This wil display ‘abcde in the Shell cr \ Splitting and Joining Strings Cl BET DD swith che split Function, the separator doesn't have to be a space, it can also bea comma, a ful stop, a hyphen or whatever youtlke: colours=[*Red”, “Green”, “Blue”] col=",”. join(colours) ‘You can therefore apply Join tothe separated name ‘you made in Step 4, combining the letters again to Bisa Foimthe name: -Joingnane) ames" nome ‘We've joined the string back together, and retained the list called rhame, passing it through the join Function, sentence: Liste["Conan®, “raised”, “his”, “mighty”, “svord”, ‘tand”, “struck”, “the, “denon™) text" *.join(list) text ‘A.qood example of using the Join Function is when {you have alist of words you wentto combine into Note the space between the quotes before the join function (where there were ne quotes in Step 6's join) ‘There's some interesting Functions you apply to a Bid string, such as capitalize and .tle, For example: titlee”conan’ the cimmerian” title.copitalized) title.titleQ BEET ou cen also use loaic operatorseon strings, with the in’ and ‘not in’ Functions, These enable ‘you ta check fa string contains (or does nat contain) a sequence of characters: messoge="Have a nice day” “nice” in message "bad? not in’message “day” not in message “night” in message " “Se EM Set Doha Gres yo ' | eo a » Working with Data Formatting Strings When you work with data, creating lists, dictionaries and objects you may often want Rema es a Uri Rumen cc raeodeeeccr Miearanen Oem eeuo manent eccentrics 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. PEPTEM The basic Formatting in Python isto call each BEPTIEB) You can of course also include integers into the mix variable into the string using the curly brackets: nunber=10000 names"Conan” printC'{} of {} was o skilled mercenary, print ("The barbarian hero of the Hyborian’ Age is: ond thief too. He once stole {} gold froma 4)". formatCnane)) merchant”. format(name, place, nunber)) Remember to cose the print function with two sets “There are mary different waysto apply string ‘Of brackets, as you've encased the variable in one, formatting, some are quite simple, as we've shown and the print function in anather. You can include multiple cases of you here; others canbe sianiFicantly more complex. tall depends string formatting in single print Function: Conwhat you want From your program. A good placeto reference Frequenty regarding sting formatting i the Python Docs webpage Found at www.docs.python.org/3.1/library/string.html Here, you val find tons of help rame="Conan” place="Cinneria” print("{} hailed from the North, in a cold land known as. {}".format(name, place)) ee se anane i EXD 20m: Detntve Guide Series-Volume 3s ETD sterestinaly you can reference alist using the string foimatting Function. You need to place an asterisk in Front ofthe list name: nunbers=1, 3, 45, 567546, 3425346345 print (Sone numbers: {}, {, it, 0, 0". Format (*nunbers)) TEED With indexing in lists, the same applies to caling 2 listusing string formatting. You cen index ezch item according to its postion (from Oto however many are present}: nunbers=1, 4, 7, 9 print(’More numbers: {3}, {0}, (2h, {1}.”. format C*numbers)) Eee 742500 probably suspect, you can mix strings ‘and integers in a single st to be called in the Format Function, characters=["Conan”, “Beit”, 20] print (“{0} is {3} years old. whereas {1} is {4} years old.”. format(*characters)) “Valeria”, 19, 27, - (Formatingstines CX You can also print out the content of auser’s input Inthe same fashion: nane=inoutC*Nhat”s your name? “) print¢*Hello 4}.”. Format (name) You can extend this simple code example to display Bed the firstlettern a person's entered name: nane=inoutC*what”s your name? *) print(’Hello 4}.”.FormatCname)) Uname=List (name) print("The first Letter of your name is a {0}". Format(*Lname)) FED ane tunonasa rs averaenc Looking back the code fram Step 7, you can alter it with nanese[“Conan”, “Belit”, “Valeria”] oges=[25, 21, 22] Creating two lists. Now you can call each lit, and individual tems: printC{O[0]} is {1[0]} years old. Whereas {0[1]} ‘is {1[1]} years old.”. Format names, ages)) er Zz Working with Data Date and Time Wien e cenetoicenon eked Ms curl may want to time-stamp an entry or see at what time a user logged into the system and For how long. Luckily acquiring the date and time is easy, thanks to the Time module. TIME LORDS ‘The Time module contains Functions that help you retrieve the current system time, reads the date from strings, formats the time and date and much more. FR ss rccitcinpariieinc roa toe seated re eee sneered ‘import time time asctime() ESTEE The time function is split into ine tuples, these are ‘divided up into indexed ters, as with any other tuple, and shown in the screen shot below, ander eld ‘vale age eae 2016 5 seed (0 61 (60 or 6 ae ap seconds) © Davof meek 006 0 eMondon) 7 avery 1 0.366 oan aay) © avon saings 1, 0.2, means ary detemnes OT DMs Definitve Gude Seves-Voiume 35 time: Local. timec) ‘The outputs displayed as such: time, struck timeCems year=2017, tm_non=9, tm_nday=?, tnhour=9,, ‘tmmin6, tmsec=13, tmnday=3, tmyday=250, tm ‘isdst=0)*; obviously dependent on your current time as Opposed tothe time this book was written. ‘Youcansee the structure of how time is presented byentering eta, wane, tot, mi, tint, se fen ans “There are numerous Functions built into the Time ‘module, One ofthe most common of theses, strftime() Witt you'te able to present a wide range of arquments, as it converts the time tuple into a string, Far example, tocispay the current day of the week you can use: ime: str FbimeCKA) eS aiew ee e s oin, ‘This naturally means you can incorporate various Bisa Functions into your avn code, such as time. strftimeC%a”) ‘time, strFtimeC%8") time, strf time") time. strftimeC“sH") time. strFtime SH") Note the last two entries, with aH and HSM, 35 Bisa ‘you can see these ae the hours and minutes and as the ast entry indicates, entering them as HEM doesn't display the tome eorrectlyin the Shell. You can easily rectify this wth: time, strFeime cmH") PEPPER) thismeansyou're coina to be able to dpa ether the current time othe time when something occurred, suchas user entering their name. Ty thiscode nthe Editor import time name=input (Enter Login names“) print(*Welcome”, nane, *\d”) print(“User:”, name, “logged in at”, time, Date and Time Cl ESTEE BD vousow atthe endof the previous section, in the code to calculate Pito however many decira places the users wanted, you can time a particular eventin Python. Take thecode from above and alter slightly by including start_time-time, time) ‘Then there's endtimo=time. timec)=starttime SS aon b, st fara bm Br ie tne rane, fat some, | The output will look similarto the screenshot below. ‘The timer function needs to be eithersie of the input statement, asthat’s when the variable name is being created, depending on how long the user took to login. The lenathof time is then displayed on the las line ofthe cade asthe endtime variable. FTE SE TR There'sa lot that can be done with the time module; some ofits quite complex too, suchas displaying the number of seconds since January 1st 1970.{F you want to drill down Further into the Time module, then in the Shell enter: helpGtime) to display the current Python version help file forthe Time module. BE) tng ion) Opening Files Matera erste steel Tur aN Cla cere ces You can also write to file, which is something we will look at next. Reading and writing to files enables you to output and store data from your programs. OPEN, READ AND WRITE In Python you create a file object, similar to creating a variable, only pass inthe file using the open() Function. Files are usually categorised as text or binary. {as word processors include backaround formatting and other elements. incur exemple, we have the poem The Cimmerian, by Robert E Howard. You need to save the file as poem.xt Start by entering some text into your system's text iE ba ‘editor. The text editor is best, not a word processor, ESERERD {you nowenter poem into the shell, you will get some information regarding the text file you've Just asked to be opened, You can now use the poern variable to read the contents of the fle poem: read() Note than a /n entry inthe text represents a newtine, as you Used previously ‘You use the open() Function to pass the file into a variable as an object. You can name the ile object anything you tke, But you will need to tell Pythen the name and location of the text file youre opening oem-open(*/home/pi/Docunents/Poem. txt”) ET) 20st cae sees- vues Berea ‘you enter poem.readi a second time you will, notice that the text has been removed from the file ‘You will need to enter: poen=openC*/home/pi/Documents/ Poem: txt) againto recreate the file. This time, however, enter: print (poem. read¢)) This time, the /n entries are removed in Favour of newlines and readable text. ERD ~stasiwith lists, tuples, dictionaries and so.on, ‘you're able to index individual characters ofthe text Forexamle: poem. reads) Displays the First ive characters, whilst again entering: poen:read(S) Will display the nex Five. Entering (1) wil display one character at, atime, ‘Similarty, you can display one line of text at a time by Bisa Using the readline() function. For example: poem=open(*/home/pi/Documents/Poem. txt”) poem readline) ‘wil display the Fist ine ofthe text with: Poem:readLine®) Displaying the next line text once more ‘You may have quessed that you can pass the Et readline() Function into a variable, thus allowing you to callitagain when needed: oein-open(*/home/pi/Documents/Poem. txt") Line=poem.readlineC) Line ( Opening Files Cl BSTETBD tending ths further, you can use readlines to arab allthe lines ofthe text and store them 2s ‘multiple lists. These can then be stored asa variable: poem=open(*/home/pi/Documents/Poen. txt") Lines=poem. readlines() Lines (0) Vinesf1) lines[2] Ss) for lines in lines: printCLines) ‘Since this is Python there are other ways to produce the same output: oem=open(*/home/pi/Documents/Poen. txt") for Lines. in poem: printClines) You can also use the For statement to read the lines of text back to us: BST Lcrsimacine that you want to prine the text one charecter at atime, lke an old dot matrix printer would. You can use the Time module mixed with what yau've looked athere. Try this: import time poem-open(“/home/pi/Documents/Poem. txt”) Vines=poem, read¢) for lines in lines: print(lines, end=" ‘time. sLeepC.15) ‘The output is fun to view, and easily incorporated into your own cade. Zz Working with Data Writing to Files Mon Meder Cocca Ue uns enuercae Tu Micu ata ica ori cae dolce ie] Utara gr mW Un Nit aoe ola M cola e=e-19) ca coRerel dol" aa grae =r LoD cele eT T Co) a file, that you can then read() back into Python. 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 is in read or write mode. FPTSEMD tert by opening IDLE and enter the Following; FETED However, the actual text file stil blank (jou can check by epening it up). Tiss because you've — writen the tine of text tothe fle object but not commited it othe . fle itself. Part ofthe write Function is that you need to commit the Change the destination from /home/piDocuments to your own changes the ile; you can do this by entering system, This codewilceate a text ecalledtextbtinwrite mode: e6s¢5 tsing the variable there's rofl ofthat name inthe location it villcreate one. Fone already exist will verarite it so be careful FREER You can now wrteto the text file using the write) EWM you now open the textile witha text editor, function. This works opposite to read, writing lines ‘you can see that the line you created has been Instead of reading ther. Try ths: vritten to the file. This alves us the Foundation for some interesting ‘NTC rou ranean TAREE TSUNEO REAL pesslitiespsrans the creation afyourown loafer even the single table stands to one side, there isa locked "°dMingof an acventure game door in front of you.") Eases Note the 109.1ts the number of characters you've entered. ena 32S es BT) 20st csesees- vues EEE) To exo2nd this code, you can reopen the file using 12, for access or append mode. This willadd any text atthe end ofthe origina ine instead oF wiping the file and creating 4 new one. For example: ‘teopen(/home/pi/Documents/text.txt”,"a”) t.writec*\n") t-write( You stand ond survey your surroundings. On top of the table is some meat, and a cup oF water.\n"), ETD You cankeep extending the text tne by ine, ‘ending each with anew line (\r) When you're done, finish the code with close) and open the file in atext editor to see the results: tvwriteC*The door is made of solid oak with iron strips. It’s bolted from the outside, locking you in. You are a prisoner!.\n”) t-closeQ) BETTER There are various types of ile access to consider using the open) function. Each depends on how the file is accessed and even the position ofthe cursor. Far example, + ‘opens afile in read and write and places the cursor at thestart of thefile. BED Youcsn pass variables toa ile that you've created In Python, Perhaps you went the value of Pito be written toa file. You can call Pi from the Math module, create a new file and pass the output of Pinto the new File: ‘import: math printcValue of Pi is: “,math.pi) printC\nliriting to @ file now.) Ss) pismath. pi ‘You also need to create-a new fileinwhich to write Pi to ‘teopen(“/home/pi /Docunents/pi-txt”,"w) Remember to change your file location to your own particular system setup. [Now let's create avariable called piand assianit the value of P: BSED 1 fish, vou can use string Formatting to cathe variable and write i to the fil, then commit the changes and close the ile: towriteC*Value of Pi is: {}".format¢pi)) t.closeQ) ‘You can see from the results that you're able to pass any variable to afile (wrunctorie @ (_ Writing to Files Cl Emo Exceptions When coding, you'll naturally come across some issues that are out of your control. eee ae ede icc ec mS Mites nca raven EXCEPTIONAL OBJECTS Rather than stop the Flow of your code, Python includes exception objects which handle unexpected errors in the code. You ‘an combat errors by creating conditions where exceptions may occur, ‘You can create an exception error by simply tiving Bap ‘You can use the Functions raise exception to create BAD vice wrnber by ser. Tis eportback BMD oc eortancing code vthn Paco. Lees with the ZeroDiisionError: Division by zero message, as seen inthe assume your code has you warping around the cosmos, too much screenshot. The ZeroDhisionError partis the exception class,of however results ina warp core breach. To stop the game from which there are merw. exiting due to the warp core going supernova, you can create & custom exception: raise Exception(*warp core breach”) Most exceptions PEPIEPD 10 trap any errorsin the code you canencase the ate raised potential error within a ty: block. This biock consists automatically when Python of try, except, else, where the code is held within try, then I there's, Comes across something that’s anexception do something, ese do something else. inherently wrong with the code However, you can create your cw exceptions that are designed to contain te potential error and react tot, as opposed to leting the code fal be hare swe exception, thm He tis oo ESTER) (or exemple, use the divide by zero error. You can ‘create an exception where the code can handle the error withou Python quitting due tothe problem: try: a-intCinput (“Enter the first nunber: beintCinput(“Enter the second nunoe print(a/b) except Zerodivisionérror: printc*You have tried to divide by zen else: print(*You didn’t divide by zero. Nell done!” FETT) Vou con use exceptions to hanclea variety of useful tasks, Using an example From our previous tutorials, ler’ assume you want to opena file and write tot try: ‘txt = openC"/hone/pi/Documents/textfile. txt”, txt.write(“This is a test. Nornal service will shortly resume!") except 10Erron: print “Error: unable to write the file. Check permissions”) else: print (“Content written to file successfully. Have a nice day.”) ‘txt-close() Obviously this won't work due to the file textile, bitbeing opened as read only (the "part Soin this ease rather than Python telling you that you're doing something wrong, you've created an exception using the IOError lass informing the user that the permissions are incorrect. \ xceptions Naturally, you can quickly fix the issue by changing the “read only instance with aw" For write, This, asyou already know, wil create the File and write the content then ‘commit the changes tothe fil. The end result will report. adlfferent set of circumstances, in this case, a successful execution of the code FTES Youcaen also use a finaly: block, which works ina similar Fashion butyou can't use else with it. To use ‘ur example fram Step 6: try: ‘txt openC"/hotie/pi/Documents/textfile. txt”, “r” try: ‘txt.writeCThis is atest. Normal service will shortly resune!”) final print (“Content written to file successfully. Have a nice day.") ‘txt closeQ) except 10Erro print (*Error: unable to write the fle. Check permissions”) FSTEED DD 45 defore an error wll occur as you've used the read-only permission, IF you change it toa "w", then the code wil execute without the error being displayed in the IDLE Shell. Needless to say, t can bea tricky getting the exception code right the first time. Practise though, and you will get the hang ofit, Zz Working with Data Python Graphics Wine cc Mie sceenenseer Re eee NM eT ec hnet cle acs will come a time when a bit of graphical representation wouldn't go amiss. Python 3 DeSantis u neva rit gre antler GOING GRAPHICAL You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available, to bring out some spectacular effects. ‘neo the best rapes to begining BH Python graphics is Turtle. The Turtle module is, as the name suggests, based on the turtle robots used in many schools, that can be programmed to draw something on a large piece Ct paper onthe aor The rte modal canbe ngewe tort turtte Let's begin by drawing a simple circle. Start New isd File, then enter the following code: import turtle turtlevcircle(sa) turtle. getscreen(): root mainloop@) AS usual press F5 to save the code and execute'it. Anew window will now open up and the Turtie' wil draw a circle IT) 20st case soes- vss ‘The command turtle cicle(50) is what draws the circle on the screen, with 50 being thesize. You canplay around with the sizes if you like, oing up to 100, 150 and beyond: you can draw an arc by entering: turtle.cirele(SO, 180), where the size is 50, but you're telling Python to only draw 180° ofthe circle, L PETER The last part ofthe circle code tells Python to keep the window where the drawing i taking place to remain open, so the user can cick to closet. Now, levs make a square: ‘inport: turtle printC“Orawing @ square.”) for t in rangeC4): turtle. forward(10@) turtle. Left(90) turtle.getscreen(). root mainloop©) ‘You can'see that we've inserted a loop to draw thesides ofthe square You can add a newline tothe square code to add some colour turtle.color(“Red”) sy Then you can even change the character ton actualturtle by entering turtlevshapec“turtle") You can also use the command turtle begin=ALLO, and turtle.end ALLO toll in the square wth the chosen colours; red outline, yellow fillin this case BD Vou consee thatthe Turtle module can draw out some pretty good shapes and become a little ‘more complex.as you begin to master the way works, Enter thisexample: From turtle import * color(‘red?, *yelLlon”) begin ALO while True: forward(200) TeFta70) if abs(pos))'< 1: breaic end_f110) done Isa different butverveff ethod, Eee {nother vay in which you can display graphicsis byusing the Pygame module, There are numerous ays inwhich pygame can help you output graphics to the screen but for now let's look a displaying a predefined image. Start by ‘opening a browser and finding an image, then save itto the Folder where you save your Pychon cade, & a | & | 8 Crivoncoons CE Now let's get the code by Importing the Pygame mode: ‘import pygane pyoane.imitO) ing = pyoame, image: Tocd(*RPi.pna”) white = (255, 255, 255) w= 900 h = 450 screen = pygane.disploy. set_nodeC(w, h)) sereen fill CGviite)) screen.fillCGvAite)) screen blitCing, (@,0)) pygane. display. ftp) while True: for event in pygane.event.get© if event. type = pygane. QUIT: pyaane. quitO ESTEE RD "he previous step you imported pyaame, initiated the pygame engine and asked it to import our saved Raspberry Plage image, saved 35 RP; png, Next you defined the background colour ofthe window to display the Image and the window size as per the actual image dimensions. Finally you have 3 loop to close the window ww = 900 h = 450 screen = pygame.display.set_mode((w, fh) screen. fill((white)) screen. fill((white)) screen.blit(img, (0,0)) pygame.display.flip() while True: for event in pygame.event.get(): af event. type == pygane QUIT: pygame .quit() BETTER 10555 to save and execute the code and your image willbe displayed in a new window, Have e play around with the colours sizes and se on and take time ta look up the many functions within the Pygame module too. RaspberryPi Index “Good code is short, simple, and ESN an tcm ates] baa nta pel i(nef-y pale} tule) out how to get there.” — Sean Parentlbveloper and author) »- > = a 2 BE) 01s Definitive Guide Series-Voiume 35 Using Modules APython module is simply a Python- created source file, which contains the necessary and unique code for custom classes, Functions and global variables. You can bind and reference modules to extend functionality, and then create even more spectacular Python programs. Want to see how to better use these modules to adda little something extra to your code? Then read on and learn how they can be used to fashion Fantastic code. Calendar Module ing the Math Module 0S Module Random M Tkinter vovoebcingublistions som @ ee Calendar Module WORKING WITH DATES The Calendar module is built into Python 3. However, if For some reason it’s not installed you can add it using pip install calendar as Windows adi ies loadedinto memory, start by entering: sep=calendar. TextCalendar(calendar. SUNDAY) istrator, or sudo pip install calendar For Linux and macOS. EET SERED 2unch Puthon 3 and enter: import calendar to callup the module and it inherent Functions. Once PEPER) there are numerous functions within the Calendar ‘module that may be of interest to you when Forming your own code. For example, you can display the number of leap years between two specific years: sep. prmonth(2a19, 9) ‘Leaps=calendar.Leapdays(1900, 2019) print(leaps) The results 29, starting from 1904 onward, ‘Ble Edt shel Debug Options window Help Python 3.5.3 (default, Sep 27 2038, 17:75:39) {eee 6.3.0 20370536) on Tanwn Type Sconright; orests" or *BScona()* for nore Snforaation 53> Ieapescalendar: Leapdays(3900, 2010) 23> print easy aE oserYeSlendae Soe sapecalerantTontCaleiar (calendar. i904¥) 22 Seprpreonen 20, Roto ee se FTP) Vou conse that the days of September 2019 are displayed in a wal calendar fashion. Naturally you can change the 2019, 9 part ofthe second line to any year and ‘month youwant, a birthday For exemple (1973, 6) The First line configures TextCelendar to start its week en 2 Sunday; you can opt ‘You could even Fashion that particular example into 4 piece of working, user interactive Python code: import calendar print(s>s5s>5>5>Leqp Year Calculator Heor(t2)| ‘The Math Module can also be renamed as your Import, a with the other modules on offer within Bsr) Python, Thisoften saves time, but don't forget to make @ comment to show someone eise looking at your code what you've done: ‘import math as m m.trunc(123.45) # Truncate removes the fraction ‘Ee EO Shel Debup tions widows Help eee eee ate eer Marts atine eect ort 5 ett W488" oF ~License)" for more information, FETS) thouah it’s not common practise, tis possle to Inport Functions from @ madule and rename them. In this example, we're importing Floor From Math and renaming it to Falthough where lenathy code isin use, this process can quickly become confusing from math import floor as f £2) ieee Debits wrdows Hep Python $43 (Gataale. Oct 19 20Na, HATH T6EC'9.9-11 on Lim pe scents eredat or *icenseQ" for more sntormaion SIE Sane Soper" Floor af So tala) Importing al the Functions of the Math Module can Bisa be done by entering From math import * While certainly handy, thisis often frowned upan by the developer community 2s i takes up unnecessary resources and isn't an efficent way of coding, However, iFt works For you then go ahead, ‘le Eat Shel Rebup Qptens Windows Hap ten 3.4.7 (Seas, ocx 18201 TIT te, caytughes ergata or pe saree) 335 coop License() for more information. Incerestinaly, some Functions within the Math Bias Module are more accurate, orto be more precise are designed to return a mare accurate value, than others. For example: Akinyele) willretur the value of 0.999999989, whereas: ‘So eD, retums the value of 1.0 “License()" for were information. 4D ay (Using the math module (CII precise values: From math import exp, expmi exp(te-5) - 1 # value accurate to 11 places expmi(le-5) # result accurate to full precision Forfurther accuracy when it comes to numbers the exp and expt functions can be used to compute Ele Et She} Debug Options windows Help Rrra ee, Toldlatnn To Bn a PTTSEDD This evel of accuracy is really uit impressive, but quite niche for the most part, Probably the two ‘most used Functions are e and Pi, where es the numerical constant equal to 2.71828 {where the circumference of acrcieis diced by itscliameter ‘import math print(nath.e) print(math.pi), ‘le Et shal Oebug pins Windows He Python 3-47 CGetault, Sct 19 2018, 13:1771) [ecC'4.9:1] on Line Hype “copyright”, “credits” or ~License() for nore information Pats Sides BH TE? 10 angular conversion toconstants. Look up https://docs.python.ora/3/ Uibracy/math.htmU# For alist of available Math Module Functions. OS Module INTO THE SYSTEM. (One of the primary Features of the OS module is the ability to list, move, create, delete and otherwise interact with files, stored on the system, making it the perfect module For backup code. PSTD You canstart the OS module with some simple PEPER the windows outputs different asthat's the functions to see how i interacts with the operating current working directory of Python, as determined system environment that Python isrunning on, Fyou're using Linux by the systems as you might suspect, the os.getovd() Function s fr the Raspbeiry try this asking Python to retrieve the Current Working Directory. Linux users ome wtleeeametiog ang the sae las as ibe orpbary 2 howe=os..getand() ~ printChome) BEER The returned result from printing the variablehome ERM Yet another interesting element to the O5 module, isthe current user's home Folder on the system. ists ability to launch programs that are installed Inourexample that’s /nome/okit will be different cependingon _inthe hest system, For instance, Fyou wanted to launch the the user name you login as and the operating sytem you use Chromium browser rom within a Python program you canuse For example, Windows 10 willoutput: C\Program Fils (x86) the command Python3s.32 nas 5 browser=os. systen(*/usr/bin/chroniun-browser”) FETED The os.system0 function is whatallows interaction vith external programs: youcan even call up previous Python programs using this method. You will obviously reed to know the fll path and program filename for it ro work successfully, However, you can use the Following: import os os-system(‘start chrone “https Feed/music™*) Bis ia Ee 2" Step 5's example we used Windows, to show that the OS module works roughly the same across allplatfoxmsn that case, we opened YouTube's music Feed page, so itistherefore possible to open specific pages: import os os.systen(’ chromiun-browser “http:// ESRD Noten the previous steo’s example the use of single and double-quates, 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 in the same browser: ‘import os ‘o=(*chromium-browser “http://bdmpublications. con”) b=C‘chronrium-browser *http://im,google.co,uk"") os-system(a + b) ( OsModule Cl The ability to manipulate directories, or Folders if Scary} you prefer, is one f the OS madule’s best Features, For example, te create 3 new directory you can use: ‘inport os os mkdiir¢*NEW") This creates a new directory within the Current Working Directory, named according to the abject in the mkdir function, import os os. rename(*NEW", “OLD") Todelete them: ‘import os os. rndir¢*OLD") ‘You can also rename any directories you've created byentering: ‘Another madule that goes together with OSis shutil You ean use the Shut madule together with OS and time to create a time stamped backup directory, and copy files into ‘import os, shutil, time root_sre_din = r’/home/pi/Docunents’ root_dst_dir = '/home/pi/backup/? + time-asctimeC) for sre_dir, dirs, files in os.walkCroot_sre_dir’ dst_dir = srcdir.replace(root_src_dir, root_ dst_dir, 1) if not os.path.existsCdst_dir): os.makedirs(dst_dir) for file_ in files: sec file = os.path.jointsre_¢ dst_file = os.path.join(dst. if os.path.exists(dst_file): 0s. remove(dst_file) shutil.copy(sre_file, dst.dir) print(>sa>ssps>-Backup conpletecc File) and create a True/False while loop: import pygome ‘import pygane pygane.imit© From pygame.locals import * pygane.imit© ganenindow-pygane. display. set_modeC(820,600)) Pygane.display.set_caption(“Adventure Gane”) oo“ white running: for event in pygame.event.get(): ‘if event.type=QUIT: running-False ygame quit) STEI t's create a simple game ready window, and give itatitle: Prase- display set-caption(-saventore Gane") ‘gamenindow=pygame. di spLay.set_modeC(800,600)) rioningtree pygame.display.set_caption(“Adventure Game”) halle running: ‘or Then in pygane;cvent.get0 ‘You can see that after the fist nef entered youneed! to cick back trent ypersutt into the IDLE shel to centinue entering code; also, you can change Denenaiey {he tile of the window to anything you tke. l ( Pygame Module Cl BEER the Pyeame window stil won! dose don't worry, i's just @ discrepancy between the IDLE (whichis written vith Tkinter) and the Pygame module. IFyou run your code via the commandline it closes perfectiy wel FEED vou going toshitthe code around abit row aor ge Loner et running the main Bygame coce within while oop; spritel.png?) itmakes ieneater and easier Follow. Weve downloaded a craphic “—s def sprite(x,y): 9 use and we need tose ome parameters for pigame tetssondwe need Sree ‘gamewindow.bLitCima, (x,y)) ‘import. pygome sxuoness pygane-initQ y-(600"0.8) gamewindow LLCHhite) white running: sprite(x,y) ‘gameni ndow=pygane display. set_mode¢(800,600)) ee pygane. display.set_coption¢*Adventure Gane”) for event in pygame.event.get(): black=C0,@,0) “UF event.type=pygame. QUIT: iwhite=(255,255,255) running=False areal BSED (2% s quickly go through the code changes. We've downloaded image called spritet.png and allocated itto the defined two colours, black and white together variable img; and also defined a sprite function and the Blt function with theie respective RGB. colour values. Next we've loaded the vail allow us to eventually move the image. Tom ree -(90000.45) ‘opie foals spore * srtsoore.8) eda gaemindon.f11¢9hst0) renninget ron Speiteceny) Preme dizplay update() sete running menindompyaane. display set_node( (800.600) Preane- display setacoption(-Aaventure cane’) PiScteco.0r0) or event in pygame.event.get0 witees(285, 255.255) iT event. type=QutT “nespyeeee, image: 10ad(~/hane/p\/Oomnloads/spritet.pne") anminge” sis pramnes quit) Gmenindon bLitCing, (xy) neckinoiictocn GS Zz ) Using Modules) BESTT) ow we can change the code around again, tis time containing a movement option within the wile loop, and adding the variables needed to move the sprite around the screen import pygame from pygane.Locals import * pygane-init© running=True gonexindow-pygane. display. set_nodeC(800,600)) pygane.display.set_caption(“Adventure Gane”) black=(2,0,0) mhitten(255,255,255) ‘img-pygame image. load(“/home/pi/Downloads /spritel. png") def spritecx,y): ‘gamewindow.blitCima, (x,y)) x=(800*0.45) yoC620"0.8) xchange=2 ‘ingspeed-0 white running: for event in pygame.event.get(): if event.type=QUIT: running-False if event. type == pygame.KEYDONN: if event. key==pygame. K_LEFT: xchange=-5 elif event.key==pygame.K RIGHT: xchange=5 if event. type=-pygame. KEYUP: ‘if event key==pygame.K_LEFT or event key==pygame. K_RIGHT: xchange=0 x4 xchange ganenindow FLUCuhite) sprite(x,y) pygame. display update() pygane.quit© ESTEE Copy the code down and using the lft and right arrow keys on the keyboard you can move your sprite across the bottom of the screen. Now, it looks lke you have the makings ofa classic arcade 20 scroller in the works. DUNE) 20s cnt ce soes-vuess Crmmenodile CE BETTE vou connowimplementa few additions and utlise pygane. display. fip© some previous tutoriat code, The new elements aie clock. tick(60) the Subprocess madule, of whichene Function allows us olaunch a continue second Aythonscriptfrom thin another; andwe're going tocreatea break New ile called pygametit.py- pomemitee ‘import. pygame import time ‘import subprocess pygane init = screen = pygane.display.set_mode((800, 250) |sreme Dnt clock = pygane.time. Clock) font = pygame. font.Font(None, 25) Pygame..time.set_timer(pygane.USEREVENT, 209) | def text_generatorCtext): enn for letter in text ‘tmp += letter if letter Ie 6 *: yield tmp a lass Dynami cText (object): sai . def init__(self, font, text, pos, es eencres autoresetaFalse): self.done = False self.font = font self.text = text self_gen = text_generator(self. text) self.pos = pos ek st self.autoreset = autoreset +g Serta sons fre self. updateQ) def reset(self): self.gen = text_generator(self. text) self.done = False self update) def update(setf: if not self.done: try: self.rendered = self. font. ‘When yourun this code i will display a long, render(next(self..gen), True, (@, 128, @)) ALAR harow ane window withthe nt text except Stoplteration: scroling to the right. After a pause often secones, it then launches self.done = True the main garne Python script where you can move the warrior sprite time.sleep(10) ‘around, Overall the effects quite good but there's always room subprocess. Popenc*>python3 /home/pi/Docurents/ forimprovernent Python\ Code/pyganel.py 1”, shelt=True) def drow(self, screen): sscreen.blit(self.rendered, self.pos) text-CA long time ago, a barbarian strode fron the Frozen north. Sword in hand. ..") message = DynanicText(font, text, (65, 120), autoreset=True) while True: for event in pygame.event.get(): ‘if event.type — pygane.QUIT: break if event.type —= pygame.USEREVENT: message. update) else: ‘screen. fillCpygane..color.Color(*black”)) message.draw(screen) 4 @ ee Basic Animation LIGHTS, CAMERA, ACTION ‘The Tkinter module is an ideal starting point for learning animation within Python. Naturally, there are better custom modules out there, but T EERE ets make a bouncing bal animation. Fist, we will need to create a canvas (window) and the ball to animate: from tkinter import * import. time gui = TKO gui .geometry(“800x600") gui.titlec*Pt Animation") canvas = CanvasCgui , wvidth=800, hei ght=600,bg="white”) convas.pack() bolt = canvas.create_oval(S,5,60,60, fil ui -nainLoop() red") comer ofthe window. While thisis great it's not very animated. Let’sade the Following code: ons bums for x in range(0,100): canvas .rovecbalt1,a,b) gui -updateC) ‘time. sleep(.01) Sise pect bana = cones.createov{s,9,60,60, Tilleres") ay range(o.a00) ames ne a 0,0) pueanel| EineSeept 03) us.minoop() BNE soso ce sees- vues Bee nce vs nsratncanion rer does the job well enough to get a grasp on what's needed. Insert the new code between the ball BD covas-create.ovel(5,5,60,60, filL=" red?) tine and the gui. .mainLoop() line. Save it and Run, ‘You will iow see the ball move from the top left comer ofthe animation window, down tothe bottom right corner. You can alter the speed in which the ball traverses the window by altering the time. sleep(.01) line. Try (05). Bee Theconvas.moveCbat11,a,b) line isthe part thatmoves the ball From one comer tothe other; ‘obviously with both a and b equalling 5, We can change things around abit already, suchasthe size and colour ofthe ball with the line: bolt = canvas.crecte_oval(S,5,60,60, fll="red") end ‘we can change the values ofa and b to something ese ball = canvas.create oval(7,7,60,00, fill='red') ane bea for x in range(9, 100) Canvas, ove ball1, a,b) ‘gut.update() tine. sieep{ 05) Let's see if we can animate the ballso that it bounces around the window untilyou close the program. xa=5 yo= 10 while True: canvas.moveCbalLt xa, ya) pos=canvas..ccords¢batt1) if pos[3] >=600 or pos[1] <0: ya = -ya if pos[z] >=800 or pos[d] <0: gui update) time. sLeep¢.225) Baw Remove the code you entered in Ste 2 and insert the code from Step 5 in ts place; again, between the ball1 = canvas. create_oval(S,5,60,60, fill="red’) and the gut .mainLoopQ lines. Save the code and Run it as no If you've entered the code correctly, then you wil see the red bal bounce off the ecgesof the window until you close the program, ESSER the bouncing animation takes place within the While True loop. First, we have the values (of xa and xy before the loop, bath of 5 and 10. The pos=canvas.coords(ball1}) ine takes the value ofthe balls lecation in the window. When itreachestthe limits oF the vwinddow, 800 or 600, it will make the values ‘negative; moving the ball around the scr aNew Fileand entering import pygome from random import randrange MAX_STARS = 250 STAR_SPEED = 2 def init_stars¢screen): “"" Create the starfeld “"” global stars stars = 1 for i in range(MAX_STARS): #A stor is represented as o list with this format: [X,Y] star = Lrandrange(®, screen.get_width() - 1), randrange(@,screen.get_height() - 1)] stars oppend(star) def nove_and_draw_stars(screen): “°" Move and draw the stars “"™ global stars for star in stars: star[1] += STAR_SPEED if star[1] >= screen. get_height(): star[i] = 0 star[@] = randrenge(@,639) screen. set_ot(stor, (255,255,255)) ( Basic Animation Ci FE on athe Floning def naing) pygame. init© screen = pygane.display.set_node((640,480)) Pygane. di splay.set_caption(“Starfield Simulation”) Clock = pygane.time. Clock init_stars(screen) while True: # Lock the franerate at 50 FPS clock. tick(S2) # Handle events for event in pygane.event.get(): if event.type = pygane.QUIT: return screen.fl1C(0,0,0)) mmove_ond_draw_stars(screen) pygone. display.fipO ‘ase ° Tortovent sh pyasneevent.o8¢() scroon.£211((0,0,0)) Proave display #15 aa toa presentation? Using a combination of Pygameand Tkinter, your Python animations wil lock Fantastic @ ee 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. FSPTSEDD cts start by creating aset of basic mathematics ETSERD 0% y0u'e going totake the Function definitions functions. Multily anumber by two, three and ‘utof the program and intoa separate fe. square or raise a number to an exponent (powe). Create aNew File Highlight the Function definitions and choose Edit» Cut. Choose File Inthe IDLE and enter > New File and use Edie> Paste in the new window. Yau now have tarsetieeeeIoge: we seperate sane wt the uncon defies, the ther th ee the Function cals def timesthree(x): return x * 3 def square(x): et save return x * x coon deF ponertx,y): “tenant return x * y FETTER) Urcer the above code, enterfunctions tocalithe EWM iF you now try anc execute the basic_math.py code cove: again, the error ‘Name€rror: name ‘timestwo’ is not defined’ willbe displayed. Thisis due to the code no longer BririENCeLNestOC2)) having access tothe Function cefinitions, print Ceinesthree(3)) print CsquareC4)) Taeabok twet recon el ian SEE GHMERCSESDD PTS erty convening ane 3, aon ‘Save the program as basic_mathpy and execute ttogetthe resutts. ==)” STENT Smt Stn eenenn earl thenexy Sele vivo coo retention Sefton and desrte> snes Name ts ilnnah pyre ie fae labor thera base mathy ur ho dive hernfiathoy wine sathe be matin teen BENE) soso ce sees- vues From mininath import * Back tothe basic. math.py window: at the top of the code enter: This will mportthe Function definitions asa module. Press F5 to save and execute the pragram to see it inaction. ‘You can now use the code Further to make the programa litle more advancec,Fuly utilising the STEP 7 newly created module. Include some user interaction by creating a basic menu the user can choose from. print("Select operation. \n”) printc‘.Times by tno”) printC2.Times by Three”) print¢3.Souare”) print(“4.Power of") choice = inputC*\nEnter choice (1/2/3/4):") Now we can add the user input to get the number Bisa} the code will work on: num = intCinput("\nénter number: *)) This ill save the user-entered number asthe variable num, file Edt Format Bun Options windows Help Trom mininath import * print("select operation. \n") rine("1-Tines by tre") Fein Times by Three”) rine(=3-Square” Print("4.Poner of") choice = input("\nénter choice (1/2/3/4) punt = int(input("\nénter number: ")) ( Create Your Own Modules Finally, you can now create arance off statements sry to determine what to dowith the number and vslise the newly created Function definitions: if choice = ‘1": print (timestwoCnumt)) elif choice == ‘2": print (timesthree(nunt)) elif choice == °3": print (square nun) elif choice == ‘4": pumz = intCinput(“Enter second number: “)) printCpowerCnun, nun2)) el print¢“Invalid input”) oO ete estieaecram)) Nate that forthe lst available options, the Pawer (of choice, we've added.a second variable, num2. ‘This passes a second number through the function definition called power. Save and execute the program to see it in action, EA) index) Introductions ce C++ : “Measuring programming progress by lines of code is like measuring aircraft building progress by weight.” ~ Bill Gates (Co-founder of Microsoft) ELD vores vetntive vide Series-Voiume 3s C++ isan excellent, high-evel programming language that's used ina multitude of technologies. Everything From your favourite mobile app, console and PC game, to entire operating systems, are developed with C++ as the core, together with a collection of software development kits and custom libraries. C++ is the driving force behind most of what you use on a daily basis, which makes it a complex and extraordinarily powerful language to get to grips with, In this section, we look at how to install a C++ IDE and compiler on your computer. 88 Why CH? 90 Equipment You Will Need 92 Howto Set Up C++ in Windows 94 Howto Set Up C++ ona Mac 96 Howto Set Up C++ in Linux Other C++ IDEs to Install z= Introduction to C++) ere Rg ar tuesd cst cuticle mad cule tere ee) Re OU ke kena cce m ACLS St oman ew eral oursa regen eel cuct eee) Ponertieeklnteceranetl Cleon C EVERYTHING 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 back to 1979, thestart of the golden era of hame computing, Crs, orrather Cwith Clases, was the brainchild of Danish computer scientist Bjarne Stroustrup while working on his PhO thesis. Stroustrup plan was to further the original Clanguage, which was widely used since the early seventies, C++ pravad to be popular amang the developers of the ‘80s, since it was a much easier environment to get to grips with and ‘more importantly, it was 99% compatible with the original C language. This meant thatit could be used beyond the mainstream GS (Cet code is much faster than that of Python. ‘computing labs anc by regular people who dict have access to the ‘mainframes and targe computing data centres. CCre'simpactin the digital world is immense. Many of the programs, applications, games and even operating systems are coded using #4. For example, al of Adabe's major applications, such as Photoshop, InDesign and so on, are developed in C++. You wil find that the browser you surf the internet with is written in Ct, 25 ‘well as Windows 10, Microsoft Office and the backbone to Google's search engine. Apple's macOS is written largely in C+¥ (with some 1 #include 2 using namespace std; 3 | void main() 4 |K(char ch; 5 cout<<"Enter a charater to check it is vowel or not"; 6 cin>>ch y switch (ch) a jo [ Qo case'a’: case'A': 10 cout< When you click Next, the install begins; when i's finished a ply File, This creates anew, blank window for you to type in ‘notfication pops up asking you F you want start CodeBlocks now, soclick Yes. — ee SSS = ae or = = =m | rats dere Viana vpOna Raman Psa Waar MeL. @ Coie booe BETTER The frst time CodeBlocks toads it runs an BETTER) the new windows, enter the Following autodetect for any C++ compilers you may already have installed on your system, Ifyou dont have ary, clickonthe ——_#Finelude" Save as and save the codewitha Informing you that Code:Blocksis currently not {op extension helloworld cpp, For example the default application for C++ files. You have two options, to leave CodeBlocks changes the view to colour code according to C++ everything as its or allow CodeBlocks to associate all C+ file standarés. To execute the code, click on the Build and Run icon types. Again, we would recommend you apt for the last choice, to _along the top of the screen. It's a green play icon together with @ associate Code: Blocks with every supported file type. yellow cog, vw : BR) i oseciontocss ) How to Set Up C++ on a Mac To start C++ coding ona Mac you need to install Apple's Xcode. This is a free, Full featured IDE that’s designed to create native Apple apps. However, it can also be used eoXe kk Ooch SIN XCODE Apple's Xcode is primarily designed for users to develop apps For macOS, iOS, tvOS and watchOS applications in Swift or Objective-C, but you can use it for C++ too. Start by opening the App Store on your Mac, Apple When you'r ready, click on the Get button which ‘Menus> App Store. n the Search box enter Xcode and then turns into tnstall App’ Enter your Apple 1 press Return, There willbe many suggestions filing the App Store and Xcode begins to downlosd and instal. tmaytake some time window but isthe First option, Xcade, that you need toclickon. depending on the speed of your internet connection gecacee ne — en ena ae: “Take @ moment to browse through the app's ‘when the installation is complete, click on the Open Information, including the compatibility to ensure button to launch Xcode, Clik Agree to the licence you have the correct version of macOS, Xcode requires macOS teimsand enter your password to allow Xcode to make changes 10.12. orlaterto instal and work tothe system, When you've done that, Xcode beginsto install, qumsmaen 20titional components. Xcodd gg BED) 22 sont cee soies-vuess FEPPID with everything now installed, including the ‘additional components, Xcade launches, displaying the version number along with three choices and any recent projects that you've worked on; although fora fresh instal, this shows bani FETTER tert by clicking on Create New Xcode Project this ‘opens template window From which to choose the platform you're developing code for. Click the macOS ab, then the Command Line Tool eption and finally, Next to continue ESTED [ilinthe various elds but ensure that the Language option atthe bottom i set to Ce. Simply chooseit from the drap-down ist. When you've filled in the fields, and made sure that C+ isthe chasen language, click on the Newt button to continue, The next step asks where to create ait Repository forall your future code, Choose a location on your Mac, or a network location, and click the Create button. When you've done all that, you can star to code, The left-hand pane 5 7 Ayy first: C++ program Conse std::cout << “Hello World!\n"; Flnctude BE 22s intr cceseies-vuess When you've entered your code, click File > Save As ‘and choose a folder where you want to save your program. Name the file as heloworld.cpp, or any ether name just as long asit has cpp as the extension, Click Save toc FETTER The frst thing you can see isthat xed has automatically recognised ths asa C++ file, since the File extension is now set to.¢pp. The colour coding ig present in the code and if you open up the file manager you can also see that the file'sicon has C+ stamped ont ESTED With your code now saved, drop into the Terminal again, You need to navigate to the location of the C++ file you've just saved. Our example is in the Document Folder, so we can navigate tot by entering: ed) Documents Remember, the Linux Terminal s case sensitive, so any capitals must be entered correctly, BRTSEDD fore you can execute the C++ file you need to compile, In Linux it's common to use a+, an open source C++ compiler and as you're now inthe same Folder as the ‘opto the Terminal, enter: GEE HETLOWOFLM. ep anct ss return, davidemis Fle Eét View Search Terminal Help fiavidenint-nate eT) BSED There willbe a brief pause as the code is compiled byot+ and providing there are no mistakes or a and prompt. The compiling of the code has created a new file. f you enter US into the Terminal you can see that alongside your C++ file is aout. File edt View Search Terminal Help Eeeeernrecrtsy Poueat ret reeerrtes ESET DD The 2.cutfileisthe compiled C++ code. Torun the code enter: {Za0ut and press Return. The words Hello World appears an thescreen. However, aout int very friendly To name it something else post-compiling, you can recompile with: gk helloworld.epp:-0:heLLoworld. This creates an cutpu! Fle called hellowarld which can be run with: ZheLLoworta, File Edit View Search Terminal Help Cees Covet reins Seer Fle Et Yew Search Terminal He Other C++ IDEs to Install IFyou 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 Deft nein -e-1-d) CNA Colm ELEM EDT AUS Colo DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but find the one that works best for you. PETES ines nso ctor ses Linux and Mac. Head over to www.eclipse.ora/downloads/ to download the latest version. f you're stuc,clickthe Need Help tink For more information, See ‘The GNAT Programming Studi (GPS)is a powerful nd intuitive IDE that supports testing, debugging and code analysis. The Community Editions Free, whereas tre Proversion costs; however, the Community Edition isaveilable For \Windows, Mac, Linux and even the Raspberry Pi, You can find itt ‘wurwadacore.com/download. BE) 22st ccesoies- vues CODE. Linux and mac. |t's lightweight, uncomplicated and extremely download and instal at www.codelite.ora/, ‘Another popular choice is NetBeans. This isanother excellent DE that’s packed with Features and a pleasure to use. NetBeans DE includes project based templates For C++ that give you the ability to build applications with ‘dynamic and static libraries. Find out more at www.netbeans.ora/ Features/epp/index.html SECT ORD Microsoft's Visual Studio sa mammoth C++ IDE thatallows you to create applications For Windows, Android, iOS and the web. The Community version is free to download and instal but the other versions allow a Free tral period. Goto wwwvisualstudie.comy to see what it can do for you. een Tis«ross platform IE's desioned to create C++ applications for desktop and mobile environments It comes with a cade eaitor and integrated tools for testing and debugging, aswell as deploying to you chosen platform. t's not Free but there isa trial period on offer before requiring purchasing: wwwrat.io/at-featuresclibraries-apis-tools- Bloodshed Dev C++, despite its colourful name, is an older IDE that is for Windows systems onl However, many users praise its clean interface and uncomplicated way of coding and compiling. Although there's not been much Updating For some time, it's certainly one to considerif you want. something diferent: ynwwnbloodshed.net/devepp.html, Other C++ IDEs to Install ( cH ‘The Anjuta DevStudio is a Linuxenly IDE that ANJUTA Features some of the more advanced features you ‘would normally Find in a paid software development studio. There's GUI designer, source editor, app wizard, interactive debugger and ‘much more, Go to wwnw.aniuta,ara/ for more information. ‘This excellent IDE allows developers towrte C++ code for desktop and ‘web applications across all the major platforms, There's an advanced text editor, integrated debugger and a configurable workbench to help you create your code. It's avalabe for Windows, Macand Linux {ands free to download and use: www.monodevelop.com/. jy Ultimates sa cross platform Cr+ IDE that boats 2 rapid development of code through the smartand aggressive Use of C++. For the novice, isa beast ofan IDE but behind its complexity is a beauty that would make a developer's knees go ‘wobbly. Find out more at www.ultimatepp.ora/index.html, er: Fundamentals ( G++ Fundamentals Within this section, you will begin to understand the structure of C++ code, and how you can compile and execute that code. These are the core Fundamentals of C++, which teach you the basics such as using comments, variables, data types and strings, along with how to use C++ mathematics. These are the building blocks of aC++ program. With them, you will be able to form your own code, produce an output tothe screen, and store and retrieve data. 102 _YourFirst C++ Program 104 Structure of a C++ Program 106 Compile and Execute 108 Using Comments 110 Variables 112 Data Types 114 Strings 116 Cr+ Maths , Your First C++ Program eM ae eae to cera aaa ell working exclusively in Windows and Code::Blocks from here on. Let’s begin by writing your first C++ program and taking the first small step into a larger coding world. HELLO, WORLD! It’s traditional in programming for the first code to be entered to output the words ‘Hello, World!’ to the screen. Interestingly, this dates back to 1968 using a language called 8CPL. FETTER mentioned, we're using Windows 10 andthe PEPTTED 2 tne momentit doesn't look ice much, and latest version of CodeBlocks forthe rest of the C++ itmakes even less sense, butwe'llget to that ode in this book. Begin by launching Code:.Blocks. When open, click in due course. Now click on File > Save Files, Create of find 3 ‘on Fle > New >Empty File or press CrleShifteNon the keyboard, _suitable location on your hard drive and in the Fle Name box, cll ithellowarid. line and re-enter it. You can see the auto select boxes appearing include BET 22 scot cceseies- vues BETTER) uto-selection of commands is extremely handy and Cuts out potential mistyping. Press Return to.get to line 3, then enter: int maing) Notes there's no space between the brackets. BED nthe nexcline below int maind, enter a cury bracket: a This can be done by pressing Shiftand the key to the right of Pon an English UK keyboard layout. ~is dias hie peer r es BETTER Notice that Code:lockshas automaticalycreated 2 corresponding closing curly bracket a couple of lines betow, linking the pat, as well asa slight indent. Ths is due to the structure of C++ andit’s where the meat of the code is entered, Now enter: iy first’ Cee program Your First C++ Program Cl NNoteagain the colour coding change. Press Return at Suse} the end ofthe previous steps line, and then enter: std::cout << “Hello, world!\n"; Just. as before, CodeBlocks auto-completes the code you're entering, including placing a cosing speech markas soon as you enter the Fst. Oon'c forget the semicolon atthe end of the ine this sone ofthe most important elements toa C++ program and we'l tell you why in the next section. For now, move the cursor down to the closing curly bracket and press Return. That's allyou need to do for the moment. It may SUEY ‘not look terribly amazing but C++ is best absorbed insmal chunks. Don execute thecode athe moment asouneed tolookat how» C= progam ls sutured fist then youcan bul and unthe code. For now cickon Save, the snl lopy cco, BE) crconenas) Structure of a C++ Program C++ has a very defined structure and way of doing things. Miss something out, even as small as a semicolon, and your entire program will fail to be compiled and executed. Many a researc) net geese vecagtaet cs #INCLUDE Learning the basics of programming, you begin to understand the structure of a program. The commands may be different From one language to the next, but you will start to see how the code works. aH #INCLUDE a a, The structure of a C++ program si C++ wasinvented by Danish Is quite precise. Every C++ code Hnolnie student Bjame Stroustrup in begins with acivective:tinelude 1979, aga part ois PhO. ‘© The directive instructs the thesis intially C++ wascalled CF pre-processor to include + ‘with Classes, whichadded section ofthe standard C++ Features to thealready popular : code. Far example:#include programming language, -lostream> includes the ‘while making itamore jostream header to support Lserfriencly environment input/output operations. through anew structure Bjame Stroustrup, inventor oF Crs. INT MAIN() Starthere | *helloworld.cpp intmaind intatesthe declaration of a function, whieh isa group of code statements Under the name fair. All ++ code begins atthe main function, regardless of where it actually les within the code. #include int main() 2 3 4 5 6 BRACES #include ‘The open brace (curly brackets) is something that you may not have come across before, int main() especially Fyoure usedto Python, The Be ‘open brace indicates the beginning ofthe main Function and contains allthe code chat belongs te that Function, ET) 22s cin cceseies- vues L, COMMENTS. Lines that begin with a double slash are comments. This means they won't be executed in the cade and are ignored by the compiler Comments are designed tohelp you, or another programmer looking at your code, explain what's going on. There are two types (of comment: # covers multiple line comments, //asingleline. Lines that begin with a double slash are comments, This meansthey won't be executedin the code and ate ignored by the compiler. Comments are designed tohelp you, or anather programmer looking at your code, explain what's cing on. There are two types of comment: covers ‘multiple line comments, //@ single ine Hicloge lewteem™ lac L STD While std stands for someting quite different, in ++ itmeans Standard. l's part of the Standard Namespace in C++, which covers a numberof different statements and commands, You can leave the std: part out ofthe code butit mus be declared at the start with: Using namespace std; not both. For example: #include using namespace std;_ COUT In this example we're using cout, which is partof the Standard Namespace, hence why it's there, as you're asking Cr+to use itfrom that particular namespace. Cout means Character QUTput, which clsplays, or prints, something to the screen. iFwe leave std out we have to declare tat the start of che code, as mentioned previously. Finclude using namespace std; int main() cout C Structure of a C++ Program Ci << ‘The two chevrons used here ae insertion operators. This means that whatever Follows the chevrons fsto be inserted into the std:cout statement. In this case they're the words ‘Hello, world, which are to be displayed on the screen when you compile and execute the code. OUTPUTS Leading on, the “Hello, world” part is what we want to appearon the screen when the code is executed. You can enter whatever you like, as long a5’ inside the quotation marks. The brackets aren't ‘needed butsome compilersinsist on them. The \n part indicates a ‘newline isto beinserted //My first C++ program cout << “Hello, world!\n” ; AND} Finally you can see that lines within a function cade block (except comments) end with 2 semicolon. This marks the end ofthe statement and ll statements in C++ must have one atthe end or the compiler Falls to bulld the code. The very lat line has the closing brace to indicate the end of the main Function. Finclude ‘using nanespace sta: ant mazn() gout << "Helle, worla!\n wewkinoitictocn Cy BE) Fencamentas) Compile and Execute ech a eeer ee cen hn Cmca uetere et ait es structure of one. Let's actually get things moving and compile and execute, or run if you prefer, the program and see how it look: 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 it’s done. FETE open Code:Blocks, if you havent already, and FPIREM) start by clicking on the Buldicon, the yellow cog load up the previously saved Hella Wor'd code you ‘Atthis point, your cade has now been run through created, Ensure that there are no visible errors, such as missing the CodeBlocks compiler and checked for any errors. You can see semicolons atthe end ofthe std:cout lin. ‘the results ofthe Build by looking to the bottom window pane. Any - messages regarding the quality ofthe code are displayed here, SA SSeS Gaaie sed Ze int main() At PROUE ED 20s Dette cute Seves-Voiume 35 Pressing ary key in the command ine box closest returning you to CodexBlocks. Le's alter the code tly. Under the tlincluce line, enter using namespace std; Then, delete the std part of the Cout ine ike so cout << “Hello, world\n”; ESTEE 1° order toapply the new changes tothe code, you need to re-compile, build, and run it again. This time, however, you can simply click ie Bu 1nd green play button. JyRun con, the combined yellow c 1e previous pages, you using namespace ste at the beginning of the code, We could have easily licked the Buile/Runicon to begin with but it’s worth going through the available options. You can also see that by building and running, the file has been Just as we mentioned in don't need to have std:coutif you already declare conpieaniteate CR reate ad error inthe code, Remove the he cout tne, soit reads cout << “Hello, world! \n” Starthere %| helloworld.cpp 7 finclude using namespace std; int StartLives inenainO { startLives = StartLives = 1; cout << StartLives; using nanespace std; auto pi = 3.141593; int main { double area, radius = 1.5; area = pi * radius * radius; cout << area; AED using namespace std; double PI = 3.141592653589793238463; int maine) £ cout << PI; ¥ ee 7 2 | using namespace sta} 3 | double Pr ~ 3.14159265350979929046; 3 Sant masn() . > cout << Pr: ° $ 10 Bl Cer vhDocumentCe~\DaaTypenene Build andrun the code and as you can see the outputs only 3.14159, representing cout's limitations inthis example. ‘You can alter the code inclucing the aforementioned cout precision Function for greater accuracy. Take precision allthe way up to 22 decimal places, with the following code include using nanespace std; double PI = 3.141592653589793238463; int naing { cout.precision(22); cout << PIs 3 double Again, build and run the code; as you can see from the command line window, the number represented by the variable Pliscifferen -e number youve told ise in the variable. The output jsthe value of Plas 3.14 589793115998, with the rhumbers going avary From the fifteenth decimal place Calculator =e Scientific D 15.142857142857142857142857142857 Dec HYP FE MoM Ms ” sin cos. tan ma 1o* og Exp Mod +) [le © ON WO This is mainly due sion from binary inthe compile ‘and that the IEEE 754 double precision standard occupie: (oF data, of which 52-bits are dedicated to the significant (the significant digits in a Floating-point number) and roughly 3.5bits roiding the arrive at 15.142857 recurring, whi alues 0 to. Fyou divide 53 by 3.5, then you ‘Sedigits of precision, Tobe honest, if you're creat istobe accurateto code that nee more than fifteen decimal places, then you wouldnt be using C++ youwould use some scientific specific language with Cs asthe connective tissue between the two languages your own data types, using an alia #include using namespace std; int main © t ¥ 4B a/GRfor so ome [le 5 | mse] iol 2] Sd + b> To create a string you use the char Function, Open a new C++ file and begin with the usual header BEPTSE DD |< 259 to confuses string with an array. Here's an using namespace stds intinain'© { chor grect[8} = {:W", ‘27, “17, ‘c?, ‘07, "m” Bud and run the code, and 'Welcome' appears ‘on the seen, while tisis perfectly Fine it's nota string. A string is@ class, which defines objects that can be represented asa stream of characters and doesn't need to be {esminated ike an array, The code can therefore be represented as: include using navespace std; int main © { string greet = “Welcome”; cout << greet << "\n"; } ETI) 22 scot cceseies- vues There are also many different operations that y ‘an apply with the string Function, For instance, to get length of astri include using namespace std; int main O t string greet = string greet2 = string greet3 = Hello”; + world!”; greet + greet2; cout << greet << “\n"; 100, Build and run the code to see BETTE DD -0st2s you might expect, you can mixinan int and store something to do with the string, Inthis , we created int length, which stores the result of string #include using nanespace std; int main © { ‘int Length; string greeti = “Hello”; string greet2 =“, world!”; string greet3 = greet + greet2; Length = greet3:sizec); ‘cout <<'“The Length of the conbined strings + << Length << “\n"; BED Using the avalable operations that come with the string Function, you can manipulte the contents ofa string, For example Oremove characters from a string you could u include using nanespace std; int main © { string stra (“Here is @ long sentence in a string”); cout << stra << ‘Nn’ strg-erase (10,5); cout << strg << ‘\n’s strg-erese Cstrg.begin()+8); cout << strg << *\n strg.erase Cstra-begin()+9, strg.end()-9); cout << strg << ‘Nn’; es worth spending so he number ng. Occasionally, it 3, so practice makes perf de. ne time playing around with which are the character positions sn be hit and miss whether rake @ look at the screenshot the result of th sii 5 &é ES C++ Maths SM uure cea utes sem atrscrthides built-in scope for some quite intense maths. C++ has a lot to offer someone who's Tony) tunnlelare Maal dal-uar-le (er Muncere CHa oki m eee MeL eee meee relatively simple. 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. Co's matheraial operations flowthe ‘llkaton and ahision can be applied as sch Su? same pattems as those taught in school, in that es #include rmuttiplication and division take precedence over addition and ane " subtraction, You can alter that though. For now, create anew file mane int main ©. #include { Using nanespace stds int main © float numbers = 100; numbers = numbers * 10; // This multiplies 100 ; by 10 float numbers = 100; cout Using namespace sta; intnain'O { ¥ % number: FER tert by getting the square root #include #include using namespace std; int main © { float number = 134; cout << “The square root of “<< nunber << is: “<< sqrtCnumber) << “\n"; FETED Calculating powers of numt #include include using nanespace std; can be done with int main © { float nunber = 12; ‘cout << nunber_<< * to the poner of 2 is" <« PonCnunber, 2) << “\n’ ‘cout << number << " to the poner of 3 is" << Pon(nunber, 3) << “\n"; cout << number << “ to the poner of .O8 is ‘<< ponCnumber, 0.8) << “\n”; PEPIIIDD sce we created Fat called number with the flue of 12, and the powivariable, power) is where the calculation happens. Of course, you ‘oots without using variables. Fo First cout ample, pow (12 tt value of Fiisal brary. tt can be called up with t nter cout <= M_PLinto the code and you get 3,1 seitto calculate: o stored in the cmath header M_Prfunction. 95 oF you can #include include using namespace std; int main © demrena teracenrmretnEE a area = MPI * radius * radius; cout << area << “\n"; } “The best programs are written so that computing machines can perform them quickly, and so that human beings can understand them clearly.” ~ Donald E. Knuth (Computer scientist, mathematician and author) crinmiouot CX There's a satisfying Feeling when you program code that asks the user for input, then uses that input to produce something that the user can see. Even if it’s simply asking for someone's name, and displaying a personal welcome message, it's a big leap forward. User interaction, character literals, defining constants, and file input and ‘output are all covered in the following pai pages. All of which will help you to better understand how a C++ program works. 120 User interaction 122 Character Literals 124 Defining Constants File Input/Output User Interaction P Dire enna hice sen ie cteretileN esi um oels irate ecdeoh (ol MMe Merle on keke area taught aspects of any language and with it you're able to do Tarren eC MeAC TET el klar NAT oa ( Fe) HELLO, DAVE You have already used cout, the standard output stream, throughout our code, Now you're going to be using cin, the standard Input stream, to prompt a user response. Anything that you want the user to input into the program needs to be stored somewhere in the system memory, soit can be retrieved and used, Therefore, any Input must frst be declared asa variable, so t's ready to be used by te user. Start by creating blank C+ ile with headers, int main () Be “The data type of the variable must also match the type of input you want from the user. Far example, ise to.ask user thelrage, you would use an integer lke this winelude using namespace std; int main © t ‘int ages cout << “what iS your’ag cin >> age; cout <<"\nYou are“ <> nave; cout << “\nHello, << name <<“. I hope you’re well today?\n"; : seis aS Fier 5] mrmenconce = weno Besa The principal works the same asthe previous code. ‘The user'sinput, their name, is stored in a string, bbeceuseit contains multiple characters, and retrieved in the second cout lie, As long as the variable ‘name’ doesn't change, then you canrecallit wherever you like in your code, BTS) You cen chain input requests to the user butjust ‘make sure you have a valid variable to store th input to begin with, Let's assume you want the user to enter two whole numbers #include using namespace std int main © { ‘int num, nani cout << “Enter tno whole numbers“ ein >> num >> num; ‘cout << you entered * << uml <¢ “and << un << “\n"; PED kcwise, inputted data can be manioulated once you have it storedin a variable. For instance, ask the ser Fortwo numbers and co same maths an them: #inelude > numd >> nun; wns cout << numd ce 4“ using nanespace std; int main © string mystr; cout << “Enter @ sentence: \n"; getlineCcin, mystr); cout << “Your sentence is: “ << mystrisize@ << characters: ong. \n"; ¥ BETERE DD Suildand execute the code, then entera sentence with spaces. When you'e done the code reads the wumber of characters. F you remove the getline with cin >> myst and try again, the result displays the numb characters up tothe firs space, PRPS etline is usually command that new C++ [pragrammars forget to includ. The terminating vihite space is annoying when you cant figure out why your code isn't working, In short, t's best to use getine(cin, variable) in Futures #include using namespace std; int main © { string nave; cout << “Enter your full name: \n"; getlineCcin, nate); cout << “\nlello, * << nome << *\n"; } z= C++ Input/Output) Character Literals Kerem M ei Ue- La ole) (Lem |o) (CANT Lem ene Me Ta eA ILL IS throughout the code. However, a character literal is defined by a backslash, such as the \n you've been using at the end of a cout statement to signify a new line. ESCAPE SEQUENCE When used in something like a cout statement, character literals are also called escape sequence codes. They allow you to Insert a quote, an alert, new line and much more. PEPTED Ccate anew Cis Fleand enter the relevant headers: IBM tr you wanted toinsert speech quotes inside a cout statement, you would have to use a backslash asit #include already uses quotes: using namespace std; #include int main © using namespace std; t int main © { } cout << “Hello, user. This is how to use _ _, Vquotes\”."5 : ‘using namespace tdi PEPER Vou ve already experienced the character literal BSAA there's even a character literal that can tigger an placing a new line wherever i's called. The line: cout alarm. in Windows 19, t's the notification sound <<"Hello\n" <<"'m a C+#\n" << “Program\n’; outputs three lines that chimes when you use \a Try this code, and turn up your sound. of text, each starting after the last, aaa using namespace std; “ap Spd ehlo — int main £ : cout << “ALARM! \o"; : Riw s|><| aa) QEd «hE Yinclase sos en eee A HANDY CHART There are numerous character literals, or escape sequence codes, to choo: you to havea handy chart available, For those times when you need to ins ESCAPE SEQUENCE CODE CHARACTER Pe From. We therefore thought it would be good for ‘acode. Pro Double Quote (Speech Marks) Question Mark Reon Backspace | ey fen ono oor een fiers ree) ua) UNICODE CHARACTERS (UTF-8) rears bya In #include using namespace std; include inca using namespace std; define LENGTH 50 define WIDTH 40 define HEIGHT 60 int main © t ‘cout <« “Length ist << LENGTH << *\n"; cout using namespace std; define LENGTH 50 define WIDTH 40 define HEIGHT 60 define NEWLINE *\n” int main © { cout << “Length is: * << LENGTH << NEWLINE; cout << “Width is: “ << WIDTH << NENLINE; cout << “Height is: “ << HEIGHT << NEWLINES } FETED Te code, when built and executed, does exactly the seme as before, using the new, constant NEWLINE to Insert anewdine in the cout statement. incidentally creating a newline constantsnt a good idea unless you're making it smaller than\nor even the endl command. PPT OeFining 2 constant isa good way of intialising your base values at the start of your code. Yau can define that your game has three lives, or even the value of Pl without having tocall up the C++ math Ubrary #include using nanespace std; int main { ‘const int LENGTH = 50; const int WIDTH = 40; const char NEWLINE Nn int area area = LENGTH * WIDTHS cout << “Area is: “ << area << NEWLINE; BE) rowsousst ) File Input/Output MUN laler-I Ke Mone BeeN e o eet AUT N aA a) and cout input and output functionality. However, to be able to read and write from a file you need to utilise another C++ LUT -TnV ke] Celera FSTREAMS There are two main data types within the Fstream library that are used to open a file, read from it and write to it, ofstream and lfstream, Here's how they work. PRISED The first tackisto create anewC++ fileand along — EAMEM weve included comments inthe screenshat of step ‘with the usual headers you need to include the new 2 tohelp you understand the process. Yeu created fstream header string called name, to store the user's inputted name. You also created atext fle called nametxt (with the ofstream newflle and ‘newfile-open lines), asked the user for their name and stored it and then written the data to the ie #include include #include string it ‘ifstream newfie (“name.txt”); ‘cout << “Contents of the fil “<< endl using namespace std; getline(newfile, line); pers cout << line << endl aR newile. closeC); t string names ofstream nenfile; newfie open(“nane txt”) cout << “Enter your" nana: <<" endL; getline¢cin, nave); nenfile << name << endl; newfie; closeQ3 KEES EE eevevsowd } ET) 205 scot cca seies- vues The code above is creat for opening afile with one ‘or two lines but what i there are multiple lines? Here we opened a text file ofthe poam Cimmeria, by Robert E Howard string Line; ifstreom nenfile (Mc:\\users\\david\ Document s\\Cirmeria. txt”); cout << “Cinmeria, by Robert E Honard: \n” << endl; while Cgetline(newfile, Tine) cout << Line << endl; newfile:close(); =siem vee ded ule, arenes tobe read fromthe fente eosgetines tie also see that the location of the textile atkt ist in the same folder asthe C++ ted the first nare.tat fle, it was written to the same folder where the code was lacated: hiss done by default Tospecfy another folder, you need to use doubles per the character Urals fascopi oeaquuenew Gods, BETTE MD -ustas you might expect, anything you like toa file, For reading either in Notepad or via the console th The re integers; so when you're using a data type other than a string, use the standard in, BSED enone een coe can ave a user's name, age, phone number value of Piand various mat Fico CE the C+» code sstring name; ‘int ages ofstrean newfl nnewfile. open(“nane.. txt” cout << “Enter your nane: “ << endl; getlineCcin, name); newfile << name << endl; ‘cout << “\nlow old are you! cin >> age; << endl; nenfile << age << endl; ewfile,close(); The code from step 8 differs again, but only where i comes to adding the age integer, Notice that ‘in>> age, instead ofthe previous getlne(cin, variable). 1 for this that the getline Function handles strings, not Maybe even t matical elements, “The most important property of a program is whether it accomplishes the intention of its user.” — CAR. Hoare (Computer scientist, developer of Quicksort) iz DMs Definitve Guide Seves-Volume 35 nd Decision Making Loops and repetition are one of the most important factors of any programming language. Good use of a loop will create a program that does exactly what you want itto, and delivers the desired outcome without issues or errors. Without loops and decision-making events within the code, your program will never be able to offer the user any choice. It's this understanding of choice that elevates your skills as a programmer, and makes for much better code. hile Loop For Loop. Do... While L z= Loops and Decision Making While Loop ‘ Cite ne eee eu art ese urged MCE Rene on Cancun eile it initialises itself by testing the condition of the loop and the Ren cierto osem il oy TRUE OR FALSE? While loops are one of the most popular Form of C++ code looping. They repeatedly run the code contained within the loop while the condition is true. Once it proves false, the code continues as normal. ECG Cee whatyouvedonesofarand createanewcs+ EER First you file. there's any extra headers atthe need to ‘moment, 0 add the standard headers as per usval: rea condition, so use @ varleble called num and give ithe value 1, Now create the wile loop, stating that int main © aslong as numis ess than #include > word) 4 cout << word << endl; 7 return 0; whieiooo CX You can further expand the code to enable each word ofthe poem to appear every second, To do you need to pullin anew library, . This isa Windows ibcary and within t you ean use the SleenQ Function include #include #incLude > word) { cout << word << endl; Sleep(1000); ? return 0; ? ‘Sleep() works in miliseconds, so Sleep( 1000) ‘one second, Sleep(10000) ston seconds and so Combining the sleep Function (along with the header itneeds) anda while loop enables you to come up withsome interesting countdown code. include include t cout << a << endl: Steep(1000); cout << “\nBlast return 0; OFFI" << ends don't Forget to include windows, the Sleep seethe numbers 10to nerements, until itreaches zero and bias include alot more content into er input: op, including some v int ijn, fact= 25 cout << “Enter a whole number: *; cin 55 ny for Com dpi ny Hid foct *= i; Y coutee “\nFactorial of “<< > m5 for Cink t= 15 te 125 44494 cout ence" x Sect ce nd; 2 return’ 0; geri o whatever number youwant,cispl one). anintese' 2 the data type within a For loop do ss valid it works. (float t= )0200;° 1 < 1.005 += 0-01) cout << 1 <<'end rn 5 133 z= Loops and Decision Making Do... While Loop Ado... while loop differs slightly from that of a for or even a while loop. Both for and while set and examine the state of the condition at the start of the loop, or the top of the loop if you prefer. However, a do... while loop, is similar to a while loop but instead checks the condition at the bottom of the loop. DO LOOPS The good thing about a do... while loop is that it’s guaranteed to run through at least once. Its structure is: do, Followed by statements, while condition is true, This is how it works. con ere'salook atthe structure ofa do... while a sue ‘int main © t ) : int num = 1; do 4 code continues ‘ cout’ << “Number: “<< num << endl; continues until the user enters a certain character. num = pum +1; + while: Cnum < 30; return 0; BERD 2014 Dente uid Serie-Volu (Go..wte.cos CE zero, then the laop is terminated, iFnot then it continues i indefinitely. When the user finaly enters zero, the value of sum, ae the total value of allthe user's input is displayed. The loop, and cout << “#** Program to execute a Do... tbc vo Ht reverses lpeayed Ine While Loop continuously ****" is are assigned, number and sum, both tee ta te here isa brie setof instructions For the user. BETRET BD the mein advantage of using ad isbecause i's an exiscondltion loop: whereas 2 Therefore, if your cade requires a BED) the do... while loop inthis instance asks the user to input a number, which you as varlable, number. friable, sum, which rsa new value vihile Loop is an ent Sp that the numberof lives in ag igned tothe Float ntrol Loo cand Floating umber every time the he calculation step uses the do { cont < " number 135 Zz 0 ) Loops and Decision Making IF Statement De eee ee Ree eee eae euul cutee omen eal Peete enn) Slr iienitescem aren cr) junction in the code, where IF one condition is true, do this; or IF it's false, do that. IF ONLY {Fuses a Boolean expression within its statement. IFthe Boolean expression is true, the code within the statement is executed. IF not, then the code after the statement is executed instead. ESTEE Fist. create a new C++ file and enter the relevant standard headers, 2s usual include ‘using namespace std; using namespace stds int main () int main © ‘ { z Eee is best explained when you use anumber- PED What's going on here? To beain aninteger called i ‘The f statement comes ext, and inthis case we've instructed the ee code that ifthe condition, the value, of rum ilessthan 1, thenthe code withinthe braces should be executed. if C num < 30) { = cout <<"The nunber'is less than'30z" <<) me The nenter is leas then 30,7 ¢ end; eee sssveessssssssusesennenennenesseesnsss - BRTEP DD The second cout statement displays the current ¥ easy to see how the ifstatement works if you were to change the Initia value of num from 1 to 31 wee #include ‘using nanespace std; int main () & , . at ey =; amt mum = 31; // chs = if ( mmc 30} ae iS BET 22st ccesoies-vuess Ez ‘When you change the value to anything above 30, then build and run the code, you can see that ’ statement, displaying the current v intialf statementis, nly ine to be outputted to the serzen isthe second cou fe of rum. This is bacause the ise, soitignores the code within the b BRED (oe aint aniston wthina do, tt 009. For example { float temp; do { cout << “\nEnter the temperature’ Cor =1000 to exit): * << endl; cin >> temp; iF Ctom <= 0) a (cout 0) 4 ‘cout << “\nAt Least it’s not Freezing!” << endl; + 7 while C temp ! ‘cout <é "\nGood return =aaeR le loop that asks the user toe er the current temperature, BED The FirstiF statement checks to see ifthe us nputted value Is ess than or equal to zero. Fits then the output is‘ herwise, the input s ‘greater than zero, Atleast t's not freezing) ode outputs BED Finally, if the user enters the value -10000, which is impossibly coldso is therefore a unrealistic thedo... while cops terminated and a friendly ‘Good bye' is splayed to the screen. BEER) Using ifs quite powerful ifit’s used correctly. Ju ‘emember that ifthe condition is true then the fe executes what's in the bra continueson its merry way See what: musing f and a combina s. not, = ) Loops and Decision Making If... Else Statement There is a much better way to use an if statement in your code, with if... else. If... else works in much the same way as a standard if statement. IF the Boolean expression elem Me eee MeL eek le ecto a Aeele( RN eo Pcteaen teh ese IF YES, ELSE NO There are two sections of code that can be executed depending on the outcome in an if... else statement. It’s quite easy to visualise once you get used to its structure. BRIER the First line inthe code creates the integer called ‘num and gives ita value of 1. Theif statement Finonaae ostream checks to see iFthe value of num is less than thirty and iF tisit include Usinginamespacerstdy = | "1"? nemermnon we ‘outputs “The number i less than 30!"to the console, int nain © : \imer Fi ihe omen ¥ - : e's expand the code From sao SRID te se companion tof cocksithe ourber BED ooo mr Fomtersttonen ne Tetons presious pase: number is greater than 30!” to the console; and Finally, the code is i terminate satefatory. ‘int num = 1; ‘Sone ee Tne Ruber is Less than 30M << onalT +f C num <3.) i. 7 COUOREOTOSEAMLCNLNNRNNSEorgonmecen || ee << "PME mata se rena nan 01 cc amt ends mae RI onchange thevaie of mmintne codeor oa - - sou can improve the code by asking the ser to TOI a ai + t return @; enema ¥ cout << “Enter a number: “; cin >> nun if (num < 30.) i cout: << “The number is less than 301" << endl t else i cout << “The nunber is greater than 30!” << endl; # return’ 0; ' 0s en ieee The code works but what Ifyou wanted to display something ifthe User entered the number 30? Try tis: t ‘int. nun; cout << “Enter a number: cin 55 num if C num < 30> 7 cout << “The number is Less than 30!” << endts + else if ( num > 30) { cout << “The number is greater than 30!” > nung ‘cout << string(S®, *\n’)3 PEPE the cout <> guess; triest+5 if (guess > num) { cout << “\nToo Hight\n" << endl; else if (guess < nun) 4 ¥ else if (guess cout <<""\nToo Low!\n” << endl; nun) cout < Save As, callit batpyt.bat and set content ofthe command os.environ. Os environ iscalling the Save As Type as All Files, system variable ‘name’, which we created inthe batch Fla. Save the code as batpyt.py. Deere nee ne i To recap: we havea batch file called batpy1 bat, ‘hich asks the user their name and stores the info ‘2 system variable called name. ell then print tothe screen ‘message, then run the Python cade, and finally print" worked!" The Python code, called batpy'py, uses the OS module to call ‘osenvironf'name’], stored as n.illthen print the value of after amessage. THE LINUX WAY Linux’s version of passing variables to Python is slightly different, just because it’s Linux! It's easy, though, and here's how it’s done. Start by opening your favourite Linux text edtor, nd entering the Following: #1/bin/oash echo -n “HeTLo, what is your name? read firstname export firstname at ae python3 ./batpyl.py ' echo echo be echo = “Tt worked! 11" ym ve echo Drop into a Terminal session and make a new sirectory celled batpy (mkdir batpy). Save the Bach ecript as batpy.sh, and fram the Terminal enable the script as executable with: chmod 4x batpy.sh, =n" b< Oa wia tee eee ‘al B or Aa ein BTID op intoa Windows command prompt a navigate to the Folder Batpy. To run a Windows batch file, simply enter the command: batpyl.bat er your name as instructed and the reply willbe passed to Python, then back tothe batch Fle to end. PRED Now create anew Python file, and enterthe Following import os os. environf ‘firstname “0 ‘Save the Python code as batpyt py. print(*Your name is ESTP 22ck inthe Terminal, enter: ./batpy.-shtorun the Bash script. Asyou can see, the results are the same as in Windows. The major differences are making the Bash s executable, and adcing the export firstname commando File. In Linux, you need to export system variables before they can be ‘accessed by the subsystem, in ths case the Python code. us 1 we rare a THE GOLDEN ERA OF CODE THE BEEB The problem with BASIC ing old : Spectrum, aswellas nthe 50, code stil enyday coding GOING BASIC ses otro language topla sdbackin the mid sit chosen, due toitsru AkPurpose Asa result, the BBC amethe dominant e¢ BEEBEM Naturally, you couldscous eBay and look For play around on,andtllbe a lot of Fun Hi und with some retro code, wells Kurtz needed alangu asi. ThnkoF BA acand macO, as well as othe la F youre using Windows 10, simply navigate tohttp//www.mkw. sme.uk/beebem/indexhtml and download he Bet cisplayed in the mainscreen ees eres rk sis ee) 50 print BRC BASIC so has some interesting bul in features such asthevalue 1 REM Area of a circle 2as 20 Input “Enter the radius: r 30 let area = PI*r*r 49 print “The area of your circle is: “; area 59 print Once down instructions t aun jeandfollowtheonscreens —_Asyoull notice variables tall. Linu users can find the instalation Fes, with adoliar(§) reoresent asfullinstructions at http /beebem-unix bbcmicro.com/dawnload. stings, nothing afte the hunt MacOS users can get everything they need Frm: hetpe//ww, aa) STilécom/, loating point cima whole integer hasatocharacer andatyte BBC BASIC E hasan ampersand (8). The ‘Single quotes after the Print ‘online Soindicate ablank ine, one foreach tick while REM online Iisa comment, andthusignored by the BASC compiler Once inetalled and powered up, JE BBC system startup along with acouple of beeps. Those of youoldenaughto hhavebeen ina UK schootin the 805 villcertinirecell this setup Beem wl dsolay the de Neselessto say, theres alot youcan learn aswellashaving fun, with BAC BASIC. ’sarainy day project and something thatsinteresting to show the kc 80s, sseline numbers to determine which ines of cade runin >ampl, toprint some sishow werolled backint There are a number of tes arn BEC Inara 2s http:/farchive,retro-ki.co.uk/bbc.nva.ora/docs.php3 html Sec ‘Once you've typed the above in, press ro vihat youcan come upwith using BBC BASIC, er ather BASIC ype Fa Enter andthentype: cifferent systems, andlet us know what you've created We can of course expand include variables, mut ras int statements andso on Oa es 10 Input “Hello, what’s your name? “ nS pet ee tolockto the BSC Micro 20 print play acuind Morea q 30 print “Hi, “n$ “I hope you're well today code.|Fyougrew up witha Type RUN toexecute the code, you can also type LIST to view the cod Commadore 64, thenye stry VCE, the C64 LUkewse, the 2x youveentered, cnalw erat cru has lew of get emalators available for every modern system to pley around ee na a ct you can probably forvinualy Pee aad everyebitor 1é was produced overthe As youcan see, variables arehandled inmuch thesamewayasPython,a unique perspective and cading intstatementn ts own displays blankline,ancCLScearsthe screen: nuances,sofindafewandsee feat Each hasthat ~asused in conjunction withthe OS module in Python and when unning what you can create Windows. Were aso able to dosomemaths work, and play around with variabestoo! ras 10 input “how old are you? “ a 20 print 30 iF a> 40 print “You're over 40 years old.” 40 if a < 40 print “You're under 40 years old Nar ok Oe a nen ara Disa oe Text Animations THE FINAL COUNTDOWN andsoonto 10.It'ta ime, but t's worth it in the en youcan always take acifferent proach ane design the numbers Therest ste rocessis tointalve the code settings and sta nessage LAST OFF < fstart the countdown for counter in range(start, 0, -1): AE counter == 10 tent) éna() iE counter == 0: eight elif counter == 7: savant) elif counter == 6: six) vel) tour) elif counter == 3 threat) 01) ‘onel) time. eleep(t) os.systen(‘cle! if os.nane int! else ‘clear’) Let's begin with some examsle code that wil display alarge countdown, Fromten, then clea quitesimple, but lengthy. You allne Time modules then And Finally, we can adda display for the message: fotaplay the massage printov*yv print(ne print(neeage) printin< peint(-v'y"¥" rine(\n\a\n") The code in its entirety can b fram within our Code Repository: https:// bdmpublications.com/ code-portal, where you're free to copy ito your awn Python IDLE and use itas yousee fit. The end effect is quite good andit be worth to your own Pee ees co Toextend the code, or make it easier to use, you can always Greate the number Functions in their ow Python code, callit Count.py for example, then import Count at the beginning of ‘anew Python file called Cauntclown py, along with the OS and Time modules: smpart oo import tine import count From there, you will need to specify the imported code in the Countdown section: tstart the countdown for counter in range(start, 0, -1): Af counter == 10. ‘count. ten() count.ninet) elif counter = 8: count.eiahe() elif counter = 7 count.cevent) elif countar = 6: count. a0) elif counter ‘count fve()| ‘count. four) elit counter = 3: count.three() e1iE counter = 2 ccount.-¥00) elif counter = 1 ‘count,one()| This will ull the Functions From the imported Count.py and print them to the screen, ROCKET LAUNCH Building on the previous countdown example, we can create an animated rocket that'll launch after the Blast OFF! message has been printed, The code for this would look something like this def Rocket!) ‘distanceFrontop = 20 os.eystea(‘cle’ if os.name = ‘nt’ else ‘clear') print(*\n" * distancersontop) print” n bi print" u , peint(* WN oh prine(” aN > tine.sleep(0.2) os.eysten(‘cle’ if os.nane == ‘nt’ else ‘clear') ‘istancePronfop —= 1 ££ distancePromtop ietanceFronfop = 20 Hesach Rocket, Recket() air ay Fa ee.) alee ae i LETS cee lere we've created 8 new Function called Rocket, which produces the effect of an ASCIFike rocket taking off and scrolling upward; using che distanceFromTop vanable. To use this, adit to the end of the previous countdown code and at the end of the Blast Off! message, add the Following lines: print (\n\n\nhn’) Anpac(*Press Enter to launch rocket. This wil allow your message to be displayed and then, when the ser has hit the Enter button, the rocket will launch, o code in ts entirety can be Found in the Code Repository at: https://bdmpublications,com/ code-portal, ROLLING DIE Aside from the rocket animation, together with its countdown, bit of text-based animation is that of aralling A rolling dice can be a great animation to include in an adventure game, where the player rolls to see what thelr score is compared to that of an enemy. The highest roller wins the round and the lasers’ health drops as.a result. It's an age-old combat sequence, ‘mainly inthe Dungeon and Dragons board games and ighting Fantasy novels, but it works wel The code you'll need to animatea dice rollis: Amport os import tine ‘from random import randint aie br wow dom Ate.append(” ola \x0 ~) 2 eappend("0 \2 0 \a O°) #3 Aie.append("0 ln \K00) le.append("0 O\n 0 \n0 0") #5 ie.append("0 O\n0 O\n0 0”) #6 ee Atoot ‘for roll in range(0,15): of systen(‘cis" peiat("\e" fonber = randint(0,5) print(die(number)) time. sleep(0.2) Sf of nane == ‘nt’ else ‘clear) You may need to tweak the O entries, to line up the dats on the virtual dice, Once i’sdone, though, you'll be able to ‘add this Function toyour adventure game code and allit up whenever your character, or the situation, combat or chance rallof the dice i Coormand Prompt quires some element of luck, ce Poe en > Cee BL et 4 a 3 er > as Casa ose cl Po aca is isnot justan ats par of comput rogram th ns ay no longer be with us, inclu dd alittle rt perninour owMPy themed spice ta the mix SCREENS Creating loading screenin Pythons loading scr Jed from tape. The then praceedto ard the buyin For ns Featured animation Loading screens wese 3 pat ‘game as an experience. Som ow. Teeter inves nes arden ge ‘adventure. Once you've established your story, created the characters, events and >on, you could Fe som: oF THE CODE Following code to a Now Fle det loading _ screen(eeconds) screenswopen("acreens. txt", ‘e!) for lines in screens: print(lines, end="") tine. sleep(seconds) ‘eiteans Clore!) iain Code stact os.systen|'cle! if oo.name leading _ screen(.5) ‘at! else ‘eleaz’) Print ("\sour code begine here...) Thecode quite simple: import the OSand Time moduiesand then create Python function called loading screen wit a (second option. Ythin the funtion open the textile withthe ASCHart as readonly and create For loop that rea the teat ile one ine-at atime, Next, printthe ines incidentally, the lines, end=" element wlstrin the newline Framth text document, wthaxt tyoutlend upwitha doubleinespaced cpa Incude themingin seconds and dose the text Fie buffer. Thefinalparof the co Sor Wind Function, together with the outout number oF seconds tow ##ian Code Start is where youlldlear the ows Cle screen or Linacand mac) and cal the it foreech Save the code as ser y, drop into a Comma Prompt or Teri will deer and your as attnside the textile willeadin tne-byine, ceatingaloadng screen effec reading ther Fa uritentroduction: reenis that oF asimple loading word laadingis dsplayed flowed by some characters and apercentage ofthe program loaded, Wet may not take long foryour Python code to load, thee ect can beinterest Create 2 New Flein Pythonand enter the Fliowing code ampart os import tine det loading _bar(seconds) for loading in range(0,seconde‘l) percent = (Loading * 100) // seconds print("\o") Brint(Loadiag...") prine(v<" + (= * loading) + (° > * (seconde Leading)) + ° "+ stz{pezcent) + °<") rint("\n") tine.lesp) cesysten(‘cle’ 1 oe.nane == ‘nt! else ‘clea Wain Code start Beading _bar(t0) print ("\sour code beging here...") The code worksin much the sare way asthe previcus except, instead of reacing fromatex il,’ running through afor loop that prints coc. followed by an animation of sorts, long with a percentage counter clearing the screen every second and displaying the new results tssimple, yes, butcuite effective inits des COMBINING THE TWO ow about combining the wo elements we've looked a? Le’ be oscing,.. progressbar, followed by the loading screen. A jn wth that, you nd continue your program. Here's the code: Amport os Saeaeeeiaal def Loading _bar(seconds) for Leeding in range(0,secondes]} percent = (Loading * 100) // seconds peine("\e") print ("Loading Brintiv<” + (~" ¥ loading) + (° > * (anconda- eading)) + "> " + ste(parcent) + “4") peine("\e") time. sleep) os.systen(‘cle’ if oa.nano == ‘at! ol ‘etear’) det toading _ screen(eaconde) ‘screans=open(“scroens.txt", ‘s’) print(Lines, end="") time.sleep(seconds) sscreens.closel) Wain Code start, Joading _bar(0) oeeysten(‘cle’ if os.nane == ‘nt’ alee ‘clear’) Aeading_ screea(.5) print ("sour code begine here...") 18 furcions up wherever and whenever you eainning ‘You can of course pul ‘wantin your code and theyll display, asthey should, tthe Remember to have the ASCI textfile in the same folder a ent"sereens.b",") partoft code, atte screen: to where the text ieisloc ee eared with Python nhappen hen we work together. NASA, among other agencies, usesa wealth (of Python code ar-boarc the to help automate routines, well tas an in-between link trandate code from one language to ‘another, and then intoa human readable format. you're considering acaseesinspace then learning Python samust-have sil re toFillyouinonallthe details regoring the thelSSutlises, we canlookata fun Python script that wil rackthe THE GRAPHICS Fistly weneed to get hold of amapof the world, andanimage ofthe |5S to use asan icon that willbe undated accorcing to the postion ofthe space station ast travels ver the surface. A quick Google of World Map vllhelp vou euchere. Look for one that's reasonably large, che one we sed fortis example was 1280x700, and one that has the names ofthe countries ~ifyoure using this wth young people, tohelp with putt shapes of counties to names, Next look foran SSican,Asthisis going to bea graphical representation ofthe location ofthe 5, eed the image tobe reasonably small soit nithemmap, butalso prominent encugh 1 map is loaded. We opted Foran image that's 32x22 rt worTy too much youre not abeto find one that smal Bee Meee earner Tracking the ISS 18S, display the numberof astronauts on boo update the stations Cutrentlattude and ionatude every ve seconds, while aso Saving your current latitude and longitude, Displaying al hat information ina single screencan becomealitle lutkered sointhis instance we're going to lonkat spreading al those details over three screens:a text document window -dsplaying the astronauts and your current latitudeand longitude, acomman¢ ine (or Terminal window) -csplaying the continually updating latitude andilongitude of the Is5 35 torts Earth, and a nal large window displaying a mep ofthe world, together with anicon representing the updatedasit orbits. Interested? Read aie i @F - tas Feed YO er: ~ Asweire going tobe using Turtle a cormpone ‘rages wil needto be corverted to GF since thi knee, the downicaded edefautand ‘upaconveter online, but tforr, willsfFice ‘Smply load the image up in your image editor app and choose Save As, callthem map andiss respectively, ancicick GF as the image Format Remember to so resize the SS rage before saving tasa GF THE CODE Thecode were using here ulises an open source API (Application Programming Interface) to retieve reaktime data oninerecardingthe status the $5, An AP enables applications to communicate with one anatherby prouding the rew data thata programmer can pullout and Ineract within heir own code. In thiscase, Ue APlin question ise web based collection of raw deta that'sstoredina JSON UavaScript lect Notation) format—en accessible and easy to se datanterchangeinterface Inordee forPython to interact with the SON provided data tneedsto Use the ur request and on modules We'eaisogoingto beusinga ‘ews module called geocoder, which will pullup 3 user curentlabcude ndings based on thal Paddres, The wo JSON APIS can be tecatedt tp/optopen-netify.rg/astrosison, and, hep: /opi open-notifyorg/se-nowjon, One of wach contains the data regarding the astronauts onboard the, andthe other contains the data regarding the curentlocaion of helSSin longitude and etrude. ee © apepe nome, Let's beginby breaking the code into bitesized chunks: Amport Jeon, turtle, urllibrequest, tine, webbrowser Amport geocoder # need to pip install geocoder for your Aat/long to work. Fist, we need tolmaort the madules usedin the code: kon, tute, urs, request, time and webbrowser. The son and ulbrequest modules dea with the data being pulled roma the APK turtle will display the graphics, ~andtime you already know. The webbrowser module wil open text Fes in the default textile application - despite what tsname may suggest. Thegeocoder madule is anew element,andyou willed toinstallt vith: pip install geocoder. Geocoder can retrieve ntheir iP adress, as each ISP wihave a geo-spedfc iP. Wetcieve the nanes of all the astronauts currently on Dboard the 185, and own Lat/long - write to a file and display lari = "http:/fapi.open-aotify.cxg/astros.jaon” response = urllib.request .rlopen(ur!) result = json.loads(response.read()) aropea("iee txt") awzite(There are currently " + str(result{"nunber"]) +" faetronauts en the IS5:\n\n’) people = result{"people"] for p in people! aorrite(pl'nane’] + - on board + "\n") gegeosodar ip('na’) # need to pip inatall geocodar, and Amport as in the headers above awzite("\nYour currant Lat/Long is: * + strig-tating!) # prints your current lat/long in the taxt fe. a.close) vwebbrowser.open(*ise.txt") This section will use the json and urlib.request modulesto pullthe data from the AP thet containsthe namesof the astronauts anboard the 1, Iethen creates anew text fle caled ist, where illite Thereare ‘currently Xastronauts on the ISS... andlst them by name. The second part of thissection villthen use the geocoder meduie to retrieve your current latte and longitude, based on your IP aides, an also write thatinformation to the endof the text fle that contains the names oF the astionauts. The es line, webbrowseropent is bt? wil se the ‘webbroser module to pen and dplay the new written text fle inthe system's defaulttex fie readna app. #setup world map in Turtle serean = turtie.Serean() screen. setup(1280, 720) sereen, setworidccordinates(-10, Road the world map image sereen.bypic(*map.gif") -50, 180, 99) screen.register _shape("iss.gif”) Ase = turtie.Turtie() Sas shepe(iee.gif") Sas sethending 45) ss.pemup0) This section ofthe code sets up the graphical window containing the wor'd map and the IS icon. Te bagin we et up the turtle screen using the resolution ofthe world map image we downloaded atthe start of thistutorial (1280 x 720). The screen setworiccoordinates stax will ‘mark the boundaries of the screen, creating the xandy coordinates of the four corners ofthe canvas, so thatthe $5 con can freely travel acoss te map of tye orld and rap itself bac tothe opposite se when it reachesan edge. TheISSiconisset as the turtle pen shape, cving tan angle oF a5 degrees when moving, smite re: ioad tha current status of the T8S in resl-tine ‘url = "http://api.open-notiy.org/sss-now.jeon" Feeponse = urllib request elopen(erl) result = j2on.loada(eeaponse.read()) Extract the 185 location location = reeult[“iss _ position”) lat = location ("iatitude"] Jon = lecation["Lengitude’) fourput Lacitade and Longitude to the console at = oat tat) don = oat en) prine(\ntatiteda: ° + ste(lat)) Print(longitede: "+ st=(Loa)) fopdate the TSS Location on the map ies.geta(lon, Lat) deetzeen every 5 seconde ‘time sleeps) Now forthe Final part of the code: Here we cllectthe location data from the ISS status AP, pulling outthe latitude and lonaitude elements ofthe {SOF ile. The cede then prints the latitude andlongitude datatothe astingin order topieitcorectly. The lst section wil use the latitude an! longitude as vatiables zt and ion, to undate the IS iconon the mep everyFive seconds. consoleTerminal transferring the data from float (Bp tstacepy- eer doi Dacurent thon Track Strack p70) Fle ft Format Rin Opions Window Help és the code nits entity Amport Jeon, turtle, urllib.requast, tine, webbrowser import geocoder # need to pip install geoceder for your Lat/Long to work. ‘fetrseve the nanee of all the astronauts currently on Doss the 189, and own lat/long - write to a fle and ataplay rl = "htepi//api.open-notty.org/astros json" responce = urllib request urlopen(ssl) result = json. losda(eeapanse.read()) aropen(*iss.txt"/"W") aweite(‘Thare are curzently “ + str(result{“number") + * astronauts on tha IS8:\n\n") people = result{"people"] fer p in people! awrite(p["aane"] + ~ on board” + "\n") g-geccoder.ip('me') # need to pip install geocodar, and deport fas in the headers above Awzite("\nYour currant Lat/Long ie: printe your current lat/long in the text fle, a.close() ‘wabbroweer.open("iss.txt") > + ste(g.tatingy) # setup world map in Tortie screen = turtie.Sereen() screen.setup(1280, 720) screen. setworidesordinatas(-180, -90, 180, 90) oad the world map image sereen.bypic(*map gif") Yocation = remsie (*ie1_pon acteen.regiater _anape("ine git”) = turtle,tuctlel) s8.gif") ses setheading(tS) iss.penup() Yioad the current statue of the TSS in resl-tine GEL = “Retp://eps. open-notsfy.og/see-now.}e00" zesponse = urilib request.uriopen(orl) result » jeon.loada(respense.resd()) fixtract the 185 location Jocation = rosult{"iss _ position”) dat = leeation(riaesesda”] don = lecation(“iengitude’] output Latitude and Longitude to the console Jat = float(lat) Jon = fat ton) peint(\ntatitude: * + ste(lae)) peint(Langitude: "+ at=(Joa)) update the ISS Location on the map Aes.geta(lan, lat) deefsesh every 5 seconde ‘tine. sleep) ‘Create a new folder in you ster, called ISSTiack for examole), and place the two graphics, as wellas the Python cadeitself RUNNING THE CODE The code is best executed fram the command tineor Term desktop, enter your carmand line and navigate to where ywoulve saved the cede plus the two graphics. Aaunchthe code with ether python SSSTradkpy or Python SSTrackpy (depending on your system and what youive called the Pyehon code}, The cade willaunch twoextra windows line window youal the named astronauts elong with your current lattude and longitude andthe other wilbe the world map with the ISS icon located wherever the Sis curently oriting, The command line window willstarscrling through te changing latnide and longitude ofthe ISS. her with the command have open, One wil be the text Fe containing Using Text Files For Animation ASCII ANIMATION Let's assume you wanted to create an animated ASCII Happy Birthday Python script, with the words Happy and Birthday alternating in appearance. Here's how it's done. First we need to create some ASCIMike text, head ‘over to http://patorjk.com/software/taag, This an online Text to ASCII generator, created by Patrick Gillespie. Start byentering Happy into the text box, the result will be displayed in the main window. You can change the font with the drop-down, menu, to the side ofthe text box; we've opted Fo ESTESE DD Now create a folder in your Python code directory onyour computer (callit Test, for now, and open either Notepad for a Windows 10 computer, or, i you're using Linux then the currently installed text editor, Click on the Select & Copy button at the bottom of the ASCII Generator webpage, and paste the contentsinto the texte FETESEDD S2¥¢ the text fleas txt (ou can callit whet you like, but now For ease af use 1.x wil Suffice), Save lin the newly created Test Folder. When i's saved, do exactly thesame forthe word Birthday. You can select new font From the ASCII Generator, or add extra characters and when you're ready, save the file as 2.ext, ‘Open up Python and create a New File. We're going toneed to import the OSand Time modules For this example, Followed by allne to clear the screen of any content. IF you're using Windows, then youll use the CLS command, whereas its Clear For Linux. We can create asimple ffelse statement.to handle the command. ate a lst ofthe names ofthe 9 open, and then we needto pe Terminal met n them For display in tt 7 (oliext™, “2.0xt"] Flenames, frames = 0 for name in filenames: with openCnane, “r”, encoding="Utf8") asf: Frames.appendCF.readlinesQ) PTSD \¢ ve used the UTFS standard when openin text files as ASCII art as text, within a text file, julres you to save the fle as UTE compliant - due to the characters used. Now we can add aloop to splay the files as 1x, then 2.x, creating theillusion of animation while clear screen after each Fis displayed BTSE DD s2ve the Python code in the same Folder asthe text files and drop into @ Terminal or Command Prompt. Navigate to the Folder in question, and enter the command: python NAME.py Where NAME is whatever you called your saved Python code, Cree) Pee eee Jere's the code in ful import os, time os.systen(‘cls" if os.none == ‘nt? else “clear") filenames = [“1.txt”, “2.txt"] frames = 1 for name in filenames with openCnane, “rt”, encoding="utf8") as f: frames .appendCF.readlines()) for i in range(10) for frame in frames prime”. joincframe)) Eine. sleepC1) os. systen¢‘cls? if os.nane == ‘nt! else ‘clear’) ised Note from the : oe the same CLS and: statement as before. Again if you're punning on Windows then the OS mo the CLS command, using Linux ora Mi IF youwant, you could use a Ty BRPETB You can spice things upa litte by adding system erminal colours. You'll need to Google the system odes for the colours you want. The code in our example turns the \Wwinclows Command Line te green text on a lack background, then changes itback to white on biack at the end of the code. Either way, it'sa fun addition to your Python code. WE pe eee a ee Y® ge a mmon Coding Mistakes je IMM When you start something new you're inevitably going to make mistakes, thisis purely Ceo acdsee ae Meno A ee) oct Re Kora Oot ol cere oar Ne od ESL (eles) X=MISTAKE, PRINT Y There are many pitfalls for the programmer to be aware of, Far too many to be listed here. Being able to recognise a mistake and Fix its when you start to move into more advanced territory, and become a better coder. Everyone makes mistakes, even coders with over thirty years’ experience. Learning from these basic, common mistakes help build a better coding foundation. e EASY VARIABLES Meaningful naming for variables isa must to eliminate ‘common coding mistakes. Having letters of the alphabet isfine but what happens when the code states there's a problem with x variable. It’s not too difficult to name variables lives, money, player’ and so on I would be wonderful to be ableto work like Neo from The Matrix movies Simply ask, your operator lads itinto your memory and you instantly know everything aboutthe sublect. Sadly though, we cant do that. The first ‘major pitfalls someone trying to learn too much, too quiciy, So take cading in small pieces and take yourtime. 1 var points ~ 1023; 2 var lives = 3; 3 var totaltime = 45; 4 write( "Points: “+point 5 write(*Lives: “+Lives); a 9 write("oral Tine: "itotaltine:” se: write("— 1 var totalscore = 07 write("Your total Score is: "+totalscore) ; Sp release arene an PLAN AHEAD throu the sedis oF ce tha ere cau problens also useful iF ou need to review an clder piece of code oueetalle po cevien a ober pieces While it's great to wake up one morning and decide to code: a classic text adventure, it’s not always practical without 2 ‘900d plan, Small snippets of code can be written without too much thought and planning but longer and more i depth code requires a good working plan to stickto and help iron out the bugs. Common Coding Mistakes USER ERROR BACKUPS SS ea al Bo} Python Beginner's Mistakes je OM» Mb PETS OU enene creche MU era matric aC nec a Mua enue cI) language, it can be easy to make common mistakes that'll stop your code from running. DEF BEGINNER(MISTAKES=10) Here are ten common Python programming mistakes most beginners Find themselves making. Being able to identify these ‘mistakes will save you headaches in the Future. eam COMMENTING Every proarammer has and does at fe toinsert into the ing others’ code, but ssto what's going on. Is pment and help nothing wrong with what itdoes before you go blindly running icon Python Beginner's Mistakes (c} COUNTING LOOPS COLONS thon a loop doe range. Soi you wanted t then youwill need to use: count thelast numberyou Its loop tocount from 1to10, st lass Hangnan: n= UistCrangeCt, 119) def guess(self, Which wil return 1t0 10. And soon. Thecolon tes the cade, and createsthe indentsto which the Following code belongste ng language, soyc ign. For examale, Lives: OPERATORS Using the wrong operator is al BRACKETS Ever that extra bracket they should have added to statement. Python relies on the routine having an equal amount of do: sinyour code: kets: including square brad C++ Beginner's Mistakes celle , There are many pitfalls the C++ developer can encounter, especially as this is a more complex and often unforgiving language to master. Beginners need to take C++ a step at a time and digest what they've learned before moving on. VOID(C++, MISTAKES) ‘Admittedly it’s not just C++ beginners that make the kinds of errors we outline on these pages, even hardened coders are prone to the odd mishap here and there. Here are some common Issues to try and avoid. SPACE Referencing the Standard Library is common for beginners putavariable throughout thelr co srt exist, Displaying i nisfinebutnet statement, your code ‘old the complerwhat the value oFxisto beainwith. hs byaddina 5 using namespace stds File Edit View Search Tools Documents Help sioraRaeazeenRaSeON PDoeGiew youn ag sing nanespace std ctesticpp * Ree aint #include Sule ee int main() bez0; std::cout <«< x; Zig cout ce, bc 6 } > SEMICOLONS GCC OR G++ Remember that each line of a C++ program must end witha F you're comaiting in Linux , ompiier asit used ripe compl 3) athe compiler. you're compiling C++ then you need te incorrect compile crivers willbe used. int main() int a,b, ©, di; d= std::cout Featuring the latest updates Step-by-step tutorials & guides ff Created by BDM experts PLUS SPE | DEALS and Bonus Co nplete The Complete iPhone 11 Pro | iPhone 11 Manual Pro Max Manual iPadOS Manual ieee “The Complete ST Sue canes | WhatsApp Cloud Android i eit) Manual - ert] Manual Galaxy Iveta ‘ys PII Tard MAU (VET rs The Complete Photoshop Black & White Samsun Smartphones Lightroom ff Photography \ Galaxy? &Tablets For Seniors ## For Seniors For Seniors [ For Seniors Leaming to code is one of the most useful skills you can adopt in this ever-changing digital world. Discovering how code influences, drives, and controls every aspect of computing can lead to improved job prospects, mastery of IT, and a better understanding of how our devices communicate with the wider world. Learn Coding: C++ & Python will take you through the initial stages of learning how to code with two of the most utilised, and powerful, programming languages available today. Python is a perfect beginner's language: easy to learn, while being effective and efficient. C++ is the powerhouse of programming and with it, you can create great things. Join us, then, and let's start learning how to code. Python Python can be foundin the background of websites, helping to control everything from the internet, through to NASA, on-board the ISS. It's a simple, but extremely effective, programming language and you ‘an earn the basics in a matter of hours. Master Python, and you hold the future of Al, Big Data, and the Intemet in your hands. Python Power Within, you will learn how to use the core selection of Python’s many commands and routines to create your ‘own code that you can expand and improve on for use in the real world, We look at using variables, user input, loops, Python Modules, and even Python graphics, C++ Windows, macOS, Linux, PlayStation and Xbox games, they all have one thing in common: at the heart of each lies C++ code. C++ is powerful, fast, and can control some of the more complex elements of technology. It's little wonder that C+ is one of the most sought-after programming languages in the job market. Start your C++ adventure here, and see where it leads. Working with C++ Discover how to install a C++ IDE and compiler, how tosstart coding in C+, and get to grips with elements such as strings, data types, user interaction, file input and output, loops and decision making concepts. This book will help you with your frst steps into C++. Keep on Coding We've got some great coding projects for you to get your teeth into, Including code that can pass variables from the command line to Python, animations using ASCilart, code to track the International Space Station in real-time, and even some retro coding fora bit of old school fun, there's something for everyone in Leam Coding: C++ & Python.

You might also like