You are on page 1of 80
a ’C+4\ 9 & Python For Beginners All you need to get started with C++ & Python coding Over TN) Utena cs Inside Jargon-free Tips & Advice Step-by-step Tutorials Clear Full Colour Guides Want to master your Code? Then don’t miss our NEW Programming & Coding magazine on Ei Readly now! Click our handy link to read now: C++ & Python For Beginners Starting something new can be daunting. Learning a skill or mastering a new piece of hardware is tough. Even tougher if you have no-one at hand to help. Conversely as the complexity of our consumer technology increases, the size of the requisite instruction manual decreases or in some cases it simply disappears. At numerous times in our lives we have all been “beginners”, there is no shame in that fact and rightly so. How many times have you asked aloud, "What does this button do?”. “Why doesn’t that work?”. “What do you mean it doesn’t do that?”, "HELP!". At the start of any new journey or adventure we are all beginners but fortunately for you we are here to stand beside you at every stage. Over this extensive series of titles we will be looking in great depth at the latest consumer electronics, software, hobbies and trends out of the box! We will guide you step-by-step through using all aspects of the technology that you may have been previously apprehensive at attempting, Let our expert guide help you build your technology understanding and skills, taking you from a novice to a confident and experienced user. Over the page our journey begins. We would wish you luck but we're sure with our support you won't need it. Contents ) 8 —_WhyPython? 10 Equipment You will Need 12 Getting to Know Python 14 Howto Set Up Python in Windows 16 _ Howto Set Up Python on a Mac 18 Howto Set Up Python in Linux Re | 22__ Starting Python for the First Time 60 Your First C++ Program 24 Your First Code 62 Structure of a C+ Program 26 _ Saving and Executing Your Code 64 Compile and Execute 28 _ Executing Code from the Command Line 66 Using Comments 30 Numbers and Expressions 68 Variables, 32 Using Comments 70 Data Types 34 Working with Variables 72 _ Strings 36 User input 74 C++ Maths 38 Creating Functions 40 Conditions and Loops 42 Python Modules @ 46 WhyC+H? 48 Equipment Needed 50 Howto Set Up C++ in Windows 52 HowtoSet Up Cr+ ona Mac 54 Howto Set Up C++ in Linux 56 Other C++ IDEs to Install ora bémpubiations.com (Contents wo bdpublicstionscom Say Hello to Python Sr ic ee TC available to learn and use. Some are complex and incredibly powerful and some are extremely basic and Pet Peed age eeu Peete eu teint kate with a generous helping of power that allows the user Dee eg eae Tous eee ene e Pe Moe Reaute cuca cs Dae ee a rM ue Pree en a ee eee ee lively community behind it that shares knowledge, Cees edt er he ee nea act rom eke cace rT sees ener es een Ent nen neat ele tare eee cn ae SO tee ve eee cn latest version of Python and From there guide you on Teese ee eg Functions and features of the language. Before long, Sete rT ecu ce Recent eure Rnriclace es] eran r Say Hello to Python Why Python? There are many different programming languages available for the modern computer, PR Renee een eae ru hae cece tema ete ts Pek estutehcgeen'] eye Rel elie] Gen arte ic work, others for mobile platforms and such. So why choose 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 anew Frontier, Forging smal routines that enabled the letter to scroll across the screen. Itmay not sound terribly exciting toa generation that's used to ultrarhigh definition graphics and open world, multi- player online gaming. However, Fortysomething years ago it was, bindinaly briliant. Naturally these bedroom coders helped form the Foundations for ‘every piece of digital technology we use today. Some went on to become chief developers for top software companies, whereas ‘thers pushed the available hardware to its limits and Founded the billion pound gaming empire that continually amazes us. Regardless of whether you use an Android device, iOS device, PC, ‘Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin to. car, set-top box ora thousand other connected and ‘smart’ appliances, behind them allis programming. Allthose aforementioned digital devices need instructions to tell them what to do, and allow them to be interacted with, These instructions Form the programming core of the device and that core canbe built using a variety of programming languages. ‘The languagesin use today differ depending on the situation, the platform, the device's use and how the device wil interact with its Vn @ > Races > 0O De “Setcursor(p. y cirtontdotrocsi } ifleursor >= 0} Befreshion cursor) centrchataboeteecuet) ‘eTIMTnG( Paine int fs: CU ag ew breaks d Color te srr } Torcat } C++ is usually reserved for more complex programs, operating systems, games and so on. | rid arryeart ssi aortrocin() void arraycerLs:Paint(orave w) oer catSerolL0 veregrid + ti Far({s'= 0;_j¢ < colum.cetcaune(; jse+) « Wie ey’ header caviapmdtnta):) colum.Getcount() 1) >= 0) Len scolorisabled, scaloreper): wiLe(a © aatcoune()) tine) Fitop 2 catbaneey(ids ob: isi < colum.carcoune(); 36+) ¢ ah)! ‘environment or users, Operating systems, such as Windows, macOS. ‘and such are usually a combination of C++, CH, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and so.on, More general-purpose programming is used to create programs, ‘apps, software or whatever else you wanttto cal them. They/re ‘widely used across al hardware platforms and suit vitually every conceivable application, Some operate Faster than others and some are easierto learn and use than others. Python is one such general purpose language. Python is what's known asa High-Level Language, in thatit ‘talks! to the hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless ‘move interactions, Whilst t's nat as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that i’ universally accessible and easy to learn, Yi te= xnvake- java spore savas iang. reflect. *; Public static void main string args try Glass ¢ = Class. forname( args[0] ); lethod'm = c-getmethod( args{1}, new Class Object ret = m.invoke( null, null ); Systen.out.prinetn Stnvokea static method: " + args[ + of class: "+ args{o) with no args\nresults: " + ret); catch ( ClassNocroundexception e 7 Class fornane() can't find the class ach’ ( Nosuchtethodexception e2 7] that method doesn't exist Gacch'¢ ilepataccessexception €3 77've don't Rave permission to invoke that ethod Batch ( rnvocationrargetexception 4 7[ an exception ocurred white Tnvoking that inechoc Systen.out.printin¢ Method threw an: " + ed. getTargetexception( ") 3: Javaisa powerfullanguage that'susedinweb pages, B set-top boxes, TVsand \ vO ( Why Python? Cl Python was created over twenty six years ago and has evolved to become an ideal beginner's language For learning how to program 2 computer. ts perfect forthe hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves ora piece of external hardware and the computer itself. Python i free to download, install and use and is avallable for Linux, Windows, macOS, MS-D05, 05/2, 8e0S, IBM series machines, and even RISC OS. Ithas been voted one ofthe top five programming languages n the world andis continually evolving ahead of the hardware and internet development curve. So to answer the question: why python? Simply put, is Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational tool. TE TINKEYse°B THEN LET pup o" THEN LET py=P 4 Ze (BU) sey THEN LET sas42 BRINT aT. 2. FoR v=1 TO 4000: NEXT v NEXT’ w ea BASIC was once the starter language that early ‘bit home computer users learned. Python is a more madern take on BASIC, i's easy to learn ‘and makes for an ideal beginner's programming language. z= Say Hello to Python Equipment You Will Need You can learn Python with very little hardware or initial Financial investment. You don’t need an incredibly powerful computer and any software that's required is Freely available. WHAT WE'RE USING ‘Thankfully, Python is a multi-platform programming language available For Windows, macOS, Linux, Raspberry Pi and more. IF xyou have one of those systems, then you can easily start using Python. {| COMPUTER ‘Obviously you're going to need a computer in orderto learn how to program in Python and to test your code. You can use Windows (From XP onward) on either a 32 1 64-bit processor, an Apple Mac or Linuxinstalled PC, AN IDE AnIDE (Integrated Developer Environment) is used to enter and execute Python code. It enables you to inspect your pragram code and the values within the code, as, ‘wellas offering advanced features. There are many different IDEs available, so Find the one that works For you and gives the best results [_] PYTHON SOFTWARE ‘macOS and Linux already come with Python preinstalled as part ofthe operating system, as does the Raspberry Pi However, you need to ensure that you're running the latest version of Python. Windows users need to download and install Python, which welll cover shortly. (_] TexT EDITOR Whilst a text ealtor is an ideal environment to enter code into, it's not an absolute necessity. ou can enter and execute code directly From the IDLE but atext editor, such a Sublime Text or Notepad++, offers more advanced Features and colour coding when entering code. | INTERNET ACCESS Python is an ever evolving environment and as such new versions often introduce ‘new concepts or change existing commands and code structure to make ita more efficient language. Having access to the Internet will keep you up-to-date, help you ‘out when you get stuck and give access to Python's immense number of modules, = [_] TIME AND PATIENCE Despite what other books may lead you to believe, you won't become a programmer in 24+hours. Learning to code in Python takes time, and patience. You may become stuckat times and other times the code wil low like water. Understand you're learning something entirely new, and you wil get there. ra Equipment You Will Need Cl THE RASPBERRY PI ‘Why use a Raspberry Pi? The Raspberry Pisa tiny computer that's very cheap to purchase but offers the user a fantastic learning platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras. PIN ‘The Raspberry Pi isthe latest version, incorporating a more: powerful CPU, more memory, WiFi and Bluetooth support. You can pick up 2 Pifor around £32 or asa part oF kt For £504, depending on the kit you're interested in, W4a el) sel The FUZE isa learning environment bult on the latest model ‘of the Raspberry P. You can purchase the workstations that ‘come with an electronics kit and even 2 robot arm for you to build and program. You can find more information on the FUZE at wwuiFuze.co.uk Ceding We have several great coding tiles available vis www. bdmpublications.com. Our Pi RASPBIAN books cover how to buy your First Raspberry Pi, setitup and or Beginnef “The Raspberry P's main operating system is a Debian-based Use it; there are some great Linux distribution that comes with everything you need in step-by-step project examples a simple to use package. t's streamlined for the Piand isan and guides to get the most ideal platform for hardware and software projects, Python From the Raspberry Pi too. programming and even asa desktop computer z= Say Hello to Python Getting to Know Python Python is the greatest computer programming language ever created. It enables you to fully harness the power of a computer, in a language that’s clean and easy to understand. ‘WHAT IS PROGRAMMING? It helps to understand what a programming language is before you try to learn one, and Python is no different. Let’s take 3 look at how Python came about and how it relates to other languages. PROGRAMMING RECIPES Carol} Programs are like recipes for computers. A E Aprogramminglanguage recipe to bakea cake could go ike this: ‘sa lstof instructions that acomputer follows. These ut 100 grams ofselFraising flourin a bow, } instructionscanbeassimple Add 100 grams of butter to the bow. } asdisplayingyourname Add 100 millitres of mk. or playing a musicfile, or Bake For halFan hour } ascomplexas buidinga whole virtual world. Python Js programming language conceived in the late 1980s by Guido van Rossum ‘at Centrum Wiskunde & CODE Just ke a recipe, a program consists oF instructions that you Follow ‘order. A program that describes a cake might run like this: Informatica (Cw) in the [bot = 0 Netherlands asa successor to If four = 100 the ABC language. [| butter = 50 Tk = 100 bon .append([our butter milk] cake. cook(bowl) Guido van Rossum, the father of Python, PROGRAM COMMANDS ‘You might not understand some of the Python commands, like bowlappend and cake.cook(bowl) The firsts alist, the second an object; well look at both in this book. The main thing to know is that it’s easy to read commands in Python. Once you learn what the commands do, i's easy to figure outhow a program works. HIGH-LEVEL LANGUAGES Computer languages that are easy to read are known as “high-level “hiss because they fy high above the hardware (also referred to as ‘the metal’). Languages that “fly close to the meta," lke Assembly, ‘are known as“owrlevel’. Low-level languages commands read abit like this:msg db ,@xa Len equ $ - msg PYTHON 3 VS PYTHON 2 ZEN OF PYTHON Python lets you access al the power of a computer ina language that humans can understand. Behind all thisis an ethos called "The Zen of Python." This sa collection of 20 software principles that influences the design of the language. Principlesinclude "Beautiful isbetter than ualy’ and “Simple isbetter than complex." Type ‘import this into Python and it wil display all the principles. oa" | Ina typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language: Cree eae! WORLD OF PYTHON agement) Pete tet Pee he time of writing (remember Python is oat) PYTHON 2.X Pert eee aria To cee es modul Pert eer ae Poona PYTHON 3.X and enhanced Features, These Features Oe MNS eae dao cy Seon nae! nes z= Say Hello to Python ) How to Set Up Python in Windows Windows users can easily install the latest version of Python via the main Python Downloads page. Whilst most seasoned Python developers may shun Windows as the platform of choice For building their code, it’s still an ideal starting point for beginners. INSTALLING PYTHON 3.X Microsoft Wit ‘Thankfully, it’s an easy process to follow. jows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. Star by opening your web browserto wanton. UE) org/downloads/. Look for the button detailing the ‘download link For Python 3.xx in our case this is Python 3.6.2 butas mentioned you may see later versions of 3). Download the latest version for Windows FETE ED lick the download button for version 3.x, and save the ile to your Downloads Folder. When the Fileis downloaded, double-click the executable and the Python installation wizard will launch. From here you have two choices: Install Now and Customise Installation. We recommend opting For the Customise installation link Install Python 3.6.2 (32-bit) ssn eta nt i tg Qo pythén windows BSF Gc cnoncectnatorio stay with the defaults, t's good habit to adopt as sometimes (not with Python, thankfully) installers can include unwanted additional Features. On the first screen available, ensure all boxes are ticked and click the Next button, — me Pyenon docomantatin an Optional Features pythén windows ‘The next page of options include some interesting additions to Python, Ensure the Associate file with Python, Create Shortcuts, Add Python to Environment Variables, recompile Standard Library and Install for All Users options are ticked. These make using Python later much easier. Click Install when you're ready to continue. (a? puthén windows: ‘Advanced Options Eomvamastenegpienn rena tego Crys BOI r— Be Ci ‘Yes and Python wil begin to install. Once the installation is complete the inal Python wizard page will allow you to view the latest release notes, and follow some online tutorials. > @ puthgn windows Setup was successful PEED) Gefore you close the install wizard window, however, it's best to click on the link next to the shield detailed Disable Path Length Limit. This wil allow Python to bypass the Windows 260 character imitation, enabling you to execute Python programs stored in deep Folders arrangements. ‘Again, click Yes to authenticate the process; then you can Close the installation window. © Disable path length limit Chose Windows 10 users ill now — find the installed Python a Bepionseneen 3.xwithin the Start button Recently Added section. The Fist link, Python 3.6 (32-bit) willlaunch the command line version of Python when clicked (more on that in a moment). To open the IDLE, type IDLE into Windows start How to Set Up Python in Windows (iC IF younow click on the Windows Start button again, and this ime type: CMD, you'l be presented with the ‘Command Prompt link. Click itto get to the Windows command ine environment. To enter Python within the command line, you need to type: python and press Enter. The command ne version of Python vrs in SUP HO much the same way as the Shell you opened in. Step 8 note the three left Facing arrows (>>). Whistt’s a perfectly Fine environment, it's not too user-friendly, so leave the command line For now. Enter: exit() to leave and close the Command Prompt window. z= Say Hello to Python ) How to Set Up Python on a Mac IF you're running an Apple Mac, then setting up Python is incredibly easy. In fact a AY telo lela saan ME-1 ULNA ell Cte ALR el aTelU] Rue CRTC R OUR Te) Lata leet eon INSTALLING PYTHON ‘Apple's operating system comes with Python installed, so you don’t need to install it separately. However, Apple doesn't update Python very often and you're probably running an older version. So it makes sense to check and update first. PEPER) open anew Terminal window by clicking Go> PEPER ickon the latest version of Python 3.% in our tities, then double-click the Terminal icon, Now ‘ase this isthe download button for Python 3.6.2. center: python’ ==version. You should see “Python 2.5.1" and _This will automaticaly download the latest version of Python and ‘even later, if Apple has updated the OS and Python installation. depending on how you've got your Mac configured, it automatically Ether way, it's best to check For the latest version. starts the installation wizard FSTESE RD Oren Safari and head over to www.python.ora/ PETER With the Python installation wizard open, click on downloads. Just as with the Windows setup the Continue button to begin the installation. I's procedure on the previous pages, youcan see two yellow download worth taking a moment to read through the Important Information buttons: one For Python 3.6.2, and the other for Python 2.7.13, section, in case it references something that applies to your version Note, that version numbers maybe different due tothe frequent of macOS. When reads, click Continue again releases of Python. ax a DTC Racca nae ‘The next section detals the Software License Agreement, and whilst not particularly interesting tomost folks, it's probably worth 2 read, When you're ready, click on the Continue button once again. Install button, which you need to click to start the actual installation ‘of Python 3.xon to your Mac. You may need to enter your password to authenticate the installation process. Finally you're be presented withthe amount of space Python will take up on yoursystem and an BETEED) The installation shouldn't take too long; the older ‘Mac Mini we used inthis section sa Uitte slower than more modern Mac machines and it only took around thirty seconds forthe Installation Successful prompt to be splayed, L (_How to Set Up Python on a Mac Cl ‘There's nothing much else left to doin the Python instalation wizard so you can click the Close button, IF you now drop back nto 8 Terminal session and re-enter the command: python3 =-version, you can see the new version is now listed, To enter the command line version of Python, youneed toenter: python3. To ext, it's: exit, Youneedto searchin Finder forthe Python LE Sa) when you've Found it, click it to launch and it shoul looksimiartothatof te Windows DLE version shown on the previous page. The onl difference being the Mac detected hargnare lator sunning on eee Phen 360 Set Python 2.6.8 Ged 60414706, See 222016, 17:28:38) ‘Older Mac versions may have trouble with the newer versions of Python, in which case you will need to revert to a previous Python 3.x build; as long as you're using Python 3x the code in this book will work For you. Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) [cc 4.0.1 (apple inc. build 5493)] on’ darwin Type “copyright", "credits" or "License()" for mo Fe information. Say Hello to Python How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it's often difficult to nail down just one way of doing something. Different distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial. FERED fistyounced to ascertain which version of Python EEE Some Linux distros will automatically update is currently installed in your Linux system a5 we the installation of Python to the latest versions ‘mentioned, we'e going to be using Linux Mint 18.1 for this section, whenever the system is updated. To check, First doa system update ‘As with macOS, drop into a Terminal by pressing Ctst#AtlT. and upgrade with sudo apt-get update && sudo apt-get upgrade Enter your password and letthe system do any updates. davidedavie-mine Fle Edt View Search Terminal Help FSTESE RD Next enter: python ==version intothe Terminal [ENEMA Once the update and upgrade is complete, you screen, You should have the output relating to may need to answer'Y'to authorise any upgrades, version 2.x of Python in the display. Ours in this particular case is enter: python3 =-Version to see if Python 3xis updated or even Python 2.7.12, installed. In the case of Linux Mint, the version we have fs Python 3.5.2, which isine For our purposes. davidedavid-mint File Edit View Search Terminal Help eT ST ar | aire ee wera bémpubiations.com However, if you want the latest version, 3.6.22s per the Python website atthe time of writing, you need to build Python From source. Start by entering these commands into, the Terminal: sudo apt-get install build-essential checkinstall sudo apt-get install Libreadline-gplv2-dev Libncursesn5-dev Libssl-dev libsqlite3-dev tk-dev Libgdbm-dev Libc6-dev Libbz2-dev (pen up your Linux web browser and goto SUES the Python download page: www-python.org/ downloads. click on he Download ython 362 (orwhcheve \ersonts on whenyou lok to downladthe source Python deatarcfie @ python BEAD |” the Terminal, o the Downloads folder by entering: ed. Downloads/. Then unzip the ‘contents of the downloaded Python source code with: tar” =xvF Python-3.6.2. tar. xz, Now enter the newly unzipped folder with ed Python=3.6.2/. (_ How to Set Up Python in Linux FETED) Within the Python Folder, enter: -/eonfigure sudo make aLtinstall This could alittle while depending on the speed of your computer. Once finished, enter: python3.6 =-versionto check the installed latest version. FETS forthe GUIIDLE, you need to enter the Following command into the Terminal sudo apt-get install idle3 The IDLE can then be started with the command: idle3. Note, that IDLE runsa different version from the one you installed from source. EETEERD) Youstsonced Pip (Pip installs Packages) which isa tool to help you install more modules and extras. Enter: sudo apt-get install python3-pip PIP is then installed; check For the latest update with: pip3 install upgrade pip When complete, close the Terminal and Python 3 willbe available via the Programming section in your distro's menu, ww bdmpubliations.com Getting Started with Python > rrabempubiaions.com Getting Started with Python Getting started with Python may seem alittle CTE aie LeU ee une el te} mimi Mn haces neem raed start slowly, learn how to get a result and how to get aerate eee ORC a euros Ca a ae Ee eu LL PS uA eae cet N eu Pron => Getting Started with Pytho Starting Python for the First Time We're going to be using the Raspberry Pi as our Python 3 hardware platform. The Lele cto mV Ted oem Chye)el Reel dc aie-| eR Mn eae MR Lee) ee waco oT) Cla so as long as you have a version 3 Shell, all our code will work. 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 ‘on that subject. However, once you're ready, Fire up your Pi and get ready For coding. BSP se sonnersccninil sacnie RBI ca carca nw anes 2 ED ences en Reptingtns bese edna Find the Python 3 IDLE Shel from within the Windows Start button relevant output. menu and via Finder FE Se a TT trai a “len fr are nferation. ESTEE The Shelliswhere youcanentercode andseethe [ESSAI The Python Shell acts very much lke a calculator, responses and output of code you've programmed since code is basically a series of mathematical, into Python. Tis sa kind of sandbox, where you're 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, rmultipied and so on, Siar) While that's very interesting, i's not particularly ‘exciting, Instead, try this: print("Hello everyone!”) Justlike the code we entered in Sublime inthe Installing a Text Editor section ofthis book, hiss alittle more lke it, since you've just produced your frst bit of code. The Print command is fairly self-explanatory, itprints things. Python 3 requires the brackets as ‘ell as quote marks in order to output content to the screen, in this ‘ase the ‘Hello everyone bit. >>> print("Hello everyone! Hello everyone! >>] > FETED You mayhave noticed the colour coding within the Python IDLE, The colours represent different ‘elements of Python code, They are: Bleck Data and Variables Green-Strings Purple—Functions Orange-Commands ‘Blue — User Functions Dark Red - Comments Light Red Error Messages IDLE Colour Coding [-eotour_[Tusefor [| txampies | aa me [restos [pe Tae [eereeee [ome (Starting Python for the First Time Cl FETTER) The Python IDLEis a configurable environment. IF you dont lke the way the colours ae represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don’t recommend that, as you won't be seeing the same as our screenshots, Justlke most programs available, regardless of the ‘operating system, there are numerous shortcut keys avaliable. We don't have room for them all here but within the ‘Options » Configure IDLE and under the Keys tab, you can see a list of the current bindings. STEP 9 etwas Gel Simskecme emer mae ee BETSEB) the Python DLE isa powerinterface andone that’s actually been written in Python using one of the available GU! toolkits. If you want to know the many ins and ‘outs of the Shell we recommend you take afew moments to view worw.docs.python.org/3/library/idle.html, which detalis many oF the IDLE's Features, @ Getting Started with Python Your First Code Essentially, you've already written your First piece of code with the ‘print(’Hello Se Oat curt m ad err cat hare ce es cle eC Menta eysnt cscs 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. PETESEDD "youve closed Python 3 IDLE, reopenit in FETESE DD ou con see that instead of the number 4, the Whichever operating system version you prefer. In ‘output isthe 242 you asked to be printed to the the Shell enter the Familiar Following: screen. The quotation marks are defining what's being outputted print¢*Hetlo”) tpthelDLE Sel top tetl of 202 you need remove print (2+2) ESTEEM 2ust2s predicted, the word Hello appearsin the PSTD You can continue as such, printing 2+2, 46442343 Shell as blue text, indicating output from a string, and so on to the Shel. An easier wayisto use a Its fairly straightforward and doesn't require too much explanation. variable, which is something we will cover in mace depth later. For Now try now, enter: printc*2+2") a=2 BATES What vou have done heres assign the letters ‘and b two values: 2 and 2, These are now variables, ‘which canbe called upon by Python to output, add subtract, divide ‘and soon for as long astheir numbers stay the same. Try this: printCa) print(bo) The output ofthe last step displays the current 2 them tobe printed separately. you want to add them up, youcan Use the following: print(arb) ‘This code simply takes the values of a and b, adds them together New Fle, This will open a new window ‘with Untitled as its name. This isthe Python IOLE Editor and within it you can enter the code needed to create your future programs. The IDLE Editor is, for allintents and purposes, @ simple text editor with Python Features, colour Siar ‘coding and so on; much inthe same vein as Sublime. You enter ‘code 2s you would within the Shel, so taking an example From the previous tutorial, enter: print (“Hello everyone!”) bear eden anesoeoinporroe nee execute the code you need to first save it. Press F5 and you get a ee ee ‘lick on the OK button in the Save box and select a destination where you'l save all your Python code. ‘The destination can be a deviated folder called Python or you can ust dump it wherever you like, Remember to keep a tidy drive though, tohelp you outiin the Future Entera name for your code, ‘print hello' For example, and click on the Save button. Once the Python code is saved i's executed and the output wll be detailed in the IDLE Shell n this case, the wards Hello everyone!. Ls [ie £8 Se) Sein tom Hor So Py Reamer HTT \F you open the file location ofthe saved Python code, you can see that itendsin a.py extension, ‘Thisis the default Python file name. Any code you create willbe \whateverpy and any code downloaded from the many internet Python resource sites wil be py. Just ensure that the code is written For Python 3 Saving and Executing Your Code Sia) Let's extend the code and enter afew examples From the previous tutorial: surname="Haynard” print(name, surname) print Carb) IF you press 5 now you'llbe asked to save the fil, again, as t's been modified from before. IF you cick the OK button, the file willbe ‘overwritten with the new code entries, and executed, withthe output inthe Shell It’s not a problem with just these Few lines but if you were to edit a larger ile, overwriting can become an issue. Instead, use File > Save As From within the Editor to-create a backup. STEP 9 PEPTET OR) Now-create anew file. Close the Editor, and open ‘a new instance (Fle > New File from the Shel), Enter the following and save itas hello py: a="Python” be"is” c="cool!” print(a, b, ¢) ‘Youwill use this code in the next tutorial Talo pyrene Dosmerayton Oxeelo py O42) 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, et’s see how you can run code that was made inthe GUI at the command line level. SIR hon intinus comesvith Nowyeu'eat the command ine w 1” 2, whilst the other uses the Python 3 libraries command python3 and press Enter. Ths wil put you into the ‘command line version ofthe Shell, wit the familiar three right: Facing arrows asthe cursor ‘ways with Pyu ‘and So on. Fist though, drop into the command line or Terminal on {your operating system Ea Fromhere! looked at print(a) ously, such as that it works exactly the same. Go > Utities > Terminal ora bémpubliationscom Executing Code from the Command Line roweteeptoleetieconnerdine thon EERE) Te rest aningryten 3am SIPS session and return you back to t SUBS Python 2 command line is quite obvious. Whilst it prompt. Enter the Folder where you sa rom the doesn't error out in any way, due to the differences between the previous tutorial andlistthe available files within; hopefully you way Pythan 3 handles the Print command over Python 2, the result should see the hello. file isn’t as we expected, Using Sublime for the moment, open the hello.py fie FEED Fromwithin the same folder as the code you're PEPER Since Sublime Text isnt available forthe Raspberry going to run, enter the Follawing into the Pi, you're going to temporarily leave the Pifor the command tine: ‘moment and use Sublime as an example that you don't necessarily n IDLE. With the hellopy file open, alteritto reed to use the P include the Following: python3 hello.py This will execute the code we created, which to remind yous J es naw nput "What is your name? “) ‘a="Python” printC*Hello,”, name) > c="cool!” zs print(a, b, ¢) Naturally since thisisPython 3 code, using the (RII ae the ep le and drop backs the aiienha usu loka mabersestinast Meu lea kyeemne | sede vith then 2 y enter python3 hello.py python hello.py The result willbe the original Python is cool statement, together with the added input command asking you for your name, and clsplaying it in the command window. wv bdmpubliations.com @ Getting Started with Python Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the Reese aE Meese ene nice eee stem el can work within the IDLE Shell or in the Editor, whichever you like. IT’S ALL MATHS, MAN ‘You can get some really impressive results languages, maths is the driving force behind the code. FETED Per up the Gul version of Python 3, as mentioned you can use either the Shell or the Editor. For the time being, you're going to use the Shell ust to warm ourmaths muscle, which we believe isa small gland located at the back of the brain or not). PEER the shell enter the following: 22 54356+34553245 (99867344*27344484221 ‘You can see that Python can handle some quite large numbers. the mathematical powers of Python; as: ‘most, ifnot all, programming BSED) ou con use all the usual mathematical operations: New Fe) and create a simple variable and ‘anergy hoplOcouran/PytonComtanmregy@a2) ~ 8 Lie E6t Fama sore wre He BRTeED Rennina the code will return the ine: The value of A 's, 10 nto the IDLE Shell window, which is what we ‘expected. Now, add some ofthe types of comments you'd normally ‘see within code: # Set the start value of A to 10 010 # Print the current value of & print(“The value of A is,”, a) Resave the code and execute it: You can see that the ‘outputin the IDLE Shellisstil the same as before, despite the extra lines being added, imply put, the hash symbol (#) denotes ane of text the programmer can insert to inform them, and others, of what's going on without the user being aware. hon 342 Sat PEPTSPDD ct's2ssume thatthe variable A that we've created isthe number of tivesin a game. Everytime the player des, the value is decreased by 1. The programmer could Insert a routine along the lines of: a=a-1 print(*You’ve just lost a life!”) print(*You now have”, a, “Lives left!”) Whilst we know that the variable is tives, and that the player hasjust lost one, a casual viewer or ‘someone checking the code may not know. Imagine for a moment that the code is twenty thousand lines long, instead of just our seven. You can see how handy comments ae. Siar # Set the start value of A to 10 010 # Print the current value of A print(*The value of A is,”, a) # Player lost a Life! na-1 # Inform player, and display current value of A lives) print¢*You’ve just lost a life!”) print¢“You now have”, a, “Lives Left!” Essentially, the new code together with comments could look ike: You can use comments in different ways. For ‘example, Block Comments are a large section of text that details what's going on inthe code, suchas telling the code reader what variables you're planning on using: # This is the best game ever, and has been developed by a crack squad of Python experts # who haven’t slept or washed in weeks. Despite being very smelly, the code at Least # works really well. Using Comments Cl Inline comments are comments that Follow a section (of code. Take our examples from above, instead of Sia) inserting the code on a separate line, we could use: a=10 # Set the start value of A to 10 print (“The value of A is,", a) # Print the current value of A a=a-1 # Player lost a life print(*You've just lost a life!”) print(*You now have”, a, “Lives left!) # Inform player, and display current value of A (lives) ‘The comment, the hash symbol, can also be used to ‘comment out sections of code you don't want 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) STEP 9 Ele Eat Format Bun Options windows Help 7 Set the start valuw of A to 10 19) rane She curcane yun of A # print "The value of A is,", 2) # Fiayer lose'a Tite! # Inform player. and display current value of & (1ives) prant("rou've just lost a life!) Print(-You non have", 8, “Lives left!) PEPER) You also use three single quotes to comment ‘outa Block Comment or multitine section of comments. Place them before and after the areas you want to comment for them to work This is the best game ever, and has been developed by a crack squad of Python experts who haven’t slept or washed in weeks. Despite being very smelly, the code at least works really well. Sey oe Po @ Getting Started with Python Working with Variables eee ecu Ckm Ue Cantatas ei ea ta oe es Meramec ene arnberces tu ss uetet cil ITA cok RVI 10) VARIOUS VARIABLES ‘You'll be working with the Python 3 IDLE Shell in this tutorial. you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. insome programming languages you're required touse dollar sign to denote a string, which is 2 variable made up of multiple characters, such as a name of a person. In Python ths isnt necessary. For example, inthe Shell enter: rname="David Hayward” (or use your own name, unless you're also called David Hayward). {ie Est Oot Gt ro eae BETTER You can check the type of variable inuse by [ssuing the type () command, placing the name of the variable inside the brackets. In our example, this would be: ‘type Cname). Adda new string variable: titLe="Descended from Vikings”. You've seen previously that variables can be concatenated using the plus symbol between the variable names. In our example we can use: print Chame + *: + title). The middle part between the quotations allows us to adda colon and a space, as variables are connected without spaces, so we need to add them manually He 5 Sh Se ane Meso EA PPD Youcanalco combine variables ‘within another variable. For ‘example, to combine both name and title variables into a new variable we use oe at Beg ge He charactersname + “: “+ title “Then output the content of the new variable as: print (character) Numbers are stored as different variables: age=44 Type Cage) Which, as we know, are integers However, 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 one into the ‘other or vice versa, When you do try to combine bath, you get an ‘error message: print Crane + age) Siar This @ process known as TypeCasting. The Python codeis: print (character + “ is “+ str(age) + “ years old.) ‘or you can use: print (character, “is, age, “years old.”) Notice again that in the last example, you don't need the spaces between the words in quotes as the commas treat each argument to print separately >>> print (name + age) Traceback (nose recent call Last): Pile “ prin’ (name + age) Typetrror: can't convert “int* object to str inplicitly S8Sprane (character # 3s"! + str(age) +" years eld." David Hayward: Descended fron Vikings 1s 44 years eld. So print (character, "is", age, “years 0 David Hayword: Descended trom Vikings. is D3 > years ol. center: ‘age= input C“How old are you? “) All data stored from the Input command is stored as string variable. Ele Es Shel Rebug ato wrdows Lp Ta (Seta Ook 19 0, TITTY ‘Another example of TypeCasting is when you ask for input from the user, such asa name. For example, Working with Variables ( CG ‘This presents a bit ofa problem when you want to ‘work with anumber 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: intCage) + 10 ‘This wil TypeCast the age string into an integer that can be ‘worked with, Sia) ‘The use of TypeCasting is also important when dealing with Floating point arithmetic; eemember: ‘numbers that have a decimal point in them. For example, enter: shirt=19.99 Now enter typeCshiirt) and you'l see that Python has allocated the number 3s a float, because the value contains 3 decimal point. STEP 9 2 (dataalt, Oct 19 2004, 1353 tion Liman clas feats wo BERET RM When combining integers and floats Python Usually converts the integer to a Float, but should the reverse ever be applied it's worth remembering that Python doesn't return the exact value. When corwerting a loatto an integer, Python will always round down to the nearest integer, called truncating; in our case instead of 19.99 it becomes 19. ee ‘le Eat Shel Debug Options indows Help FFB aD Eee eae oem Seas Ze aetes aa, : 2, @ Getting Started with Python User Input eens ratecmmc eran tctes iMeNCURm ocr CeCe ate c en Mareen C camry eta eee acid 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. Fit’s not already, open the Python 3 IDLE Shell, Sica and start a New Filein the Editor Let's begin with ‘something realy simple, enter: print¢*Hetto”) firstnanesinputC‘What is your first name? “) print(*Thanks.*) surnane=input(“And what is your surname? ‘Save and execute the code, and as you already no SEP2 doubt suspected, in the IDLE Shell the program will askfor yours name storing asthe variable fsiame followed byyoursumame; ao storedin sown variable uname |e at Set Om pr Hem Now that we have the user’s name stored ina ‘couple of variables we can call ther up whenever we want, print(*Welcone”, firstname, surname, “ you're well. today.”) T hope Run the code and you can see a slight issue, the fullstop after the surname follows a blank space. ‘To.eliminate that we can add a plus sign instead of the comma in the code: printC‘Welcome”, firstname, surnanet. I hope you're well today.) FETED You don't always have to include quoted text wit the input command, For example, you can ask the User their name, and have the inputn the line below: print(“Hello. What’s your nane?”) namesinputQ userinput py -/home/pi/Documents/Python Codes le Edt Farmat sun Qptions windows Hep Fant (“Hel ames np Wat's Your name?) The code from the previous step i often regarded {as being a litle neater than having alengthy ‘amount of text the input command, butts nota rule that's set in ‘stone, 0 do 2s you lke in these situations. Expanding on the code, try this print(“Halt! Who goes there?”) ‘name=input() User Input ‘What you've created here is aconeition, which we will cover soon. n short, were using the input from the user and measuring itagainsta condition. So, ifthe user enters David as their name, the guard wil allow them to pass unhindered, Else if they enter a name other than David, the guard challenges them toafight. FETED ust2s you learned previously, any input froma user is automaticaly a string, so you need to apply 2 ‘TypeCastin order to turn itinto something else. This creates some interesting additions to the input command. For example: # Code to calculate rate and distance printC*Input a rate and a distance”) rate = floatCinput(“Rate: “)) PEPID 2 good start toa text adventure game, pechape? [Now you can expand on it and use the raw input From the user to flesh out the game alittle: if nane=="David”: print(‘Wlelcone, good sir. You may pass.”) else: print(*I know you not. Prepare for battle!” ‘setepupy-amelp/Doaurans/Pyon Cosehsemptpy(s4z) = © ™ Gat Fame in eto from te PEPPER Tofinalise 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 Float{input element, we've told Python that anything enteredis a Floating point number rather than a string, @ Getting Started with Python Creating Functions Nears eh uses tee g ur eral ana n eel rele Team ee Cute eet eee inten Mao Taen Cocke marten ones FUNKY FUNCTIONS ‘Afunction is a 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. I's not ust data thata function works on, They can do all manner of useful things in Python, such as sort data, change items From one Format to another and check the length or type of items. Basically, a Function is ashore word that's Followed by brackets. For example, len), ist() or type(). ER TeGEED 4 function takes data, usually a variable, works on it depending on what the Function is programmed to do and,eturns the end value. The data being worked on goes inside the brackets, so if you wanted to know how many letters ‘are in the word antidisestablishmentarianism, then you'd enter: ‘TenC“antidisestablishnentarianism™) and the number 28 ‘would return, ESTEE) ou con pass variables through functions in much the same manner, Let's assume you want the numberof letters in a person's surname, you could use the Following code (enter the text editor For this example) nanesinput (“Enter your surname: “) count=Len(nane) print (“Your surname has, count, “Letters in = Press F5 and save the code to execute it. Python has tens of functions built into't, Far too ‘many to get into in the limited space available here. However, to view thelist of bul-in Functions avalable to Python 3, navigate to wwrw.docs.python.org/3/library/functions.html. These are the predefined functions, but since users have created many ‘more, they/re not the only ones available. Siar ‘Additional Functions can be added to Python 0 ‘modules available that can cover numerous programming duties. “They add functions and can be imported as and when required. For ‘example, to use advanced mathematics Functions enter: ‘import math (Once entered, you have access to all the math module Functions. FORGING FUNCTIONS BETTS) 0 vse a function from a module enter the name of the module Followed by afull stop, then the name of the Function. For instance, using the math module, since you've just imported it into Python, you can utlse the square root function, Todo so, enter: math. sqrt(16) You can see that the code i presented as module function(data). Br era nee eau ue ue cc keane Peer eee ei tsetse enter erent ee gre eee ge ea Core iieme ne eter ite, STEP 1 Enter IdeF Hel 1o0):) fai) ress F5 to save and run the script. type in Hello() and itreturns the new Function perros Idef_HelloCname) :} print CHeTlo™ name) mee eee teensy Sree eee atte ent Pea eee eee ene et Ts STEP3 Se see the last line in the script and press CtilsS to save eres eer ee eats Css From the Nau r Sa: Tee cn eter eels oe Ce ues @ Getting Started with Python Conditions and Loops eon ese Ce Ser MaPaue Ce MCR Ren eee Umea atta suh eatin yeu ten atl) achieve; they could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking if something is TRUE, then doing something else iF itisn’t. PETER DD Lets create a new Python program that will ask the user to input aword, then checkitto see iF it's ‘a fourletter word or not. Start with File > New File, and begin with the input variable: wordsinput(“Please enter a four-letter word: “) Now wecan create a new variable, then use the en SUEP2 function and pass the word variable through it to ‘get the total number of letters the user has just entered: word=input(“Please enter a four-letter word: “) word_length=Len(word) 40 Now you can use an fstatementto check ifthe ‘word length variable is equal to four and print a Friendly conformation ifit applies tothe rule: wordsinput(“Please enter a four-letter word: *) word_length=Len(nord) if word_length == print (word, “is a four-letter word. Well done.”) ‘The double equal sign something else. Sse} ‘means check if something is equal to ‘The colon at the end of IF tells Python thatif this statement is true do everything after the colon that’s indented. Next, move the cursor back to the beginning of the Editor: Siar wordsinput(“Please enter a four-letter word: “) word_length=LenGnord) if word_length == 4: print (word, “is a four-letter word. Well done.") else: print (word, ‘s not a four-letter word.") STIS P1es5F5 and save the code to execute it. Enter ‘a fourletter word inthe Shell to begin with, you should have the returned message that it's the word is four letters Now press FS again and rerun the program but this time enter a Five-letter word, The Shell wil display that it’s not a four-letter word LOOPS. loop looks quite similar to a condition but they are somewhat block oF code a number of times, usually with the support of ace eee ee ates eer en a arnt See eee eg erect eee STEP 2 Rouge Coat eet eae ants lue of x, then adds Now expand the code to include another conditions 10 added acondition for three-letter words: wordsinput(“Please enter a four-letter word: “) word_Length=Len(word) if word length == 4: print (nord, “is a four-letter word. Well done.”) elif word_tenath print (word, “is a three-letter word. Try again. else: print Cnord, “is not a four-letter word.”) Cae eC ted ee gis Pemiesres For word in words: print nord)) The For loop Co STEP 4 ee neers Boe or x in range (1, 10):) print Co) pei ae Cee eee numbers used. oT Conditions and Loops Cl 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 ‘though good the bln functions within Python Bua? il are limited. The use of modules, however, allows us. are Python scripts that are imported, uch as import math, FeyeeE Some modules, especially on the Raspberry Pi are included by default, the math module being a prime example. Sadly, other modules aren't always available. A good «example on non-Pi platforms the pygame module, which contains ‘many Functions to help create games. Try: import pygame, ora bémpubliationscom Ez» e results an error inthe IDLE Shell as the ygame mod! ognised or installed in Python. To install a module we can use PIP Pip Installs Packages) Close down the IDLE Shell and drop into a command prompt or Terminal session. Atan elevated admin command prompt, enter: pip install pygane Windows users can search For CMD via the Start button and right click the result then click Run as Adminstrator. Linux and Mac users can use the Sudo command, with sudo pip install package, Python Modules Siar ‘import. pygane, the module willbe imported into the code without any problems. Youll find that most code downloaded or ‘copied From the internet will contain a module, mainstream of Unique, these are usually the source of errorsin execution due to Close the command prompt or Terminal and relaunch the IDLE Shell. When you now enter: them being missing Dinentae ‘we've previously experimented with. For example: ‘import random The modules contain the extra code needed to achieve a certain result within your awn cade, as 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(1, 25)) ae ‘This code, when saved and executed, will display ten Sis random numbers from 1 to 25. You can play around ‘with the code to display more or less, and from a great or lesser range. For example: ‘import random for i in range(2s): print(random.randint(1, 100)) ‘Multiple modules can be imported within your code, Sia) To.extend our example, use: ‘import random ‘import math for I in range(s): printCrandon.randint(1, 25) print(math.pi) ae ‘The result sa string of random numbers followed by the value of Pias pulled from the math module Using the print(math.p}) function. You can also pullin certain Functions from a module by using the from and import commands, such as: STEP 9 from random import randint for i in range(s): printCrandint(1, 25)) ‘This helps create a more streamlined approach to programming, You can also use import module*, ‘which wil import everything defined within the named module, However, it's often regarded as a waste of resources but it works nonetheless. Finally, modules can be imported as aliases: ‘import math as m print(m.pi) Of course, adding comments helps to tell others what's going on, itintny Cinema BA Say Hello tol@: lore ce teem eae terete used ina multitude of technologies. Everything enact eteice ea ra Le EC ue eer aa) lereitraCecomatee oe cnn POE Wek cee ore Mone en Goat e a use on a daily basis, which makes it a complex and eee ecneene te cer ett ai PR eu ee ae cole ke Plead CRON Re wovwbdmpubleationscom Why C++? C++ is one of the most popular programming languages available today. Originally leReeheces mar Teule tee Recta Kena ceM eet nucle original C language andis a general purpose object-oriented (OOP) environment. 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 backto 1979, the start ofthe golden era of home ‘computing labs and by requiar people who didnt have access to the ‘computing, C++, or rather C with Classes, was the brainchild of ‘mainframes and large computing data centres, Danish computer scientist Bjarne Stroustrup while working on his PhO thesis. Stroustrup's plan was to further the original Clanguage, _C++'simpactin the digital word is immense, Many ofthe programs, ‘hich was widely used since the early seventies. applications, games and even operating systems are coded using C++. For example, allof Adobe's major applications, such as| ‘Ct+ proved to be popular among the developers of the ‘80s, Photoshop, InDesign and so.on, are developed in C++. You wil find since it was a much easier environment to get to grips with and that the browser you suf the Internet with fs written in C++, a more importantly, was 99% compatible with the original C ‘well as Windows 10, Microsoft Office andthe backbone to Google's language. This meant that it could be used beyond the mainstream search engine, Apple's macOS is written largely in C++ (with some GS ‘cos code is much Faster than that of Python. a #include 2 | using namespace std; 3 | void main() 4 |Dlchax ch; 5 cout<<"Enter a charater to check it is vowel or not"; 6 cin>>ch; 1 switch (ch) 8 jo ( 3 case'a': case'A': 10 cout< App Store. nthe Search box enter ‘Xcode’ then turnsinto install App. Enter your Apple ID and press Retumn, There are many suggestions filing the App Store and Xcode begins to download and install. may take some time ‘window but it's the first option, Xcode, that you need to clickon, depending on the speed of your internet connection, Leet Se S"@S "Gs" ss ERED T2kea moment to browse through the app's ESTEEM When the installation is complete, click on the Information, including the compatbilty, to ensure ‘Open button to launch Xcode. Click Agree to the ‘you have the correct version of macOS. Xcode requires macOS. licence terms and enter your password to allow Xcode to make 10,12.6 oF later to install and work, changes tothe system, When that is done, Xcode begins to install additional components. With everything now installed, including the Siar ‘additional components, Xcode launches, displaying the version number along with three choices and any recent projects that you've worked on; witha fresh install though, this is blank, \Wetcome io Xeade sBEBOSROSR Te. Eamonisetosoosn Ganencie Fillin the various fields but ensure that the Language option atthe bottoms set to C+; simply ‘choose it from the drop-down lit. When you've Filed in the Fields, ‘and made sure that C++ isthe chosen language, click on the Next button to continue. How to Set Up C++ on a Mac STEED The next step asks where to create a Git Repository for al your Future code. Choose a location on your Mac, or a network location, and click the Create button, When you've done al that, you can star to code. The left-hand pane details the files used in the C=++ program you're coding. lick on the mmain.cpp filein the lst. Youcan see that Xcode has automatially Sua) completed a basic Hello World program For you. ‘While it may not make much sense at present, you will discover more as you progress, the content is just Xcode utilising what's inatableon the Mac \When you want to run the code, click an Product > Run. You may be asked to enable Developer Mode fon the Mac; thsis to authorise Xcode to perform functions without needing your password every session, When the program executes, the outputs displayed at the bottom ofthe Xcode window. Say Hello to C++ | How to Set Up C++ in Linux Linux is a great C++ coding environment. Most Linux distros already have the essential CeoTa Noodle Pesala (emo Reo nM OL Nae eee Noe (cn acele entering code into, including colour coding; and there's tons of extra software available to help you out. LINUX++ If you're not Familiar with Linux, then we recommend taking a look at one of our Linux titles from the BDM Publications range. IF you have a Raspberry Pi, the commands used below work just Fine and for this example we're using Linux Mint. BETEGEED The first stepis to ensure Linuxis ready foryourC++ ERE Amazingly, that'sit. Everything is already for you code, so check the system and software are up to tostart coding. Here's how to get your first C++ date. Open 2 Terminal and enter: sudo apt-get update && sudo apt- program up and running, In Linux Mint the main text editors Xed, ‘get upgrade. Then press Return and enter your password. These which you can launch by clicking on the Menu and typing Xed into ‘commands update the entire system and any installed softwere, _the search bar. Clickon the Text Editor button in the right-hand pane toopenit. ete Wow Search Temi Hp BREED Most Linux distros come preinstalled with all PETER 19 Xed, or any other text editor you may be using, the necessary components to start coding in center the lines of code that make up your C++ Hello C++; however it's always worth checking to see if everything World program. t's litle different to what the Mac produced: ispresent, Stil within the Terminal, enter: sudo apt-get. install build-essential and press Return If youhave the right ‘components nathing is installed iFyou're missing some then they int main) are installed by the command, i /My first C++ program std::cout << “Hello World!\n"; } Aeaj-~|xoe aa #include » FTI Wren you've entered your code, click File > Save As ‘and choose a folder in which to save your program, Name the file as helloworld.cpp (it can be any name as long ast has ‘cpp as the extension) lick Save to continue. The frst thing to notice that xed has SUES automatically recognised this as a C++ file, since the file extension is now set to.cpp. The colour coding is present in the ‘code and f you open up the file manager you can also see that file's icon has C++ stamped on it. Fea AD ith 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 sin the Documents Folder, so we can navigate to it by entering: ed Documents. Remember, the Linux Terminals case sensktive, so any capitals must be entered correctly ( How to Set Up C++ in Linux Before you can execute the C++ ile ou need to compile itn Linux its common to use g++, en open source C+ compiler as you're now inthe same folder asthe C++ file, enter: g++ helloworld.pp i the Terminal and press Return PEPER [takes 2 short time while the code is compiled by g++ but providing there are no mistakes or errors in the code you are returned to the command prompt. The compiling of the code has created a new file. ou enters into the Terminal you can see that alongside your Cr+ file is a.out, FETSERB) the 2.0utfileisthe compiled C++ code. Torun the code enter: a.out and press Return. The words ‘Hello World! appear on the screen, However, 2.0ut isn’t very friendly. To name it something else post-compiling, you can recompile with: g++ helloworld.cpp-o helloworld. This creates an ‘output file called hellowarld which can be run with: /helloworld Other C++ IDEs to Install TaOUM Na ole carne een oa arn Neti cme Meant plenty of options available to you. Windows is the most prolific platform For C++ IDEs but there are plenty For Mac and Linux users too. DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but find the one that ‘works best for you. Eclipses a hugely popular C++ IDE that offers, CCodelite sa Free and open source IDE that’s the programmer a wealth of Features. thas a regularly updated and available for Windows, ‘reat, clean interface, i easy to use and avaiable For Windows, Linux and macOS. t's lightweight, uncomplicated and extremely Linux and Mec. Head overto www.eclipse.org/downloads/ to powerful. You can find out more information as well ashow to download the latest version. I you're stuck, click the Need Help ink download andinstallit at www.codelite.ora/. for more information. \Viinipesleeue® PENT The GNAT Programming Studio (GPS)isapowerfl — RERESNNEMS Another popular choices NetBeans. This, and intuitive IDE that supports testing, debugging isanother excellent IDE that’s packed with ‘and code analysis. The Community Edition i free, whereasthe Features and apleasure touse. NetBeans IDE includes project based Pro version costs; however, the Community Editions avallable for templates or C++ that ive you the ability to bulé applications with ‘Windows, Mac, Linux and even the Raspberry P.You can find tat dynamic and static libraries Find out more at www.netbeans.org/ ‘worw.adacore.com/download. Features/epp/index html. Microsoft's Visual Studios 2 ‘mammoth C+ IDE that allows you tocreate applications For Windows, Android, iOS and the web, The ‘Community version iFree to download and install tthe other ‘versions allow a free trial period, Go to www.visualstudio.comy to see what t can do for you. ‘This cross-platform IDE is designed to Queue create C++ applications for desktop and tbe environments comes wth code edtr and integrated tools For testing and debugging, as well as deploying to you chosen platform. snot fre but there ia tal period on oer before requiring purchasing: www.qt.io/qt-features-libraries-apis-tools- and-ide/. Bloodshed Dev C++, despite its colourful name, isan older IDE thats for Windows systems only. However, many users praise its clean interface and uncomplicated ‘way of coding and compiling. Although there's nt been much Updating for some time, it’s certainly one to consider if you want something different: www.bloodshed.net/devepp.html, Other C++ IDEs to Install ( c mm “The Anjuta DevStudio is a Linux-only IDE that Features some of the more advanced Features you ‘would normally Find in a paid software development studio, There's 3 GUI designer, source editor, app wizard, interactive debugger and ‘much more. Go to wwwanjuta.org/ For more information, rs aa. i Hn i if =e This excellent DE allows developers MONODEVELOY, towrite C++ code For desktop and ‘web applations acossallthe major platforms There's an advanced text editor, integrated debugger and a configurable workbench to help you create your cade. I's avallable For Windows, Mac and Linux andi Free to download and use: www.monodevelop.com/. Ultimater+ isa cross-platform Cr+ IDE that boats a rapid development of code through the smart and agaressive Use of C++. For the novice it’s a beast of an IDE but behind its complexity is a beauty that would make developer's knees go "wobbly, Find out more at www.ultimatepp.org/index.html ® eC Fundamentals Rese NR Ce structure of C++ code and how to compile and execute that code. These are the Fundamentals of C++, which teach you the basics such as using comments, variables, re Re EU Me one eC elo Rees ie er ens ceca ie COU ene tree ae ss to the screen and store and retrieve data. Z=> C++ Fundamentals) Your First C++ Program SEM e cur cortege ariel dol Men etc Usic Mann ote Kellen: ere tance lees) Mace enc iecun ec mcr ecm ena cn 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 BCPL. FSTeEED mentioned, we're using Windows 10 and the ESTEE the moment it doesnt look tke much, and latest version of Code:Blocks forthe rest of the C++ it makes even less sense, but welll get to that ‘code inthis book. Begin by launching Code:.Blacks. When open, click _ in due course. Now click on File > Save File As. Create or finda ‘on File > New > Empty File or press Crl+Shift+N on the Keyboard. suitable location on your hard drive and inthe File Name box, cal ithelloworld.cpp. Click the Save as type box and select C/C++ ile. Click the Save button, Bree Now you can see ablank screen, with the tab PePTP DM You can see that CodeBlocks has now changed labelled *Untitiedt, and the number one in the top the colour coding, recognising that the fileis now leftof the main Code:Blacks window. Begin by clicking inthe main C++ code. This means that code can be auto-selected from the ‘window, so the cursor is next to the number one, and entering: Code:.Blocks repository. Delete the #nclude line and re-enter it, You can see the auto-select box rin ea re-enter it, You can see the auto-select boxes appearing. 6 ‘Auto-selection of commands is extremely handy and cuts out potential mistyping, Press Return to get to Siar line 3, then enter: int mainc) Note: there's no space between the brackets Pslmnclalal Gia s kle BETTIE On the next tine belowint maind, entera curly bracket: i ‘This can be done by pressing Shift and the key to the right of Pon an. English UX keyboard layout. asir- C++ Fundamentals) Structure of a C++ Program (eS SICEE RN Ree e en ae Care MWA eRe ee ULE ealiare Kol eA) as small as a semicolon, and your entire program will Fail to be compiled and executed. Many a professional programmer has fallen Foul of sloppy structure. #INCLUDE 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. in #INCLUDE [Sarthe] *helloworkdcop x ‘The structure of a C++ program Is quite precise. Every C++ code Finclade “clostecme, begins witha directive: include ‘©. The directive instructs the pre-processor to include a (C++ was invented by Danish student Bjarne Stroustrup in 1979, asa pattof his PD. thesis. ntially C+ was called C 1 iz 3 4 5 é vith Clases whchadded —£secionof the standard e+ + features to the already popular code. For example: #include: Cprooramminglanquage,” :lostream> ncudesthe E whiemangicamore £ iosresmhesdetosippor. E sertiendlenarorment £inputfoutut operations trroughanew srt ‘Bjarne Stroustrup, inventor oF C++, INT MAIN() [Sterthere 9<¢) *helloworld.cpp >< int main() initiates the declaration ofa Function, which is a group of code statements under the name ‘main’. All C++ code begins atthe main Function, regardless of where it ‘actually lies within the code. Bi #include int main() rt ame ene COMMENTS, Lines that begin with a double slash are comments.This means they ‘wor't be executedin the code and are ignored by the compiler. ‘Comments are designed to help you, or another programmer looking at your cade, explain what's going on. There are two types ‘of comment: * covers multiple line comments, //asingle line. Lines that begin witha double slash are comments, This means they won't be executed in the code and ~are ignored by the compiler ‘Comments are designed Vinclede cLereseam> tohelp you, or another programmer looking at iat nant) your code, explain what's fe ‘going on. There are two types of comment: /* covers , multiple ine comments /@ single tne STD ‘While std stands for something quite different, in C++ it means. ‘Standard, I's part ofthe Standard Namespace in C++, which covers ‘a number of different statements and commands, You can leave the stdz part out of the code but it must be declared at the start with: ‘using namespace std; not both, For example: #include using namespace std; lease COUT In this example we're using cout, whichis part ofthe Standard Namespace, hence why ts there, as you'e asking C++ to use it from that particular namespace. Cout means Character OUTput, which splays, or prints, something to the screen. Fwe leave std: out we have to declare i atthe start ofthe code, as mentioned previously Structure of a C++ Program Cl << ‘Thetwo chevrons used here are insertion operators, This means that whatever follows the chevronsis to be inserted into the std:cout statement. inthis case theyre the words Hello, world, which are tobe displayed on the screen when you compile and execute the code, OUTPUTS Leading on, the “Hello, world" partis what we want to appear on the screen when the code is executed. You can enter whatever you like, as long ast’ inside the quotation marks. The brackets aren't needed but some compilers insist on them. The \n part indicates 8 newline sto be inserted. cout << "Hello, world!\n" ; AND} Finally you can see that lines within a function code block except comments) end with a semicolon, This marks the end of the statement and all statements in C++ must have one at the end or the compile Fails to build the code. The very last line has the closing brace to indicate the end of the main function. finclude using namespace std: int main() ‘include using namespace tai int masa() cout << "Hello, world! \n’ eI Z=> C++ Fundamentals) Compile and Execute So Rec Meet MOU renee ets at ars Rete Sige Riel ged uae Rau ee emma elena nereeas ec na cee GREETINGS FROM C++ Compiling and executing C++ code From Code::Blocks is extraordinarily easy; ust a matter of clicking an icon and seeing the result. Here's how it’s done. ‘Open Coder:Blocks, if you havent already, and (oad up the previously saved Hello World code you ‘created. Ensure that there are no visible errors, such as missing semicolons atthe end ofthe std:cout line. ESTED #\n" using namespace std; ‘Then, delete the sta: part of the Cout line; ke so cout << “Hello, world\n"; > | erin 2 using namespace std: 3 4 int ming) eco 2 Be 3 “ € Pe ceacany 7 || cout C++ Fundamentals) Using Comments While comments may seem like a minor element to the many lines of code that combine to make a game, application or even an entire operating system, in actual Fact Nt keen maaan ene econ THE IMPORTANCE OF COMMENTING ‘Comments inside code are basicaly human readable descriptions that detail what the code is doing at that particular point, They don’t ‘sound especially important but code without comments s one of the many frustrating areas of programming, regardless of whether ‘you'r a professional or ust starting out. In short all cade should be commented in such a manneras to effectively describe the purpose of ane, section, or individual ‘elements. You should get in tothe habit of commenting as much as possible, by imagining that someone who doesn't know anything ‘about programming can pick up your code and understand what i's ‘going to do simply by reading your comments. Ina professional environment, comments are vital to the success ‘of the code and ultimately, the company. In an organisation, many programmers workin teams alongside engineers, ather developers, hardware analysts and so on. iF you're a part ofthe team that's ‘writing a bespoke piece of software forthe company, then your ‘comments help save a lot of time should something go wrong, and ‘another team member has to pick up and follow the tral to pinpoint the issue, Place yourselFin the shoes of someone whose job it sto find out ‘what's wrong with a program. The program has in excess of 800,000 lines of code, spread across several different ‘modules. You can soon appreciate the need fora little help From the original programmersin the form of 3 ‘good comment. ‘The best comments are always concise and link the code logically, detaling what happens when the program hits this line or section. You dont need tocomment onevery ine. Something along thellines of iF doesn't require you to ‘comment that ifx equals zero then do something; that’s going to be obvious to the reader. However, if x equaling zero issomething that drastically changes the program forthe user, such as, they've run out of lives, thenit certainly needs to commented on. Even f the codes your own, you should write comments asif you |were going to publicly share it with others, This way you can return to that code and always understand whatit was you did or where it ‘was you went wrong or what worked brilianty. Comments are good practise and once you understand how to add a comment where needed, you soon doit asifit's second nature, ( Using Comments Cl C++ COMMENTS, You've already seen some Commenting in C++ involves using a double Forward slash /, or a Forward slash and an asterisk, brief examples but this is how they work. FSTESEDD Usiathe Hello world code asanexample,youcan — REEWAR e careful when commenting, especially with block easily comment on different sections of the code ‘comments. I's very easy to forget to add the closing using the double forward slash asterisk and forward slash and thus negate any code that falls inside the comment block My first. C++ program cout << “Hello, world!\n”; 1 finciede Gosrcam 2 using namespace sta: 4 _sne main s ot ‘ Z]] ome mus wena ° a by a n BREED ‘However youcan alsoadd comments otheend ETERS Obviously if you try and build and execute the of line of code, to describe ina better way whats codeit errors out, complaining of a missing curly ‘ing on: bracket to Frish of the block of code. IFyou've made the me , few times, then it can be time consuming to go back and cout << “Hello, world!\n”; //This line outputs the “'01? words "Hello, world!”. The \n denotes a'nen Line, S Tantfuly: the colour codingin CodeBlocks hes deny Note, you don’t have to put a semicolon atthe end of a comment: ‘This is because it's aline in the code that'signared by the compiler. PETER ou con comment out several tines by using the FETED youre using block comments i's good practise forward slash and asterisk: in C++ to add an asterisk to each newline of the ‘comment block, This also helps you to remember to close the acon comment block off before continuing wth he code: without the need to add more slashes */ /* This comment con +" cover several lines 2tsteenebet ih hee comment pps ce au fl ‘Sot << “nt greeeinge from Cova" 3 zl 5 BP mene ne et Z=> C++ Fundamentals) Variables Variables differ slightly when using C++ as opposed to Python. In Python, you can simply state that ‘a’ equals 10 anda variable is assigned, However, in C++ variable has to be declared with its type before it can be used. THE DECLARATION OF VARIABLES ‘You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can declare. Here's how it works. ESTER pen upa new, blank C++ ile and enter the usual code headers: #include using namespace std; int main@) { } "Sethe %c| Variablescpp >! ‘inciuae ec , BTeSER You can build and run the code but twon't do much, other than store the values 10 and 5 tothe integers a andb. To output the contents ofthe variables, add cout << a; cout << "\n"; cout << bi The cout << "\n'spart simply places. new tine between the output of toands, PRPTSED star simple by creating two variables, a andb, with ‘one having value of 10 and the other S. You can Use the data type int to declare these variables. Within the curly brackets, enter int a; int bs a= 10; wstog namcepane sta bas; ine main() 1 FETED Naturally you can declare a new variable, call it result and output some simple arithmetic. int result; result = a +b; cout << result; Insert the above into the code as per the screenshot.

You might also like