Download as pdf
Download as pdf
You are on page 1of 80
C++ & Python eM Rel meme eee ers on s&s Readly now! Customising & Powering up Windows 11 www.bdmpublications.com 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? 40 Equipment You will Need 12 Getting to know Python 14 Howto Set Up Python in Windows 16 _ How to Set Up Python on a Mac 18 _ Howto Set Up Python in Linux EPS US lcd } 20) Getting Started with Python 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 TA C++ Maths 38 Creating Functions 40 Conditions and Loops 42 Python Modules ° 46 WhyCH? 48 Equipment Needed 50 Howto Set Up C++ in Windows 52__ Howto Set Up C++ on aMac 54 Howto Set Up C+ in Linux 56 Other C++ IDEs to Install worn bmoubiations.com ( Contents xémpubliations.com ‘ww bdempublications.com F Say Hello to Python) Say Hello to Python BE cud ee ae OC el CCU eee Ere oe ie incredibly powerful and some are extremely basicand used as minor utilities For operating systems. Python sits somewhere in the middle, combining ease of use RET Cue UT Pg cn ne to create minor utilities, a range of excellent games and Rouen nce os Deen eeu arate ae Ne) another programming language. It hasa vibrant and lively community behind it that shares knowledge, code and project ideas; as well as bua Fixes for Future eereee re ne asc eee ee nu neem eer Peter e ei cura n as SRa eae ruse ee ranean ty Dre ee Smash) functions and features of the language. Before long, Perce meaner ice enero ake ee eect ag Eee Lu eet C Say Hello to Python Why Python? SERUM crea ee cM eM eee Cem amu caren en and some still available for older 8 and 16-bit computers too. Some of these languages ETeeKelocsela-te Rom sal ne AAU oe Ronee CN) Clee Teagan UY eg Tele Ret ere ake 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 Frontier, Forging small routines that enabled the letter A to scroll ‘across the screen. It may not sound terribly exciting toa generation that's used to ultra-high definition graphics and open world, multi- player online gaming. However, forty-something years ago it was, blindingly brillant. Naturally these bedsoom 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, 10S device, PC, ‘Mac, Linux, Smart TV, games console, MP3 playet, 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 can be built using a variety of programming languages. “The languages in use today differ depending on the situation, the platform, the device's use and how the device will interact with its Fe Ea yoo okt BA! GD As Sm itteurgor >= 0} ‘Refresh (cursor); cert chi tdbestrocus0) SFCTemtte) forint 3 herent Stine so Siena. co C++ is usually reserved for more complex programs, operating systems, games and so on. wisle(a © catcoune()) Fstop © coteaney (2) Liftreap > stzecey) breek: fsbottom = Frtep + Gettinecy(i)s ey ica ¥ acide) @ S Blase #|> 0@ one rine Setcursorp ys Fi Bere Barnes 4 eae aon oid arrayctrl::childostrocus() fa (Seeron> column. setceune() = 1)) == 0) , Color fe = Blend(scoloroisabled, scolorPeper): by ‘environment or users, Operating systems, such as Windows, macOS ‘and such are usually a combination of C++, Cit, assembly and some Foim of visualbased language. Games generally use C++ whist web pages an use a plethora of avalable languages uch as HTML, Java, Python and so on, "More general-purpose programming used to create programs, ‘apps, software or whatever else you want to cal them. They/re ‘widely used acrossall hardware platforms and suit vitually every ‘conceivable application. Some operate faster than others and some: are easier to learn and use than others. Python is one such general- purpose language. Python is what's known asa High-Level Language, in that t'talks to the hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless more interactions. Whilst its nat as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and reaisters, ts benefits that i's universally accessible and easyto learn 7#1Te= rnvoke. java Finport java. lang.reflect.*; EM class znvoke Public static void main¢ string [] args try Gass ¢ = Class. forname( args[o) ); Hethod'n ~ c.getNethod( argsil], new Class Object ret = m-invoke( nul1, null); systen.out.princin “tqvoked static method: " + args[ am of class: © + args(o) yn aith no args\nResults: " + ret ); catch ( Classnotroundexception & U1 Class fornane(”) can't find the class earch ( NosuchMethodexcept ion e2 77 that method, doesn't exist catch ( THegalaccessexception e3 77 we don't have permission to invoke that method catch ( InvocationTargetexception e¢ 7ian exception ocurred white invoking that inethod | a SyStem.outprint Tn a SNethed! threw an: " + e4, getrargetexception( ")°); Java's a powerful language that'sused inweb pages, set-top boxes, TVsand \e (why Python? CH Python was created over twenty sixyears ago and has evolved to become an ideal beginner's language for learning how to program @ ‘computer. t's perfect for the hobbyist, enthusiast, student, teacher and those who simaly need to create their own unique interaction between either themselves ora piece of external hardware and the computer itself Pythonis fre to download, install and use ands available for Linux, Windows, macOS, MS-DOS, 05/2, BeOS, IBM iseries machines, and even RISC OS. Ithas been voted one ofthe top five programming languagesin the world ands continually evolving ahead of the hardware and internet development curve Soto answer the question: why python? Simply put, i's Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and edu ce Prrarrerrereeretterg eg nD oDS SWLOOGOREOHOFMEOOO NE ZUDHZrHNT HW WODICrOAT 2 R sssooussen 9 sogscurso 9 flonmal ° ° BASIC was once the starter language that early ‘bit home computer users learned. Python isa more modern take on BASIC, it’s easyto learn ‘and makes Foran ideal beginner's programming language. => Say Hello to Python) Equipment You Will Need Noe LMR CN Aes MeN Rom nee CU en colt) CefeyaMen t-te TaM ents] Ware AU Reed oll Ima R- Tae Aa 1M Mr eRe Tela Te RT Freely available. WHAT WE'RE USING ‘Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. IF you have one of those systems, then you can easily start using Python. (| computer Obviously youre going to need a computerin oder to learn how to program in Python and to test your code. You can use Windows (from XP onward) on either @ 32 cee bt processor on Apple Meo inx stalled PC [| AN IDE ‘AnIDE (Integrated Developer Environment) is used ta enter and execute Python code. Itenables you to inspect your program cade and the values within the cade, as ‘wellas offering advanced features. There are many different IDEs available, so Find the one that works fr 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 we'll cover shortly. [_] TEXT EDITOR whist ext edo sande envionment to enter code ino. not an absolute neces, You can enter and execute coe det from the OLE buta text eto, Suchessbbine Text or Notepads, offers more advanced Features and colour coding when entering code ‘ |_| INTERNET ACCESS. Python isan 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 Intemet will keep you upsto-date, help you ‘out when you get stuck and give access to Python's immense number of modules, = TIME AND PATIENCE Es 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. Youmay become stuck at times and other times te code willow tke water. Understand youte learning something entirely new, and youwill get there THE RASPBERRY PI ( Equipment You Will Need CH Why use a Raspberry Pi? The Raspberry Plisa 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. aaa The Raspberry Pi 3s the latest version incorporating a more powerful CPU, more memory, WiFi and Bluetooth support. ‘You can pick up a Pi for around £32 or asa part oF kit For €50+, depending on the kit you're interested in, “The Raspberry P's main operating system isa Debian-based Linux distribution that comes with everything you need in asimple to use package. i's streamlined for the Piand isan Ideal platform for hardware and software projec, Python programming and even asa desktop computer FUZE PROJECT The FUZE sa learning environment bult on the latest model ‘of the Raspberry P. You can purchase the workstations that ‘come with an electronics kit and even a robot arm For you to build and program. You can find more information on the FUZE at www Fuze.co.uk We have several great coding titles avaliable via wunw. bdmpublications.com. Our Pi books cover how to buy your First RaspberryPi, sett up and use tsthere are some great step-by-step project examples and guides to get the most From the Raspberry Pitoo. ipbt EthON Manua boa FS Coding or Beg hee ER 0 ) 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 RoR Uae] Ieee WHAT IS PROGRAMMING? Ithelps to understand what 2 programming language is before you try to learn one, and Python is no different. Let's take 2 look at how Python came about and how it relates to other languages. PROGRAMMING RECIPES Aprogramminglanguage recipe to bake a cake could go tke this: Programs ae lke recipes For computers. A isa list of instructions that ‘a computer follows. These: ut 100 grams of selFraising flourin a bowl. instructions can be assimple Add 100 grams of butter to the bowl. 2s displaying your name ‘Add 100 mililtres of milk, ‘7 playing a music file, or Bake for halFan hour, as complexas building a Sc a eee eneemrereeereeerertrect cooeesseeeneesnnaeensreeanecenee whole virtual world. Python isa programming lanquage conceived in the late 1980s CODE Baa Just Uke a recipe, a program consists of instructions that you Follow piPhgiTitt. - y Poe ee inocer a orgram hat desebes 8 cake mghtrnthe the Informatica (Cwi) in the bowl = 0 Netherlands or a sccesocto fur = 100 TheARClanguage [butter «50 milk = 100 bowl .append( four butter mi Lk]) Penne ake.cook(bowl) PROGRAM COMMANDS You might not understand some of the Python commands, lke bowl append and cake.cook(bow). ‘The firsts list, the second an object; we'll Look at both inthis 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 out how a program works. Guido van Rossum, the Father of Python. ( Getting to Know Python cH HIGH-LEVEL LANGUAGES ZEN OF PYTHON Computer languages that are easy to read are known as “high-level”. Python lets you access al the power ofa computer in a language “hiss because they Fly high above the hardware (also referred to as_ that humans can understand, Behind allthis an ethos called "The ‘the metal). Languages that “fy close to the metal," ke Assembly, Zen of Python.” This isa collection of 20 software principles that are known as “low-level”, Lovelevel languages commands read a bit influences the design of the language. Principles include “Beautiful lkethis:msg db ,@xa Len equ $ - msg Is better than ugly” and “Simple isbetter than complex.” Type ‘import this into Python and it wil display all the principles. PYTHON 3 VS PYTHON 2 Ina typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language: rane ac aes WORLD OF PYTHON Wagemetiena pc) AY Peneeecseges td ee ea een ee aed = Te ee rar aaED c Feng eee uae frequently undat s ont mse ee Stents Poco need acaels c eee DC Coa Ua Tem lel PYTHON 2.X z rn 2wasoriginaly — ERRRRIREB) Python 3's orowing popularity has meant that nent aetna eet Cree adopted quite a large collection of modules, scripts, users, : features and begin to phase out the previous version. and e Crass Y 5 Cota Soe Say Hello to Python | How to Set Up Python in Windows Nelo NAD Ee) Mend cleo MEMES een} 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 Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. Thankfully, it’s an easy process to follow. FETE EE Stzrtby opening yourweb browser towww.python. [ESTEEM choosing the Customise option allows you to ‘0F9/downloads/. Look for the button detaling the specify certain parameters, and whist you may ) hist perfectly fe envionment Ks rot too userfiendly so leave the command tne for nou Enter: exT¥() to leave and close the Command Prompt window ®) 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 esol Med mae nM EEL UrLeN Alara (creme [ely ALR eLURSaCeLe) MTL cer R OlUM CMEC) aE le tae ola 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 PEPE open anew Terminal window by clicking Go> FERED) ickon the latest version of Python 3%, in our Utes, then double-click the Terminal icon, Now (se this isthe download button for Python 3.6.2. enter: python =-version. You should see"Python 2.1" and This will automatically 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, t automaticaly Either way, it's best to check forthe latest version. starts the installation wizard, EeTeeER pen Safari and head over to www.python.ora/ FETED With the Python instalation wizard open, click on downloads. Just 2s with the Windows setup the Continue button to begin the installation. I's procedure on the previous pages, you can see two yellow download worth taking a moment to read through the Important information buttons: one for Python 3.6.2, andthe 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. DOC Rute ana Tb C How to Set Up Python ona Mac E Eq ‘The next section details the Software License Agreement, and whilst not particularly interesting tomost Folks, it’s probably worth a read, When you're ready, click on the Continue button once again Finally you're be presented with the amount of space Python wil take up on your system and an Insta button, which you need to click to start the actual installation ‘oF Python 32xon to your Mac. You may need to enter your password toauthenticate the instalation proces. The installation shouldn't take too long; the older ‘Mac Mini we used inthis sectionisa lite slower than more modern Mac machines andit only took around thirty seconds forthe Installation Successful prompt to be displayed, ‘There's nothing much ele leftto do nthe Python Sua" installation wizard so you can click the Close button. you now drop backintoa Terminal session and reenter the command: python3=-verston you can see the new version now sted. Tener te command ine version of Python you need toenter pythons To ex, ts exit PEED You nced to search in Finder for the Python IDLE; ‘when you've Found it cickit to launch and it should look similar to that of the Windows IDLE version shown on the previous page. The only difference being the Mac detected hardware platform it’s running on. eee Piaen 260 Se Dython 16.8 Gl-6a:A14FPREGet, Gee 22 2016, 172050) Sta) (ot 2} on tarcin yr teeaneeG for mare taferntion. ‘ mleodec/tch/ for tarrerttnfranton, (Older Mac versions may have trouble with the ewer versions of Python, in which case you will need to revert toa previous Python 3.x build; as long as you're using Python 33, the code in this book will work or you. ‘Python 3-12 (z312:79260M, Mar 24 2010, 0 [6cc 4.0-1" (apple Inc. build $493)] on’ darwin 33:18) ‘Type "copyright", “credits” or “Licensi Fe information. }" fer mo 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 FO TERE RD Fist younced to ascertain which version of Python FATES Some Linux distros wll automaticaly update 's currently installed in your Linuxsystemy, as we the instalation of Python to the latest versions mentioned, we're going to be using Linux Mint 18.1 for thissection. whenever the system is updated. To check, first doa system update ‘Aswith macOS, drop into a Terminal by pressing CUrt+Atl+T and upgrade with: sudo apt-get update && sudo apt-get upgrade davidedavid-mint File Edt View Search Terminal Help Enter your password and let the system do any updates. Fee Nextenter:python ==version intothe Terminal [ESTA 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. Oursin this particular case ls. enter: python3: =-Version to see if Python 3xis updated or even Python 2.7.12. installed. n the case of Linux Mint, the version we have is Python 3.5.2, which sine For our purposes. davidedavid-mint ~ Fle Edit View Search Terminal Help wera bdmpubiations.com ( Howto Set Up Python in Linux € FETED However, iFyou want the latest version, 3.62 as per [ERTESESRM within the Python folder, enter: the Python website atthe time of writing, you need ie ‘ebuild Pythonfrom source, Startby entering these conmendsinto ——.._ ee ‘This coulda little while depending o Once finished, enter: python3.6 — Installed latest version. he speed of your computer. version to check the sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev Libncursesn5-dev Libssl-dev libsqlite3-dev tk-dev Libgdbn-dev libc6-dev libbz2-dev ease PEPE open upyour Linux web browser and go to FeTSEIE DD or the GUIIDLE, you need to enter the following the Python download page: www.pythen.org/ ‘command into the Terminal: ‘downloads. lick on the Download Python 3.6.2 (or whichever version t's on when you look) to download the source Python: 3.62tarxeflle ‘The IDLE can then be started with the command: idLe3. Note, that IDLE runs a different version fram the one you installed from source. sudo apt-get install idle3 Co yore erg Gnadedend mint WDomiendutyner a2 ESTEE AD '0 the Terminal, co the Downloads folder by FETED ov aso need AP (Pip Installs Packages) which isa entering: ed Downiloads/. Then unzip the tool to help you install more modules and extras. contents of the downloaded Python source code with: tar =xvF_ Enter: sudo apt-get install python3-pip Python-3.6.2. tar.xz. Now enter the newly unzipped folder SE PIP is then installed; check For the latest update with: pip3 install --upgrade pip When complete, close the Terminal and Python 3.x willbe available via the Programming section in your dstro's menu, wn bdmpubliations.com Getting Started with Python wornbmpubiations.com Getting Started Vie Python een ee Me ea EEL daunting at first but the language has been designed with simplicity in mind. Like most things, you need to. ECA et retest eu ayes Ms Ciuc eee Ne cera expressions, user input, conditions and loops; and the Beta Cue eee uk ata Param =) Getting Started with Python Starting Python For the First Time War eerie ReoM LAUR UN AOL OMe ee Cece Le lecro meee m chy] Ree a Celene a Ee aod ol Toc laat oF ela ER OLR ERTS Be BS)a1 OE] Rell lm aele RT Bela 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, FETE RID With the Raspbian desktop loaded, cick on the SEED (or example, inthe shell enter: 242 ‘Menu button followed by Programming » Python After pressing Enter, the nex¢ line displays the 3 (DLE). Ths opens the Python 3 Shall. Windows and Mac users can answer: 4. Basically, Python has taken the ‘code’ and produced the Find the Python 3IOLE Shell from within the Windows Start button relevant output. menu and via Finder. PE rea oe TTT ips eet rte a ten) er ae tran, BEER Thesheliswhereyou canentercode andseethe — JESTEEIARB the Python shel acts very much ikea calculator, responses and output of code you've programmed since code is basically a series of mathematical into Python. Tiss kind of sandbox, where you're ableto try out _interactions with the system. Integers, which ae the infinite ‘some simple code and processes. sequence of whole numbers can easly be added, subtracted, ‘multiplied and so on, EE ma “ume me tin 7 Starting Python for the First Time ( c Eq While that’s very interesting, i's not particularly exciting. Instead, try this: print(*Hello everyone!”) Just ike the code we entered in Sublime inthe Installing a Text Editor section ofthis book, PEP This isa lctie more ike t, since you've just produced Your first bit of code. The Print command is fairly self-explanatory, it prints things. Python 3 requires the brackets as ‘well as quote marks in order to output content to the screen, in this ‘ease the ‘Hello everyone! bit >>> print(“Hello everyone! *) Hello everyone! >>| You may have noticed the colour cading within Sica the Python IDLE, The colours represent different ‘elements of Python code, They are: Black —Data and Variables Green—Strings Purple— Functions range Commands Blue — User Functions Dark Red Comments Light Red Error Messages IDLE Colour Coding | cotour_[ Usetor | examotes _| Purple | Fnetene | end print) ghred | Eromessapns | _syntanteror ESTEE The Python ies a configurable enironment. if you dont tke the way the colour are represented, then youcan always change them via Options > Configure IDLE and clicking onthe Highlighting tb. However, we donttrecommend that, as you won't be seeing the ame as cur screenshots. EERE -estlike most programs available, regardless ofthe ‘operating system, there are numerous shortcut keysavallable. 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. The Python IDLE isa power interface and one 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 Shel, we recommend you take afew moments to view ‘wwnw.docs.python.org/3/library/idle.html, which detais many of the IDLE's Features. ED) cain saresisten) Your First Code UCT cM cuN Mga setomet Meee ass) everyone!”)’ Function from the previous tutorial, However, let's expand that and look at Nee h Vol meee ET eM LCCC RMR o Kel Tene 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. PER uve doses Python IDLE, eopentin ED eerste neecrn unter ate whoever pereang stem versonyouprefen Duiputs the 22 yu skedtobepraed tothe the shel entre oa Flow screen The quotation mats are dong whats bergutputed ees ‘Ste OLE Seta pnts ila 22 youreedremave the quotes: print(2+2) Eee 2¥st2s redicted, the word Hello appearsin the Eee You can continue as such, printing 2+2, 46442343, Shell as bive text, indicating output From a string. 3nd Soon to the Shell An easier ways tousea Its Fairly straightforward and doesn't require too much explanation. variable, whichis something we will coverin more depth later. For Now try printcr2+2") ESTES What you have done here is assign the letters 2 and b two values: 2 and 2. These are now variables, ‘hich can be called upon by Python to output, add, subtract, divide ‘and so on For as ong as their numbers stay the same. Ty this: printca) print) Your First Code PTD Nowlet’s adda surname: ‘surnome="Hayward” print(surname) ‘You now have two variables containing a first name and a surname and you can print them independently The output ofthe as step dpaythe current SEG values of both a and 0 individually, as you've asked them to be printed separately. If you want to add them up, you can use the following: print(atb) ‘This code simply takes the values of @ and b, adds them together, Save As From within the Editor tocreate abackup. BRTESET RD Now create anew file. Close the Editor, and open anew instance (File > New File rom the Shel. Enter the Following end save ia hllo.py. a="Python” baris” "cool!" print(a, b, ¢) ‘You will use this code inthe next tutorial Tal Pune Sooners Caehalopy G47) Getting Started with Python Executing Code from the Command Line COMMAND THE CODE Using the code we created in the GUL at the comman FERED °2th00, in Linux, comes with two possible ways of exeautin the command line, One of the ways is with Python 2, whilst the other uses the Python 3 libraries and 50 on. First though, drop into the command line or Terminal on ‘your operating system, line level, the previous tutorial, the one we named hello py, let’s see how you can run code that was made ‘command line version ofthe Shell, withthe Familiar three right: Facing arrows asthe cursor (>>), worabmpubiations.com Ea From here you're able to enter the code you've looked at previously, such as a2 primt(a) You can see that it works exactly the same. Executing Code from the Command Line EapD Now enter: exit() to leave the command line Python The result of running Python session and return you back to the command Python 2 command line is quite obvious. Whilst it prompt. Enter the folder where you saved the code from the ‘terror outin any way, due to the differences between the previous tuterial and list the available files within; hopefully you way Python 3handles the Print command aver Python 2, the result should see the hello.py file. isn'tas we expected, Using Sublime for the moment, open the hellopy file 1 CA Ooene sine Te UES PPD Fromithin thesame folder as the code youre PPED since Sublime Text isnt available for the Raspbe doing to run enter the Following into the Pi, youre going to temporarily eave the Pi for the command line: moment and use Sublime as an example that you dor't necessarily need to use the Python IDLE. With the hello.py fle open, alteritto Pshon LS LLOTPT include the Following: This will execute the code we created, which to remind you is ane=inputC"What is your name? *) a="Python” printC‘Hello,”, name) FETTER) Noturally, since this is Python 3 code, using the PETRET PD Seve the hello.py ile and drop backto the syntax and layout that’s unique to Python 3, it only command line. Now execute the newly saved ‘works when you use the python3 command. Fyou like trythe same code with ‘with Python 2 by entering python3 hello.py The resul willbe the original Python is cool! statement, together with the added input command asking you For your name, and displaying it in the command window. python hello.py ‘worn bdmpubliations.com C3 Getting Started with Python Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the like. Let's expand on that now and see just how powerful Python is as a calculator. You can work within the IDLE Shell or in the Editor, whichever you like. IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as languages, maths is the driving Force behind the code. ‘most, if notall, programming FSTEEEID Pen uo the Gul version of Python 3, asmentioned STEED You canuse al the usval mathematical operations: you can use either the Shell or the Editor. For the vide, multiply, brackets and so on, Practise with a time being, youre soingto use the Shel ustowarm ourmaths Few, forexample: tule, unchve believe sa sal land loeated athe beck ofthe brain (ornot. = 6/2 20283 G2or) 2 STE 4 a Secmalsurbee niente ae cle as crear or floating point arithmetic, However, if you need an integer as a ‘opposed to a decimal answer, then you can use a double slash: Youcanseethateyhonantandesome autelasenunies. 2 srdsoon SoBe rae or “cna fr mee tart, Ey 10/3, wil splay 3333333333, which’s of course 3.3recurting.Fyou now enter: 1053, ‘This wil display 1, which is the remainder left over from dividing 10, into3. "Next up we have the power operator, or ‘exponentiation if you want to be technical. To work You can also use an operation to see the remainder left over from division, For example: ‘out the power of something you can use @ double multiplication ‘symbol or double'star on the keyboard: 203, 10°10 Essentially it's 2x22 but we're sure you already know the basis behind maths operators. Tiss how you would work:t out in Python. ‘Numbers and expressions dont stop there. Python hhas numerous built-in 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 to binary, use: bing) Numbers and Expressions CH ‘This willbe displayed as ‘0b11, converting the Si integer into binary and adding the prefix Ob to the Front. you want to remove the Ob prefix, then you can use: format(3, ‘b") “The Format command converts avalue, the number 3,to.2 formatted representation as controlled by the Format specification, the’ par. FETSEE DD /800lean Expression is. logical statement that will tither be true or false, We can use these to compare dataand test to see it's equal to, less than or greater than. Try this Ina New File: a=6 b=? print(, a = 6) print(2, a = 7) print(@3, a == 6 ond b == 7) print(4, a == 7 and b == 7) print(S, not a == 7 and b == 7) print(é, a w= 7 or b m= 7) print(?, a == 7 or b = 6) print(8, not Ca = 7 and b = 6)) print(3, not a == 7 and b == 6) BRTESR EDD ©xccute the code from Step 9, andyou can see a series of Tue o False statements, depending on the result ofthe two defining values: 6 and 7. I's an extension of ‘what you've looked at, and an important part of programming. C3 Getting Started with Python Using Comments UNA RATA eae R Voll molec Mend a OMe ml eR Lila cle MN UT12) (Reel aN RON 16-1 0 Percofel EMMI Me LiL EDs eR: UMC Rol aCe Me WaT Klee mere 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 variables used, the programmer comments on whatits supposed to do, for example. It's just good practise. Start by creating a new instance of the IDLE Edtor Resave the code and execute it. You can see thatthe (File> New Fle) and create a simple verable and ‘outbutin the IDLE Shellistil the same as before, print command despite the extra lines being added. Simply put, the hash symbol) denotes line of text the progremmer caninsert to inform them, a=10 4 eee and others, of what's going on without the user being aware. ‘Save the fle and execute the code. f fyens42stet ‘anmersay-fhonnploscaren yin Cotaeanmerepy aaa) =e [Be Git amt Bin tone wa Da ed tie temas for oe retin, TEED ennina the code willreturn the ine: The value of A RSTSSWPMM Let's assume that the variable A that we've created is, 10 into the IDLE Shell window, which iswhat we isthe number of livesin a game. Everytime the ‘expected. Now, add some of the types of comments you'd normally player dies, the value is decreased by 1. The programmer could see within code: insert a routine along the lines of: # Set the start value of A to 10 a=a-1 a=10 printC*You’ve just lost a life!”) # Print the current value of A printC*You now have”, a, “Lives left!") print(*The value of Ais,”, a) PPI whistwe know thatthe variable A istives, and that the player has just ost one, a casual viewer or ‘someone checking the code may not know. Imagine for a moment that the code istwenty thousand lines long, instead of ust our seven, You can see how handy comments a. Using Comments Inline comments are comments that follow a section Sra of code. Take our examples from above, instead oF inserting the code on e separate line, we could use: a=10 # Set the start value of A to 10 print(*The value of A is,", 0) # 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) Essentially, the new code together with comments SUEDE could look like: # Set the start value of A to 10 10 # Print the current value of A print(*The value of A is,”, a) # Player lost a life! ana-1 # Inform player, and display current value of A ives) print(*You’ve just lost a lifel”) print(“You now have”, a, “Lives Left!) You can use comments in different ways. For example, Block Commentsare a large section of STEP 7 text that details what's going on in the 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. aaa EEE 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) ‘Ble Est Format Bun Options wndows Hep @ Set the start value of A to 10 Print the current value of A printc"the value of Ais.” ai] Player lost'a life! inform player. and display current value of A (Lives) int( You've just lost Prine(-Yeu now have", a, Teer) Lives left! 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 nell. C3 Getting Started with Python Working with Variables Cece chemi amo anes selec Te eee worth going through the way they operate and how Python creates and assigns certain NEWER 12) oe VARIOUS VARIABLES. You'll be working with the Python 3 IDLE Shell in this tutorial, Ifyou haven't already, open Python 3 or close down the previous IDLE Shelt to clear up any old code. In some programming languages you're required to-use a dolar sign to denote a string, which is a variable made up of multiple characters, such as @ name of a person. In Python this isnt necessary. For example, inthe Shell enter: nane="David Haynard” (oruse your own name, unless you're also called David Hayward). Tae Ga sd ot GaN des You've seen previously that variables can be concatenated using the plus symbol between the variable names. In our exemple we can use: print Chame + “: 4 title). The midéle part between the quotations allows us to add acolon and a space, as variables are connected without spaces, so we need to add them manualy eG Sel oes GENE Wr He PEPER You can check the type of variable inuse by issuing the type 0) command, placina the name of the variable inside the brackets. In our example, this would be: ‘type Came). Add new string variable: tit from Vikings” ca cco er combinevarables | acest ee eee ‘within another variable. For example, to combine both name andtitlevariablesinto a new variable we use: character=name +“: + title ‘Then output the content of the new variable as: print (character) Numbers are stored as different variables: age=4 Type Cage) ‘Which, as we know, are integers ESTER However, youcantt combine both strings and integer type variables in 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 gat an ‘error message: print (nome + age) Working with Variables (c} FEED this presents abit of aproblem when you want to work 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: intCage) + 10 ‘This wil Typecast the age string nto an integer that can be ‘worked with, ed mr nc ei BRTTSDD This is 2 process known as TypeCasting. The Python, code is: print (character + “ is o 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 asthe commas treat each argument to print separately + str(age) + “ years >>> print (name + age) Traceback (most recent call Last) File "™ rine’ (name * age) Typetrror: can't convert ine 1°"in'cnodute> sant’ object to str implicitly strage) #. yours eld”) siangae 44 yrs ol Sescended tron'vikings is'4 years old. STEP 7 center: ‘age= input C“How old are you? “) ‘All data stored from the Input command is stored asa string variable, ‘le lt shal Debug Options windows He 2 Cantal. OFF 19 1TH ‘Another example of TypeCasting is when you ask For input from the user, such as a name. For example, ragits" or “License reyout Berea 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 typeCshirt) and you'lsee that Python as allocated the numbers Toa, becase the value contains a decimal pot. aerate Meredits” or “License()” for nore information. When combining integers and Floats Python Usually converts the integer toa float, but should the reverse ever be applied it's worth remembering that Python doesn't return the exact value. When converting afloat to an integer, Python will aways round down tothe nearest integer, called truncating; in our case instead of 19.99 it becomes 19, Scene ere rag a ‘le Eat shob_Qobug Options wndows ip yon 34.2 Caataalt, Bet 19 20TH D Hype Scopyrige”, Nereeits" or *License()* for nore information. Memarecioees | iase fica’) so thecanirt) ED) cin session) User Input WSN oes eon ret merle (NM nan eels cKO nL cna) (ord earlier, so now would be a good time to Focus solely on how you would get information emt mec ere cnas 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. ESTe ORE *itsnot already, open the Python 3 1OLE shell, Eafe Now that we have the user'sname stored in a ‘and start a New Fle inthe Editor. Let's begin with ‘couple of variables we can call them up whenever something really simple, enter: ‘we want: print¢“Hello") print('Welcone”, firstname, surname, “. I hope firstname=input (“What is your first name? “) ‘you're well today.”) print(“Thanks.”) surnane=input(*And what is your surname? “) Save and execute the code, and as you already no Run the code and you can ee a slight issue, the doubt suspected, in the IDLE Shel the program will fullstop after the surname follows a blank space. ‘ask for your first name, storing it as the variable firstname, followed To eliminate that we can add a plus sign instead ofthe comma in by your surname; also stored in its own variable (surname), thecode: printC‘Welcone”, firstname, surnames. I hope you're well today.”) he ath tg atone so PSE ey ee spre eter a yu ame — ‘You dont always have to include quoted text within the input command, For example, you can askthe user their name, and have the inputin the line below: print(“Hello. What”s your name?) nanesinput() seringutpy - /home/pi/Docurnents/Python Code/us) [Ble Edt Faimat Bun Options Windows Help Drint("Relle, What"= your nane?™) ane=input() User Input \hatyouvecested here sa condo, which we Sra will cover soon. In short, we're using the input from: the userand measuring kagalnst.acondton So the user enters David astheirname the guard wl low them to pass unhindered Ele they entra name other than David, the guard challenges themtoa Pht. The code from the previous step is often regarded 2s being a litle neater than having a lengthy ‘amount of text the input command, butit'snata rule that's set in stone, so do as you lke in these situations. Expanding on the code, ley this printC“Halt! Who goes there?”) name=inputQ) It's2 good start toa text adventure game, perhaps? Now you can expand on it and use the raw input STEP 7 from the user to flesh out the game alittle: if name=="David”: print(*lelcone, good sir. You may pass. else: print(*I know you not. Prepare for battle! ‘Sairntpy-emelp/Docunets/Pybon Cadebseieaey(342) = 2 ie tat rt in geters Wenn FERED .ustssyoulearmed previously, any input froma ‘user is automatically a string, so you need to apply a “ypeCast inorder totum tinto something else. Thiscreates some interesting additions to the input command, For example: # Code to calculate rate and distance printC*Input a rate and a distance”) rate = floatCinputC*Rate: ")) Faces Heatcinutenete! Si FTE EDD 10 finalise the rate and distance code, we can add: distance = floatCinputC“Distance: “)) printC*Time:”, (distance / rate)) Save and execute the code and enter some numbers. Using the Floattinout element, we've told Python that anything entered isa Floating point number rather than a string C3 Getting Started with Python Creating Functions Now that you've mastered the use of variables and user input, the next step is to tackle functions. You've already used a few functions, such as the print command but Python enables you to define your own functions. FUNKY FUNCTIONS ‘Afunction is a command that you enter into Python to do something. It's little piece of self-contained code that takes data, ‘works on it and then returns the result. BETERDD (¢snotjust data that a function workson.theycan [NSE You can pass variables through Functions in much do all manner of useful things in Python, such as the same manner, Let's assume you want the sort data, change items fram one formatto anather and checkthe numberof letersina person's surname, you could use the Following length or type of items. Basically, a Function is ashort word that's _code (enter the text editor For this example): followed by brackets. For example, ten), ist() or type(). hemes MPUETCTENceryounTsunneane ti" counteLenCnane) print (“Your surname has“, count, “Letters in it”) Press F5 and save the code to execute it. ‘Afunction takes data, usually a variable, works on Python has tens of Functions built into it, Far too ‘depending on what the Functionis programmed many to get into inthe limited space available here. todo and returns the end value. The data being worked on goes However, to view thelist of builtin Functions available to Python 3, inside the brackets, so if you wanted to know how many letters navigate to www.docs.python.org/3/library/functions.html These aren the word antidisestablishmentarianism, then you'denter. __are the predefined Functions, but since users have created many ‘Jen(“antidisestablishmentarianism™) and the number28 more, they're not the only ones available, ‘would return, ‘Additional functions can be added to Python Suave through modules. Python has a vast range oF ‘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 To wea uncon fom a made enter the name of Suar6 the module followed by a full stop, then the name ofthe unctonFornsance, sng the math modkie since youve Iistimported tint Python, youcan us the square oot uncon, “odoso enter: math.sqrt(16) You can see that the code is presented as module function(data) ‘There are many different Functions you can import created by other Python programmers and you will undoubtedly come across some excellent examples in the Future; you can also create your own with the deF command, eee oe [def Hello():) Hel Loc) Cees type in Hel eneeeans ee Belt Perens et cos Pee ese accept Ree arte er mn may Function can now pass variables through it PEED 10 modity cturther delete the Hello(’David" line, the last line in the script and press CtrlS to save Tee aioe oar iret og rerrrr eer Seat eters ad ay creating Functions (CI C3 Getting Started with Python Conditions and Loops eet een Ce Se arae coe enn Ren eee rather complex. How you use them depends greatly on what the program is trying to Ea ment eel] Coan Ma unmade Rec Lom ies ly ee Reon a ceo 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. Let's create a new Python program that wil ask te user to inputa word, then checkit to see iF its 2a fourletter word or not. Start with File > New File, and begin with the input variable: word=input(“Please enter a four-letter word: “) BETTER) Nowwe can createa new variable, then use the len function and pass the word variable through ito ‘get the total numberof letters the user has ust entered: word=input(“Please enter a four-letter word: “) word_length=lenGnord) ESTEE) Now youcan use an ifstatementtocheckifthe word length variable is equal to four and print 3 friendly conformation iit applesto the rule: word-input(“PLease enter a four-letter nord: “) word_Length-Len(word) fF word_length == print (word, “is a four-letter word. Well done.”) “The double equal sign (==) means check Fsomething is equalto something else. eicingcen a) FETIP the colon at the end of iF tells Python that if this statement is true do everything ater the colon that’s indented. Next, move the cursor back to the beginning of the Editor: Word=inputC"Please enter a four-letter word: *) word_Length=LenGword) if word_length == 4: print word, “is a four-letter word. Well done.”) else: print (word, “is not a four-letter nord.”) ress 5 andsavethe code to execute Enter Suave ‘2 Fourletter word in the Shell to begin with, you shoul havethe retuned messoe hts the wor sores Now press agan and rerun the program bu this tine entera fetter word The Shel wil display tat t's no a Foucltter word LOOPS. eee ee eeu oie PEPIID Now expand the codetto include another conditions. Eventually, it could become quite complex. We've added a condition for threeletter words: Wordsinput(“Please enter a four-letter word: “) word LengtheLen(word) if word length == 4: print (nord, “is a four-letter word. Well done”) elif word_length print (word, “is a three-letter word. Try again.”) else: print (nord, “is not a four-letter nord.”) Nee ee eae block oF code a number of times, usually with the support of a condition. eee eat Se eae ants corres x= 1 wile x < 10; print Go) PEED The cifference between if and while is when while eee eg eet eet ee oe tay eater COG Cer tean rr cease Eee FRTTRED the For loop is another example, Foris used to Usually alist stored as ee are fords=[#Cat™, “Dog”, “Unicorn™ Hor_word tn words: print (nord)) Hor x in range (1, 10):| print Go) era eet aeons The For loop at ded here b Meet eet 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 EE Although good, the builtin Functions wihin Python are limited, The use of modules, however, allows us tomake more sophisticated programs. As you are aware, modules are Python scripts that are imported, such as import math BED ‘Some modules, especially on the Raspberry P ‘are included by default, the math module being a prime example. Sadly, other modules aren't always available. A good example on noni platformsis the pygeme module, which contains ‘many Functions to help create garmes. Try: import pygame, worabmpubiations.com Ea he resultis an error inthe IDLE Shell asthe ygame module isn’t recognised or installed in Python. To installa module we can use PIP (Pip Installs Packag Close down the IDLE Shell and drop into a command prompt or Terminal session. At an elevated admin command prompt, enter: pip install. pygane BED The PIP installation requires an elevated status due it installing components at cifferent locations. indows users can search For CMD via the Start button and right click the result then click Run as Administrator. Linux and Mac users canuse the Sudo command, with sudo pip install package, PEPIED lose the command prompt or Terminal and relaunch the IDLE Shell, When you now enter: mport 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 usualy te source of errorsin execution due to them being missing Dracaiaee =e Python Modules: FETED Mutinle modules can be imported within your code. To.extend our example, use: ‘import random ‘import math for I in range(S): print(random.randint(1, 25)) print(nath.pi) Dm ‘The modules contain the extra code needed to ‘achieve acertain result within your awn cade, as ‘we've 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 ike for i in range(10): printCrandom.randint(1, 25)) ovr a This code, when saved and executed, wil display ten rendam numbers from 1 to 25. You can play around uwith the code to display more or les, and from a great or lesser range. For example: import random for i in range(25): printCrandom.randint(1, 100)) The reuse tng of random ruber olowed EMai by the value of Pi as pulled From the math module using the print(math.pi) function. You can also pull in certain functions from a module by using the From and import commands, suchas fron random import randint for i in range(s): printCrandint(1, 25)) Brame FREER ED Thshelos create a more streamlined approach to programming, You can also use import module*, _which will 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, Say Hello tol@n: erro ec eae oe er used in a multitude of technologies. Everything from your Favourite mobile app, console and PC game to entire operating systems, all are developed fencer cutee cer emer es Cad kits and custom libraries. ee Ce ees ee eee a) extraordinarily powerful language to get to grips PM eccont eet nee etons Pe ea eigen wurbdmpublicationscom ee) Say Hello to C++ Why C++? C++ is one of the most popular programming languages available today. Originally called C with Classes, the language was renamed C++ in 1983. It’s an extension of the original C language and is 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 star ofthe golden era ofhome ‘computing labs and by regular people who didn’t have access to the ‘computing, C+, oF rather C with Classes, was the brainchild of ‘mainframes and large computing data centres, Danish computer scientist Bjarne Stroustrup while working on his, PhD thesis. Stroustrup's plan was to furtherthe 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 will Find since t was a much easier environment to get to grips with and that the browser you suf the Internet with is written in C+, as more importantly, t was 99% compatible with the original C ‘well as Windows 10, Microsoft Office and the backbone to Google's language. This meant thatit could be used beyond the mainstream search engine. Apple's macOS is written largely in C++ (with some Goines | #include using namespace std; void main() {char ch; cout<<"Enter a charater to check it is vowel or not"; cin>>ch; switch (ch) al { case'a': case'A': eout< @> B= a> Of" T> ‘Take a moment to browse through the app’s information, including the compatiblity, to ensure you have the correct version of macOS. Xcode requites macOS 10.126 orlaterto install and work. Start by opening the App Store on your Mac, Apple FETED) When you're ready, click on the Get button which then turns into Install App. Enter your Apple ID and xcode beginsto download and install. t may take some time depending on the speed of your internet connection. ESTeE DD When the installationis complete, click on the ‘Open buttan to launch Xcode. Click Agree to the licence teas and enter your password to allow Xcode to make changes tothe system. When that is done, Xcode begins to install additional components. With everything now installed, including the Run. You may be asked to enable Developer Mode fon the Mac; this to authorise Xcode to perform Functions without needing your password every session, When the program executes, the outputs displayed at the bottom of the Xcode window. Say Hello to C++) How to Set U C++ in Linux LINUX++ p If you're not Familiar with Linux, then we recommend taking a look at one of our Linux titles from the BDM Publications range. Ifyou have a Raspberry Pi, the commands used below work just fine and for this example we're using Linux Mint. FETED the frststepis to ensure Linxis ready for your C++ code, so check the system and software are up to date, Open a Terminal and enter: sudo apt-get update && sudo apt ‘get upgrade. Then press Retuin and enter your password. These the entire system and any installed software commands upd: Fie te Wew Seach Temi Heb EEE Most Linux distros come preinstalled wth al Une necessary components to start coding in C++showever it's ahvays worth checking to see if everything ispresent. Seilwithin the Terminal, enter-sudo apt-get install build-essential and press Return. IF you have the right | components nothings installed if you're missing some then they are installed by the command, worn bmpubiations.com ‘Amazingly, that'sit. Everything is already for you tostart coding, Here's how to get your first C++ program up and running. In Linux Mint the main text editor isXed, ‘which you can launch by clicking on the Meni and typing Xed into the search bar. Click on the Text Editor button in the right-hand pane toopenit. Sia In Xed, orany other text editor you may be using, center the lines of code that make up your C++ Hello alittle different to what the Mac produced: #include Save File As. Create or finda cnt» News Emporcorpres GveShtevon he eyoovrdsutable ron on ou hard dv onan he le Name box cal it helloworld.cpp. Click the Save as type box and select C/C++ files. Chart Sve button PEPE D Nowyou can see ablankscreen, with the tab FRPP You can see that Code:Blocks has naw changed labelled *Untitiedt, and the number one in the top the colour coding, recognising that the files now left of the main CodeBlocks window. Begin by clicking in the main C++ code. This means that code can be auto-selected from the ‘window, so the curso is next to the number one, and entering: Code: Blocks repository Delete the #include line and aaa re-enterit, Youcan see the auto-select boxes appearing PEED .ro-election of commands s extremely handy and cuts out potential mistyping, Press Returnto get to line 3, then enter: int main Note: there's no space between the brackets. BREED © the next ne below int maind,entera curty bracket: { “This can be done by pressing Shiftanaithe key tothe right of Pon an English Uk keyboard layout. weir -faleia hl | "Notice that Code:Blocks has automatically created STEP 7 2a corresponding closing curly bracket a couple of lines below, inking the pair, as wells a slight indent. Thisis due to the structure of C++ and it’s where the meat ofthe code is entered. Now enter: My first Cre program Your First C++ Program CH Note again the colour coding change. Press Return at Sra the end of the previous step's line, and then enter: std::cout << “Hello, world!\n"; aelor son: airedae 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. #INCLUDE Starthere | *helloworld.cpp ‘The structure of a C++ program on (C++ was invented by Danish: is quite precise. Every C++ code a #include studentSjane Soustrpin begins withadirectve: include 2 1979, 35 prtof his PhD. inciudes the é whieaking amore E icstream headerto support, user-friendly environment input/output operations. Uvough anew suuctre Bjarne Stroustrup, inventor : INT MAIN() Strthere | “helloworld.cpp £ int maing initiates the a . declaration of a function, which Pnciese)chasreeee> J isagroupof cade statements ‘under the name ‘main’. All Ci code begins at the main Function, regardless of whereit ‘actually ies within the code, int main() 2 5 4 S 6 BRACES The open brace (curly brackets) is something that you may not have come across before, especially you're used to Python. The ‘open brace indicates the beginning ofthe ‘main function and contains all the code that, bbolongsto that function. include int main() Tr aoeene COMMENTS Lines that begin with a double slash are comments. This means they ‘won't be executed in 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 tine comments //a single 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 ‘Finelaae “asereeem tohelp you, or another programmer tooking at ateateti yyour code, explain what's ‘going on. There are two types of comment: * covers multiple ine comments, //2 single line STD ‘While std stands for something quite different, in C++ it means ‘Standard, I's part ofthe Standard Namespace in C++, which covers ‘anumber of different statements and commands. You can leave the std: part out of the code but it must be declared at the stat with: using namespace std, not both. For example: #include using namespace std; eo COUT In ths example we're using cout, whichis apart ofthe Standard Namespace, hence why t'sthere, as you're asking C++ to use itfrom that particular namespace. Cout means Character OUTput, which displays, or prints, something to the screen. Fwe leave std: out we have to declare it atthe start ofthe code, as mentioned previously 7 © Structure of a C++ Program CH << “The two chevrons used here are insertion operators. This means that whatever Follows the chevronsis to be inserted into the std=cout statement In this case they're the wards ‘Hello, word ‘which are to be displayed on the screen when you compile and execute the code, OUTPUTS Leading on, the “Hello, worid” part is what we want to appear on the screen when the code is executed. You can enter whatever you like, 2s long sit’ inside the quotation marks. The brackets aren't needed but some compiles insist on them. The \n part indicates 3 new line is to 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 ane at the end or the compiler failsto build the code. The very last line has the closing brace to indicate the end of the main function. Finclade using namespace sta: int main() « cout Finclade using namespace sta: int masa) cout << "Hello, world!\at; 6 z= C++ Fundamentals ) Compile and Execute You've created your first C++ program and you now understand the basics behind the Seiten colo Mae eee Le an Ne TERM ee kate Rea SONU Dg Uae Kore CT-N 0) GREETINGS FROM C++ Compiling and exec result. Here's how it's done. (Open Code:Blocks if you havent already, and load up the previously saved Hello World code you ‘created, Ensure that there are no visible errors, suchas missing semicolons atthe end of the std:cout ine. ng C++ code From Code::Blocks is extraordinarily easy, just a matter of clicking an icon and seeing the ESTED) ket by clicking on the Buildicon, the yellow cog. {At this point, your code has now been run through the Code:Blocks compiler and checked for any errors. You can see the results ofthe Build by looking to the bottom window pane. Any messages regarding the qualty ofthe code are dsolayed here. — A Build log Build messages | /\ CopChecVe in "no project" (compiler: unknown) 5), 0 warning(s) (0 minute(s), 0 second(s) che++ I your code s Looking similar to the one in our screenshot, then looktto the menu bar along the top E> ‘of the screen. Under the Fortran entry in the topmost menu you can see a group of icons: yellow cog, green play button and a cog/play button together. These are Build, Run, Build and Run Functions, g Fortran wxSmith Tools [oreo FETE Now-click on the Runicon, the areen play button, ‘A.command line box appears on your screen displaying the words: Hello, world, Followed by the time it's taken to execute the code, and asking you press a key to continue, Well done, you just complied and executed your frst C++ program. Pressing any key in the command ine box loses it, returning you to Code::Blocks. Let's alter the cade slightly, Under the #finclude line, enter: using namespace std; ‘Then, delete the std: partof the Cout lng ke so: cout << “Hello, world\n”; Si) #avelide 2 using namespace sta: 3 4 _ ane main() s a ‘ 7 cout << "Hello, world! \n" e ° w Ly a 2 Siar ‘going on: cout << “Hello, world!\n”; //This Line outputs the words ‘Hello, world!”. The \n denotes a new line. However, you can also add comments to the end Of line of code, to describe in a better way what's Note, you don’t have to put a semicolon atthe end of acormment: “This is because i's alne in the code that's ignored by the comple. FETED ou can comment out several tines by using the Forward lash and asterisk: J This comment can ‘cover several Lines without the need to add more slashes */ Just remember to finish the block comment with the opposite ‘asterisk and forward stach, asterisk and forward slash and thus negate any code that falls inside the comment block Bisa Be careful when commenting, especially with block ‘comments. It's very easy to Forget to add the closing ‘Obviously if you try and build and execute the code it errors out, complaining of a missing curly bracket to Finish off the block of cade. f you've made the error afew times, then it can be time consuming to go back and, rectify. Thankfully, the colour coding in Code: Blocks helps identify ‘comments from code. Ifyou're using block comments, I's good practise in C++ to1add an asterisk to each new line of the ‘comment block. This also helps you to remember to close the comment block off before continuing with the cade: 7* This comment can * cover several Lines * without the need to add more slashes */ Using Comments CH z= C++ Fundamentals ) Variables Variables differ slightly when using C++ as opposed to Python. In Python, you can simply state that ‘a’ equals 10 and a variable is assigned. However, in C++ a variable has to be declared with its type before it can be used. THE DECLARATION OF VARIABLES You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can declare, Here's how it works. as #include using namespace std; int maing { 3 Sethee | Variablescpp > tating namespace sta, tnt main() BID You con bid ancirn the code butit wort do urs) much, other than store the values 10 and 5 to the integers and b. To output the contents ofthe variables, add cout << a5 cout << cout << bj The cout <<"\n°s part simply placesa nev line between the output of toands, ESTEE Start simple by creating two variables, aand>, with ‘one having a value of 10 and the other 5. You can use the data type int to declare these variables. Within the curly brackets, enter: int a; FETe EDD Noturaly you can declare anew variable, callit result and output some simple arithmetic: int result; result = a +b; cout << result; Insert the above into the cade as per the screenshot. int a= 10; int b= 55 int result = a + bs cout << result; FEPEIM specificto c+, youcan also usethe following to assign values toa variable as soon as you declare them: int a (10); int b G5); ‘Then, from the C++ 2011 standard, using curly brackets int result {a+b}; FETED You can create alobal variables, which are variables that are declared outside any Function and used in ‘any Function within the entire code, What you've used so Far are local variables: variables used inside the Function, For example: #include using namespace std; int StortLives = 3 int main © { stortLives = StartLives = 1; cout << StartLives; voiates CE FEI hc rcinsseo cence wesw, returns to its default state: 3. Here we've assigned 3 lives, then subtracted 1, leaving 2 lives left PEPE the modern c++ compiler i far more intelligent than most programmers give it credit. While there are numerous data types you can declare for variables, you can in Fact use the auto Feature: #include using namespace std; auto pi = 3.141593; int main double area, radius = 1.5; area = pi * radius * radius; cout << area; FSTEED couple of new elements here: rst, auto won't work unless you go to Settings > Compiler and tick the box labelled Have G++ Follow the C++11 ISO C++ Language Standard [std-c++1]. Then, the new data type, double, which means double-precsion floating point value. Enable C++11, then build and run the code The result should be 7.06858, C++ Fundamentals) Data Types THE VALUE OF DATA “There are many different datatypes available forthe programmer in C+, such as an integer, floating point, Boolean, character and so on. It's widely accepted that there are seven basic data types, often called Primitive Bultin Types; however, you can create your own data types should the need ever arise within your code, “The seven basic data types are [integer] Float) char} ool {double jwchar-_ howd “These basic types can aso be extended using the Following modifiers Long, Shor, Sianed and Unsigned. Basically this means the modifiers can expand the minimum and maximum range values for each data type. For example, the int data type has a default value range ofF 2147483648 to 2147483647, afairvalue, you would agree, Now, iFyou were to use one of the modifiers, the range alters: Unsigned int =0 to 4294967295, Signed int =-2147483648 to 2147483647 ‘Short int =-32768 to 32767 Unsigned Short int = Oto 65,535 Signed Shi 32768 to 32767 Long int =-2147483647 to 2147483647 Signed Long int =-2147483647 to 2147483647 Unsigned Long int = to 4284967295 Naturally you can get away with using the basic type without the moaifer, as there's plenty of range provided with each data type However, it's considered good C++ programming practise to use the ‘modifiers when possible. “There are issues when using the modifiers though. Double represents a double-floating point value, which you can use for ‘worabmpubiations.com incredibly accurate numbers but those numbers are only accurate Upto the fifteenth decimal place. There's also the problem when displaying such numbers in C+ using the cout function, in that cout by default only outputs the first five decimal places. You can combat that by adding a cout precision () function and adding a value inside the brackets, but even then you're stil imited by the accuracy of the double data type. For example, try this code: #include using namespace std; double PI = 3.141592653589793238463; int main { 3 cout << PI; Starthere X< Datatypes.cop 1 #include using namespace std; double PL = 3.141592653589793238463; int main) { cout .precision(22); cout << PI; Starthere | DataTypes.cpp 2 fan using namespace std; double PI = 3.1415 fi cout precision << Pr ‘Again, build and run the code; as you can see from the command, line window, the number represented by the variable Ps ifferent tothe number you've told C++ to use inthe variable. The output reads the value of Plas 3.1415926535897931 15998, with the numbers going awry from the Fifteenth decimal place. Cateulator 2 far Scientific D 15.142857142857142857142857142857 DEG HYP RE Me oM MS Fa x” sin cos tan v 10" log Exp Mod ay ce c =n qT ON WO ‘Thisis mainly due to the conversion from binary in the compiler and that the IEEE 754 double precision standard occupies 64-bts, of data, oF which 52-bits are dedicated tothe significant (the significant diaits ina Floating-point number) and roughly 3.5-bits are taken holding the values Oto 9. IFyou divide 53 by 3.5, then you arrive at 15.142857 recurring, whichis 1S-cigts of precision. ‘Tobe honest, if you're creating code that needs to be accurate to ‘more than fifteen decimal places, then you wouldn't be using C++, you would use some scientific specific language with C++ asthe connective tissue between the bwo languages. You can create your own data types, using an aliassike system called typedet. For example: Feed Site 3] bout vpencas _% #include using namespace st typedef int metres; int main) { metres distance; distance = 15; cout << “distance in metres is: “ << distance; This code when executed creates a new int data type called metres. Then, in the main code block, there's @ new variable called distance, hich isan integer; so you're basicaly telling the compiler that there's another name forint. We assigned the value 15 to distance and displayed the output: distance in metres 15. Itmight sound alittle confusing to begin with but the more you use C++ and create your own code, the easier it becomes. a 0 ) C++ Fundamentals Strings Ree ec ra cet te cece ekke ricer eMC NT eerie eC n C Cee uence eee til or called up wherever you like in the program. STRING THEORY There are different ways in which you can create a string of characters, which historically are all carried over from the original C language, and are still supported by C++. Si #include using namespace std int main © { t |xeaQaperson Coe ce To create a string you use the char function. Open a new C++file and begin with the usual header: Build and run the code, and Welcome’ appears, Con the screen, While thisis perfectly Fine it's nota string. Astringis a class, which defines objects that can be represented as.astream of characters and doesn't need to be terminated like an array. The code can therefore be represented as: #include using namespace std; int main © char greet[] = “Nelcome”; cout << greet << “\n"; FETED 5 e259 to confuse a string with an array. Here's an artay, which can be terminated with a null character: #include using namespace std; int main © f char greet[8] = {'W', te, NO ‘cout << greet << “\n"; InCt+ there's also a string Function, which works in much the same way. Using the greeting code again, ‘you can enter: #include using namespace st int main © t string greet = “Nelcome”; cout << greet << “\n"; PEPER There are also many different operations that you can apply withthe string Function. For instance, to ‘get the lenath of a string you can use: #include using namespace std; int main © { string greet = “Welcome”: cout << “The Length of the string is: “; cout << greet.size() << “\n"; PEPE You can see that we used greet size( to output the lenath, the number of charactersthere are, of the contents ofthe string, Naturally, if you call your string something ‘other than greet, then you need to change the command to reflect this, k's always stringname.operation. Build and run the code to see the resus. #include using namespace std; int main © { You can of course add strings together, or rather combine them to form longer strings: string greet = “Hello”; string greet2 = “, world!”; string greet3 = greet + greet2; cout << greet3 << “\n"; PEPE est 25 you might expect, you can mixin an integer {and store something to do withthe string. In this example, we created int length, which stores the result of string. size() and outputs ito the user: #include using namespace std; int main © { ‘int Length; string greet = “Hello”; string greet2 = “, world!”; string greet3 = greetl + greet2; Length = greet3.size(: cout << “The Length of the combined strings “<< Length << “\n"; is: Using the avalable operations that come with the sting function, you can manipulate the contents of a Siar) string. For example, ta remave characters from a tring vou could use: #include using namespace std; ‘int main Q { string strg (“Here is a long sentence in a string.”); cout <<'strg << *\n’; erase (10,5); << strg << ‘\n? erase (strg.begin()+8);

You might also like