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

Python & C++ For Beginners, 2nd Edition (2020)

Code with Python & C++ – For Beginners is the first and only choice if you are new adopter and want to learn everything you’ll need to get started with coding and programming. This independent manual is crammed with helpful guides and step-by-step fully illustrated tutorials, written in plain easy to follow English. Over the pages of this new user guide you will clearly learn all you need to know about coding your own amazing apps. With this unofficial instruction manual at your side no problem.

Uploaded by

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

Python & C++ For Beginners, 2nd Edition (2020)

Code with Python & C++ – For Beginners is the first and only choice if you are new adopter and want to learn everything you’ll need to get started with coding and programming. This independent manual is crammed with helpful guides and step-by-step fully illustrated tutorials, written in plain easy to follow English. Over the pages of this new user guide you will clearly learn all you need to know about coding your own amazing apps. With this unofficial instruction manual at your side no problem.

Uploaded by

Zaza Vrot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 82
N a EXPERT TUTORIALS TOENGANGE YOUR USEREXPERIENGE; BLACK & WHITE PY THON & C++ Starting something new can be daunting. Learning a skill or mastering a new piece of hardware is tough. Even tougher if STC Uem Lae Ro | mee Enroll as ee ceo a ete a Re mu Ta CMU he at SM Se one Re) 9) ce Peta uae RCE eon irae eA UC Pea burlac late hie M VAAL Sol) ETS elo eA aCiae (Ruled elt lace ks OPMaa Ne olan a UL aol Cae ities ho ulcuniee kde hur ee MRE lee Pra Ree ORME bre eo eOrNaolm SOUR a ORC Lae fertile BoE Np RIC 1¢ ees Cu ced ANAM Lees ine cleo. ol i Pau ge acceler Meet ie Red out of the box! We will guide you step-by-step through using all PE eC RAC aE cul races apprehensive at attempting. Let our expert guide help you build ela renee are CUE ORL MCh iule pie RCE need toaconfident and experienced user. Over the page our journey begins. We would wish you luck but DiRT Ret ats) coe S Cole R Cente cea Contents 8 WhyPython? 10 Equipment You Will Need 12 Getting to Know Python 14 How to Set Up Python in Windows 16 How to Set Up Python on a Mac 18 How to Set Up Python in Linux —_ 20) Getting Started with Python ESO eta ured 22 Starting Python For the First Time 60 YourFirst 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 Why CH? 48 Equipment Needed 50 Howto Set Up C++ in Windows 52 Howto Set Up C++ ona Mac 54 Howto Set Up C++ in Linux 56 Other C++ IDEs to Install wm publications com aa seat Patan & ++ For Basar spe re. ar28e-26 Pied Paps Lined Digital dstbation yr: ea AB no Nope Cfo, Poctags apse merge & les Ns 00519, eons [Efooursicon i mnntinoiiatencon ora publications com Say Hello to Python ME nu ee Cd BC cone ence cet i) ee ee eu e ei) used as minor utilities for operating systems. Python sits somewhere in the middle, combining ease of use eed an cate Peerage cn ies ens ure Pee enue ieee Dee ar a eu. Soe CM Cu ec) lively community behind it that shares knowledge, code and project ideas; as well as bug Fixes for Future releases. It's thanks to this community that the language has grown and thrived and now it’s your turn, Pele tes tire u ee ae cance Begs ds ae cue ty latest version of Python and from there guide you on Pe tetera e en) Functions and Features of the language. Before long, you will be able to code your own helpful system tools, De ee UU eee Dee een ED) sricotonne Why Python? SEEM icns ae cumin) uct eee Cement skeet cn and some still available For older 8 and 16-bit computers too. Some of these languages Ere Kel sre eho ANOTHER Meco Renee farerenketeeiel esta 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 small routines that enabled the letter ‘to scroll ‘across the screen It may not sound terribly exciting to a generation {that’s used to ultrahigh defintion graphics and open world, multi player online gaming, However, forty-something years ago it was biindinaly brillant. "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 others pushed the available hardware tots 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 bu tocar, settop box ora thousand other connected and smart’ appliances, behind them als programming. ‘Allthose aforementioned distal devices need instructions to tell. them what to do, and allow them to be interacted with, These instructions form the programming core ofthe device and that core ‘canbe 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 wil interact with ts Dn tat Beet BS Ob bot Se Xe ar vivenacee)@/6 Gee +> 7@ ‘Setcursor(p. yz certsichitsentFocusi: itleurgor >= 0) Pefreshpow‘cursor); centTrchitdbastrocust) TeTIMENGT Paine") nati) ® C++ is usually reserved For more complex ‘programs, operating systems, games and so on. old Arraycert::childLostFocus() : void Arraycert::Paint(Oravé 4) ( iets < cetcount()) { top = cattiney 3) LitePeop etze.ey) breaks Hop + opttinecy (i) 4 < column. cetcnune(): 344) { er Settaiasth(3) a) 0) 4c = Blend(scoloroissbled, scoloreaper); obs environment or users. Operating systems, such as Windows, macOS. {and such are usually a combination of C++, C#, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethore of avalable languages such as HTML, Java, Python and soon. ‘More general-purpose programming is used to create programs apps, software or whatever else you want to call them. They/re widely used across all hardware platforms and sult virtually every conceivable application. Some operate Faster than others and some are easier to lear and use than others. Python is one such general purpose language. Python is what's known asa High-Level Language, in that it talks to the hardware and operating system using avarety of arrays, variables, objects, arthmetic, subroutines loops and countless ‘more interactions. Whilst it’s not as streamlined asa Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that it's universally accessible and easy to learn, gag /FiTe= tnvoke. java import java. lang.reflect.*; BM class rnvoke Public static void main string [) args try Cass ¢ = Class. forname( args[0] ); Nethod'm = c.getMethod( args (1), naw class Object Fee = a. imyokeC nulT, nul? systen.out.printin ‘Stqvokee, static method + of ctass: © + args(o tm with no args\nnesults: " + ret); catch ( Classotroundexception € 77 Class. fornane(”) can't find the class Gach € wosuchtiethodexception e2 77 that method doesn't exist * + args( aren ( Tllepalaccesstxception 3 77 we don't have permission to invoke that wnethod. Gatch ( Invocationtargetexception e4 77*an exception ocurred while tnvocing that nethod 1 Systen.out. print yetsNethod threw an: " + ef getTargetexception( ")")} Javaisa powerful language that's used in web pages, set-top boxes, TVs and \< Cinyevon CE Python was created over twenty six years ago and has evolved to become an ideal beginner's language For learning how to program 3 ‘computer. I's perfect forthe hobbyist, enthusiast, student, teacher ‘and those who simply need to create their own unique interaction between either themselves or apiece of external hardware and the ‘computer self. Python i free to download, install and use and is avallable for Linux, ‘windows, macOS, MS:DOS, 05/2, BeOS, IBM iseries machines, and ‘even RISCOS. Ithas been vated one of the tap Five programming languages in the world andis continually evolving ahead of the hardware and Internet development curve. ‘So to answer the question: why python? Simply put, it's Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational tool y y 2 a a + x 23s 130 iso 150 138 i 2 2 3 5 Score ) spy THEN LET 30; 10 TO i000: “NEXT Se ai i 2 i Se r 3 a Si Bi 3: Si ry et rt ct BASIC was once the starter language that early B-bit home computer users learned. Python is a more modern take on BASIC, i's easy to learn and makes for an ideal beginner's programming language. BE) 2 sctoiortion Equipment You Will Need pare arena nd leeCur Uc kom Une are Case un ll Colota Panto anol] Ng Leet Reon) .U UOT O LNRM OLA Le Key irl] (om 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 bvously you're going to need a computer in order to learn howto program in Python andto test your code You can use Windows (rom XP onward) on ether 232 or 6b procestor, an Apple Ma or Lnuxinstaled PC. (_] AN IDE An IDE (Integrated Developer Environment) is used to enter and execute Python code. It enables you to inspect your program code and the values within the code, 2s wells offering advanced Features. There are mary different IDEs avaliable, so find the one that works For you and gives the best results. |_| PYTHON SOFTWARE 1macOS and Linux already come with Python preinstalled as part ofthe operating system, a5 does the Raspberry P. However, you need to ensure that you're running the atest version of Python, Windows users need to download andinstal Python, which wel cover shorty (_] TEXT EDITOR Whilst a text editors an ideal environment to enter code into, it'snotan absolute necessity. ou can enter and execute code directly from the IDLE but atext editor, such as Sublime Text or Notepad++, 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 it amore 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 ead you to believe, you won't become a programmer i in 24-nours. Learning to code in Python takes time, and patience. You may become stuck times and other times the code wil flow Uke water. Understand you're learning something entirely new, and you wil get there THE RASPBERRY PI ( Equipment You will Need Cl 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. a aaa) ‘The Raspberry 13 i the latest version, incorporating a more powerful CPU, more memory, Wii and Bluetooth support You can pick up a Pi for around £32 or asa part ofkitFor E504, depending on the kit you're interested in RASPBIAN ‘The Raspberry Ps main operating system is 2 Debian based Linux distribution that comes with everything you need in 2a simple to use package. It’s streamlined for the Piand is an ideal platform for hardware and software projects, Python, programming and even as a desktop computer. FUZE PROJECT ‘The FUZE isa learning environment built onthe latest model ofthe Raspberry Pi. You can purchase the workstations that come with an electronics kitand even a cabot arm for you to build and prooram. You can find more information on the FUZE at wwrw.Fuze.co.uk. We have several great coding titles available via www. ‘bdmpublications.com. Our Pi books cover how to buy your First Raspberry P, set it up and Use it there are some great step bystep project examples and guides to get the most From the Raspberry Ptoo, =r « z= Say Hello to Python ) Getting to Know Python une eer cole ree mae) Cute kerr let rl Reo aaa eRe EL Me fe Rae te CEU RC 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. PYTHON ‘A programming language isa listof instructions that ‘a computer follows. These instructions can be as simple ‘as displaying your name or playing a music ile, or ‘ascomplex as building 2 ‘whole virtual world. Python isa programming language conceived in the late 1980s by Guido van Rossum ‘at Centrum Wiskunde & Informatica (OW in the Netherlands asa successor to the ABClanguage. Guido van Rossum, the Father of Python. PROGRAMMING RECIPES crore pus 10 arom of selfratsng four Sn + bol Programs are lke recipes For computers. A recipe to bake a cake could go like ths: 2 as 180 grans of butter to she baud Put 100 grams of selFraising flourin a bow ‘Add 100 grams of butter tothe bowl, ‘Add 100 mliitres of milk. Bake for half an hour, CODE Just lke a recipe, @ program consists of instructions that you follow lnorder.A program that describes acake might run lke this: bowit = four = 100 butter = 50 milk = 100 Feehan nna ny bb .append( [flour butter mic] If cake. cookCbon) PROGRAM COMMANDS ‘You might not understand some of the Python commands, lke bowL append and cake.cook(bowi). The firsts alist, the second an object; we'l 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. HIGH-LEVEL LANGUAGES Computer languages that are easy to read are know 2 hightevel Thisis because they fly high above the hardware (also referred to as “the metal) Languages that “ly close to the metal, lke Assembly, ‘are known as low-level’. Low-level languages commands read abit, like this:msg db ,@xa len equ $ = msg PYTHON 3 VS PYTHON 2 Pee ut cuanto. Peete Lene! WORLD OF PYTHON emetic Peer eee eae Anes Cataract peta es that DCR oa eure Ur PYTHON 2.x erie et is Se aeete eer tremely (cetinstoroowxion CE ZEN OF PYTHON Python lets you access all the power of a computer in a language that humans can understand. Behind all this isan ethos called "The Zen of Python." Ths isa collection of 20 software principles thet influences the design ofthe language. Principles include “Beautiful isbetter than ualy" and "simple i better than complex." Type import: this into Python and it wil dsplay al the principles. PYTHON 3.X apunietaenes and enhanced Featu Soren eerste : mete meee wil Doses has since be Pm 3.X WINS ielueueeemn Petits eer ro tsa cece peer bowed Python 3 For snippets of important code, 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 Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. Thankfully, i's an easy process to follow. FETED 2'tby opening your web browser to www.python. ‘0ra/downloads/. Look for the button detailing the download lnk for Python 3.x (in our case thisis Python 3.6.2 but as ‘mentioned you may see later versions of 3) DTC Re oe Ce rm a Te DownloadPython 3.62 | Oownloadython27.13, Click the download button For version 3x, and save the file to your Downloads folder. When the fle is downloaded, double ick the executable and the Python installation wizard wil launch, From here you have two choices Install Now and Customise Installation. We recommend opting for the Customise installation ink Install Python 3.6.2 (32-bit) ® = pythén windows Bis Choosing the Customise option allows you to specify certain parameters, and whilst you may stay with the defaults i's a good habit to adopt as sometimes (not with Python, thankfully) installers can include unwanted additional Features. Onthe first screen available, ensure allboxes are ticked ‘and click the Next button. J Optional Features deemaatin pythén windows tk Nest ant BPD the next page of options include some interesting adtionsto Python. Ensure the Associate fe with Python, Create Shortcuts, Add Python to Environment Variables, recompile Standard Library and install for Al Users options are ticked. These make using Python ater much easier Click Install when youre ready to continve = a pythén windows mae Advanced Options You may need to confirm the installation with the ‘Windows authentication notification Simply click Yes and Python will begin to install, Once the installation is complete the final Python wizard page wil allow you to view the latest release notes, and Fllow some online tutorial Setup was successful yy @ outle * windows. Before you close the istalwicard window, SUS however, it's best to click on the link next to the shield detaed Dsabe Path Length Lt. This wil allow Python to bypas the Windows 260 character imitation enabing outo execute Python programs toredin deep folders arrangements Again cick Yes to authenticate the proces ten you can los the etalon window © Disable path lenath limit ‘close moe ” Windows 10 users will now = find the installed Python 4 Deena 3.x within the Startbutton Recently Added section. The First link, Python 3.6 (32-bit) . wll launch the command line version of Python when dlcked more on that ina moment) To open the IDLE {ype OLE into Windows start How to Set Up Python in Windows Cl Clicking on the IDLE (Python 3.6 32-bit link will launch the Python Shell, where you can begin your Python programming journey. Don't worry iFyour version ismewer, as long as i's Python 3.x our code will work inside your Python 3 interface, environment. To enter Python within the command line, you need totype: python and pres Enter. BSTSET ER) the command line version of Python works in| much the sare way asthe Shell you opened in Step 8; note the three leftfacing arrows (>>>). Whilst it's a perfectly Fine environment, it's not tao user-friendly, so leave the command line For now. Enter: xitO to leave and close the Command Prompt window. Na AVAXHOME? nee cd providing you various content: LC eC a Ee ee eS mea eas ces Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction PRE Uys ETC emer ol Tei AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu BE) 2 sctoiortion How to Set Up Python on a Mac ert Ea CA Meena eet n eT Mn Tales NSA Toe Rese la oda eNO ELK Te NVA) Cre oN Lem OLR Colt COMM RS B VoL MR UTTIAN) TAC) labo 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 Oven anew Terminal window by clicking Go> FEED click onthe latest version of Python 3x, in our Utilities, then doubleclick the Terminal icon. Now ‘ase thsi the download button For Python 3.6.2. enter: python’ ==version. You should see "Python 2.5.1" and This wil automatically download the latest version of Python and even later, i Apple has updated the OS and Python instalation. ‘depending on how you've got your Mac configured, it automatically Either way, i's best to check forthe latest version. starts the Installation wizard, PSPTSED) oven safari andhead over to www.python.org/ FETS With the Python installation wizard open, click on downloads, Just as with the Windows setup the Continue button to begin the installation. I's ppracedure on the previous pages, you can see two yellow dawnload worth taking a moment toread through the Important information buttons: ane 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 may be different due to the frequent of macOS. When ready, click Continue again releases of Python. wane Stee Download the latest version for Mac OS X ‘Thernext section details the Software License MED s3rccment ands rot particulary interesting to most folks it's probably worth a read, When you're ready, click on the Continue button once again Install button, which you need to click to startthe actual installation (of Python 3.x on to your Mac. You may need to enter your password to authenticate the installation process. Finally you're be presented wit the amount of space Python will take up on your system and an PEPE DD) The installation shouldn't take too long; the older ‘Mac Mini we used in this section isa little slower than more modern Mac machines andit only took around thirty seconds for the Installation Successful prompt tobe displayed. Theres nothing much be fet do inthe Python S18 installation wizard so you can click the Close button. you now rp bckinoo Terminal session and reenter the commang: yhon3 =-verston yu can ee the new version now sted To ete the command ine version of Python you need toenter python3. Toes ts exiEO, FSTTSEB You need to search in Finder For the Python IDLE; when you've found it, clckitto 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. ese Pon 160 Set Pyar 3.6.0 G3.6.0414F926I1, bee 22 286, 1723-0) (EeC21 Cate ines bua S666) (ot 39} serie Fev Ce50) von ay bo conan Colder Mac versions may have trouble with the newer versions of Python, in which case you will need to revert toa previous Python 3.x build; as long as you're using Python 3.x, the code in this book will work for you. Python 3.1.2 (r312:79360M, Mar 24 2010, 01+33:18) {Gce 4.0/1" (apple inc. build 5493)} on’ darwin Type "copyright", “credits or "license()" for mo Ee ineornation. How to Set Up Python on a Mac cll 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 FETED) Fistyounced to ascertain which version of Python MEE some Linux distros will automatically update iscurrently installed in your Linux system as we the instalation of Python tothe latest versions mentioned, we're going to be using Linux Mint 18.1 for this section. whenever the system s updated. To check, ist do a system update ‘Aswith macOS, drop into a Terminal by pressing CtrAtsT, and upgrade with a sudo apt-get update && sudo apt-get upgrade Fie Et View Search Terminal Help Enter your passward and let the system do any updates, ESTEE "Nextenter:python’=-version into the Terminal ESTSSIBM Once the update and upgrade is complete, you screen. You should have the output relating to ‘may need to answer Y' to authorise ay upgrades, version 2.x of Python inthe display. Qursinthispartcularcaseis enter: python3. --verssion to see if Python 3x's updated or even Python 2.7.12. installed, In the case of Linux Mint, the version we have is Python, 3.5.2, whichis Fine for our purposes. davide-david-mint Fle Edit View Search Terminal Help pr ot Paurueeetd ww bmpublcations com How to Set Up Python in Linux FETED However iFyou want the latest version, 3.6.2as per [EIB within the python folder, enter: the Python website atthe time of writing, you need sence tpbuld thon rom sure Stary entering these commands ito [__—— ‘This could alittle while depending on the speed of your computer Once Finished, enter: python3.6 ==versivon to check the installed latest version sudo apt-get install build-essential checkinstalt sudo apt-get install libreadLine-gplv2-dev Libncursesn5-dev Libsst-dev libsqlite3-dev tk-dev Libgdbm-dev Libc6-dev Libbz2-dev BETTE) Oren up your Linux web browser and goto FETS Fo" the GUIIDLE, you need to enter the following the Python download page: vwwwpython.ora/ ‘command into the Terminal: downloads. Clickon the Download Python 36.2 (or whichever version it’s on when you look) to download the source Python: 3.62.tarve fle, ‘The IDLE can then be started with the command: idLe3. Note, that IDLE runsa different version fram the one you installed from source, sudo opt-get install idle3 Cyt ure) BETTER the Terminal gothe Downloads folder by PEPPER vou also need Pi Ppinstas Packages) whichisa contents of the downloaded Python source coce with: tar =xvF Enter sudo apt-get install. python3-pip Python-3.6.2. tar.xz, Now enter the newly unzipped folder a, PPPs then installed checkor the atest update with pip3 install --upgrade pip eee ‘When complete, close the Terminal and Python 3 willbe available via the Programming section in your distro's menu. ora vmpublcationscom z= Getting Started with Python Getting Started with Python ee SR ae Usa CTO aaa Cues Ueto se SSeS ATU el Re ule Ro os co) ee NA ene Eo eed PURO U Se Tce ae ON a ee) expressions, user input, conditions and loops; and the types of errors you may well come across in your time Paes 2 @) Getting Started with Pytho +) Starting Python For the First Time Mere ol tern ee uaa ey ed rec cea Renae ode once eaaccel Che EM Ce raced ttc lea 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. FETTER) With the Raspbian desktop loaded, cick onthe ELE or example, nthe shell enter: 242 Menu button followed by Programming > Python After pressing Enter, the next line displays the 3 (DLE). Tis opens the Python 3 Shell Windows and Mac users can answer: 4. Basically, Python has taken the ‘code’ and produced the Find the Python 3 IDLE Shell fram within the Windows Start button relevant output. ‘meni and via Finder. = PEER ecncicanweenmeracncsnete, RBI ‘nnn suisse nate scner some simple code and processes. sequence of whole numbers can easily be added, subtracted, multiplied and soon. Pe ee TT ee Steet race heme) or mre ita, Starting Python for the First Time E mm ESTEE While that’s very interesting it's not particularly exciting, Instead, try this print(*Hello everyone!”) Just lke the code we entered in Sublime in the Installing a Text Editor section ofthis book ESTED Tisise litle more tke it, since you've just produced your First bit of code. The Print commands Faity selF-explanatory, prints things. Python 3 requires the brackets as ‘well as quote marks in order to output content to the screen, inthis case the ‘Hello everyone! bit. >>> print("Hello everyone!”) Hello everyone! >>> | EaTeeAD You may have noticed the colour coding within the Python IDLE. The colours represent different elements of Python code. They ae: Black -Data and Variables Green~Strings Purple Functions (Orange Commands Blue — User Functions Dark Red Comments Light Red ~ Error Messages, IDLE Colour Coding asked | Comments | ianeaber VAR antes [Ererrosuote | syneanteror ThePython DLE coniquabeenionent F Ella! you don''t like the way the colours are represented, thenyoucanahascunge hems Optons> Conte Leon licking onthe Highlighting tab. However, we don’t recommend that, as you won't be seeing the same as our screenshots. pea «uae ost = 4 zereemn ee FETED ust lke most programs avaliable, regardless ofthe ‘operating system, there are numerous shortcut keys avallable. We don’t have room for them all here but within the ‘Options > Configure IDLE and under the Keys tab, you can see alist. (of the current bindings. PEPISETR Te Pithon IDLE is a power interface and one that's actually been written in Python using ane ‘of the available GUI toolkits. F'you want to know the many ins and ‘outs ofthe Shel, we recommend you take a few moments to view ‘ww-docs.python.org/3/library/idte.html, which details many oF the IDLE's Features ED) ceinsteawtnaenn Your First Code Essentially, you've already written your First piece of code with the ‘print(“Hello everyone!”)’ Function From the previous tutorial. However, let's expand that and look at entering your code and playing around with some other Python examples. PLAYING WITH PYTHON wi 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. ESTED you've closed Python 3 IDLE, reopen itin TERED You cansee that instead ofthe number 4, the whichever operating system version you prefer. In outputs the 2+2 you asked to be printed tothe the Shell enter the Familiar Following: screen. The quotation marks are defining what's being outputted tothe IDLE Shell to printthe total of 2+2 youneed to remove the quotes: print(2+2) print(*Hetlo”) ea ama fr notin ESTeeE RD vst as predicted, the word Hello appearsin the FETE You can continue as such, printing 242, 46442343 Shellas blue text, indicating output from a string {and s0.0n ta the Shell. An easier way is touse a 's fairly straightforward and doesn't require too much explanation. variable, whichis something we will cover in more depth later. For Now try now, enter: print(*2+2") Your First Code ( CG \What you have done heres assign the letters and b two values: 2 and 2. These are now variables, \which can be called upon by Python to output, add, subtract, divide {and soon for as long as their numbers stay the same. Try ths: print¢a) print(b) 1 ES) Oia eo ips Sel Set een “ica tr mare intanation ESTEE The output ofthe last step displays the current values of both a and b individually, as you've asked them tobe printed separately. IFyou want to add them up, you can Use the following: print(arb) ‘This code simply takes the values of a and b, adds them together and outputs the result ¥ er ‘You cn ply around with dferentknd of varabes BMD 3 ne Princ uncon. For example, you cold assign variables For someone's name: ae="David” print¢nane) "Now let'sadd a surname: ‘surnane="Hayward” print(surnane) ‘You now have two variables containing a frst name and a surname New Fie. This will open a new window with Untitied as its name. Thisis the Python IDLE Editor and within it You can enter the code needed to create your Future programs. “ThelDLE ators forallintents and purposes a Suse simple text editor with Python features, colour coding and soon much nthe sae vei as Sbme. You ener code 25 you would within the Shel so taking an example from the previous tutorial, enter: printC*Hello everyone!") ESTESEDD You can see thatthe same colour coding isin place Inthe IDLE Editor asitisin the Shel, enabling you tobetter understand what's going on with your code. However, to ‘execute the code you need to first save it. Press FS and you get a Save...Check box open, © Cickon the Ok butonin the Sve box and select a cus? destination where you'll save all your Python code. The destination can be a cedcated Felder called Python oryou ‘anjust dump it wherever you lke, Remember to keep a tidy drive though, to help you out inthe future. Saving and Executing Your Code (c} SED enxera name foryourcode, nth for Susp ‘example, and click on the Save button. Once the Python code is savedit's executed and the output willbe detalledin the IDLE Shell n this case, the words Hello everyone! FETTER Thisishow the vast major of your Python code willbe conducted. Enter it into the Editor, hit F5, save the code and look atthe output inthe Shell. Sometimes things will difer, depending on whether you've requested a separate window, but essentially that's the process's the process we wil Use throughout this book, unless otherwise stated Et shel_De ane wrt We TE aa ee TT ee ye reais yee IF you open the file location ofthe saved Python. code, youcan see that it ends in apy extension. Thisis the default Python file name. Any code you create will be whatever py and any code downloaded from the many Internet Python resource sites will be oy. Just ensure that the code is written for Python 3 SPEED sts extend the code and entera few examples, 2 be2 rname="David” surname="Hayword” printCname, surname) print (a+b) IF you press FS now youll be asked to save the file, again, as t's been modified from before. Siar) you click the Ok button, the File willbe ‘overwritten wit the new code entries, and ‘executed, withthe output in the Shel I’s not a problem with just these Few tines butf you weretto edt a larger file, overwriting can become an issue. Instead, use File > Save As from within the Editor tocreatea backup, Now rate a new fle. Close the Eto, nd open Susy anew instance (File > New File from the Shell). Enter the following and save tas hello: ‘a="Python” be"is? c="cool!” print(a, b, ¢) ‘You will use this code in the next tutorial Talo. Renepboamarai yon Comhalo py Oat Getting Started with Python Executing Code from the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made inthe GUI at the command line level. Ez Python, in Linux, comes with two possible ways o BED Now you'e atthe command tine we can stat ‘executing code via the command line. One of the Python, For Python 3 you need to enter the he and python3 and press Enter. This will put you into the ‘on. Fir ll, with the familar three right: hon 2, whilst the other uses the Python 3 libraries hough, drop into the command tine or Terminal on Your operating system, Enis EED sm here you're able to enter the code you've : looked at previously, suchas: we're using a indows users will ai an2 i printCa) You can see that it works exactly the same. 5 users can get access mmand line by clicking Go> Utities» Terminal wu bmpublcatonscom Executing Code from the Command Line BED sorceeietosctnenecormndtner en EEEED) te eutotrringrytonscoie tombe prompt. Enter the Folder where you saved the code from the tothe differences between the jesn'terror out in any way, dh vious tutorial and lst the available files within; hopefullyyou way Python 3 handles the Print command over Python 2, the result should see the hello.py ile, isn’t as we expected, Using Sublime For the moment, open the hellopy file, BED From within the same Folder as the code you're BED Since Sublime Text isn't available For the Raspberry ‘going to run, enter the following into the you're going to temporarily leave the P for the ‘command line: moment and use Sublime as an example that you don't necessarily need to use the Python IDLE. With the hello file open alter itto FSEIRIADELLNTPD include the Following: This wll execute the code we created, which to remind yous: aaaeinatComattisiyominane?, ‘as*Python” printC‘Hello,”, name) an cacool!” print(a, b,c) FE rly sincetisisPython 3code ui EEE sete tees works when you vse the python command ryeuthe ty thesame code with wth ythen 2 by entering python3 hello. py python hello.py ‘The result willbe the original Python is cool! statement, togethe with the added input command asking you For your name, and displaying tin the command window. ora mpublcatonscom C3 Getting Started with Python Numbers and Expressions es ne Coane eure ota ae anise ener MR ee oreo Mead eS anemone ETE Ke] et] lke (oll) UML aU Naat MP) ARSC Colma ee oR ConA UROL Cm IT’S ALL MATHS, MAN You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, maths isthe driving Force behind the code. FEPTEM open up the Gui version of Python3,asmentioned EM You can use all the usual mathematical operations: {you can use ether the Shel or the Ecitor. For the divide, multiply, brackets and so on, Practise with a time being, you're going to use the Shelljust to warm ourmaths Few, For example: ‘muscle, which we believe isa small gland located atthe backoFthe 4 brain (or not) a a 24293 G24") ar = eet FEE in sot crete fotnin: FEEIB oven coutnatced don pode nn decimal aber Pettis ecole orfoaing pci sft Hove Fureed afta = SeSseesssz05 Shports ode ner ten cn we adoue sak ue You can see that Python can handle some quite large numbers. C Numbers and Expressions Cl ‘You can also use an operation to see the remainder leftover From dhision, For example: 10/3 ‘will display 3,333333333, which is of course 3.3-ecurting. you nowenter: 103, ‘This will display 1, whichis the remainder let over From dividing 10 into 3, EEE excep we have the power operator,or exponentiation iF you want tobe technical To work ‘ut the power of something you can use a double mutiplcation symbol or double-staron the keyboard: 2083 30°10 Essential, it's 22x2 but we're sure you already know the basics behind maths operators. This show you would workt ou in Python. vinies ndres npr stron atriee coerce ast bing) This will be displayed as 0b11, converting the P Sus integer into binary and adding the prefix Ob to the Front Fyou want to remove the 0b prefix, then you can use: format(3, *b’) ‘The Format command converts value, the number 3, toa Formatted representation as controlled by the Format specification, the part. BTEEED *800Iean Expression isa logical statement that will either be true or false. We can use these to compare data and test to see ifit’s equal to, less than or greater than. Try this inaNewFile: a=6 b=7 print(1, a == 6) print(2, a == 7) print(3, a == 6 and b == 7) print(4, a == 7 and b == 7) print(5, not a == 7 and b == 7) print(6, a == 7 or b = 7) print(7, a == 7 or b = 6) print(8, not (a == 7 and b == 6)) print(9, not a == 7 and b == 6) Execute the code from Step 9, and you can see a series of True or False statements, depending on the resut of the two defining values: 6 and 7. t's an extension of ‘what you've looked at, and an important part of programming. Na AVAXHOME? nee cd providing you various content: LC eC a Ee ee eS mea eas ces Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction PRE Uys ETC emer ol Tei AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu C3 Getting Started with Python Using Comments ena Oem are Nuch areal Percere RM ole Ne eseR-LO Te Mela Tele -mKele meer] Follow the code line by line but over time, it can become difficult to read. #COMMENTS! Programmers use a method of keeping their cade readable by commenting on certain sections. fa variabl ‘programmer comments on what it’s supposed to do, for example. I's just good practise. is used, the FETED S2ttby creating anew instance of the IDLE Editor ESTEEM Resave the code and execute it. You can see that the (File > New Fle) and create a simple variable and ‘outputin the IDLE Shel is stil the same as before, print command: despite the extra lines being added, Simply put, the hash symbol () denotes aline of text the programmer can insert to inform them, an andthe oats nego ato ese eg ore Swe eflesndeeate be cote eosin Taare OID VRE CONES AD) = (oe tat ram Bn Stan dons ESTER Penning the code willreturnthe ine: The value of A ENTE Levs assume that the variable A that we've created is, 10intothe IDLE Shell window, which is what we Is the number of lvesina game. Every time the ‘expected, Now, add some ofthe types of comments you'd normally player dies, the value is decreased by 1. The programmer could seewithin code: insert aroutine along the lines of # Set the start value of A to 10 na-1 o=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 A is,”, a) Whit ve now that th variable Ais ves and Susp that the player has just lost one, a casual viewer or someone chectng the cde may nt ko Iagie For amoment thatthe code twenty thousand lneslong, stead of st ut seven. You can see how handy comments are, FETTER Essentially, the new code together with comments could look tke: # 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! ona-1 # Inform player, and display current value of A lives) print(*You’ve just lost a life!”) printC*You now have”, a, “Lives teft!”) Fe sore counesnatowsuny fo tatoursnnt oe goernucene he mebe de 4 This is the best game ever, and has been developed by a crack squad of Python experts 4 who haven’t slept or washed in weeks. Despite being very smelly, the code at Least # works really well. Inline comment ar comments that follow section Sua of code. Take our examples from above, instead oF inserting the code on a separate line, we could use: 010 # Set the start value of A to 10 printC*The value of A is,”, a) # Print the current value of A o-a-1 # Player lost a life! printC*You’ve just lost a life!”) printC*You now have”, a, “Lives left!) # Inform player, and display current value of A (lives) FATED 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 ist print statement, you would use: # print(“The value of A is,”, a) intc"The value layer lost 3 1ife! sont [F Inform player. and display current value of A (2ives) Prant("You've just lost life!" Print(-You non have". a, “lives left!*) ‘oualso use three single quotesto comment Susy ‘out a Block Comment or multiline section of comments. lace them before and afer the aresyou want to comment for themeo 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. Using Comments Cl C3 Getting Started with Python Working with Variables We've seen some examples of variables in our Python code already but it’s always romantic cna enbece ta ees itecieia) NUTONE VARIOUS VARIABLES You'll be working with the Python 3 IDLE Shell in this tutorial. IF you haven't already, open Python 3 or close down the pr IDLE Shelt to clear up any old code. In some programming languages you're required touse a dollar sign to denote a string, whichis a ‘arable made up of multiple characters, such as a name ofa person. InPython this isnt necessary. For example, inthe Shell enter: nane="David Hayward” (or use your own name, unless you're also called David Hayward). BATES Youcan check the type of variable in use by issuing the type () command, placing the name of the variable inside the brackets. In our example, tis would be: type name). Adda new string variable: title="Descended from Vikings”. PEPE Youve seen previously that variables can be concatenated using the plus symbol between the variable names. In our example we can use: print Cnane + *: “+ title), The middle part between the quotations allows us to ‘add acolon anda space, as variables are connected without spaces, ‘so weneed to add them manually. 1 Es Se) oy Ets om cae) coo) ae Combine variables within anther variable For example, to combine both name and tile variables into anew variable we use: charactersnane +“: + title Then output the content of the new variable as: print character) Numbers are stored as different variables: oge=44 Type Cage) Which, as we know, are integers. (wor ing with Variables Cl ESTED However, you can't combine both strings and integer type variables inthe same command, 35 you ‘would a set of similar variables. You need to either turn one into the ‘other oF vice versa, When you do try to combine both, you get an error message: print Cname + age) Bia print (character +“ is “+ strCage) +“ years old.") oryou can use: print (character, ‘Thisis a process known as TypeCasting, The Python codeis: sage, “years old.) Notice again thatin the last example, you dont need the spaces between the wordsin quotes asthe commas treat each argument to print separately >>> print (nane + age) Traceback (most recent call last): File “". line 1, in rane fname * age) Typetrror: Can't convert “int object to str inplicitly SeeSorane (enaracter' #2" atr(age) + years old David Hayward: Descended from Vikings is 44 years old. SSSlorine (characters sis", age, sears old.) David Hayward: Descended from Vikings is 44 years olé. 1 “Another example of TypeCasting is when you ask for input from the user, such as a name. for example, enter ‘age= input (“How old are you? “) All data stored from the Input commands stored asa string variable. eae See et This presents abit ofa problem when you want to work with @ 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 will 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; remember: Siar) numbers that have a decimal point in them. For example, enter: shirt=19.99 Now enter type(shint) and you'llsee that Python has allocated the number as a oat’, because the value contains a decimal point. fisezset | le Eat shel Debug Options windows lp python 3-4-2 Coefoule, Get 19 2048, 13:31771) type Scepyaghe "erediter or "Licansey” for wore inforation 33 Gpetaniee) cclaat fio 25h cert hago tt Bae, Tas F “LeenseQ™ for more information. C3 Getting Started with Python User Input WASTE Co) uate a eee Raa Aeole Mice ACR a eel y earlier, so now would be a good time to Focus solely on how you would get information Tee sm nce aetna USER FRIENDLY The type of input you want from the user 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. BTEERDD fi:snot already open the Python 3 DLE Shel and start a New File inthe Editor. Let’ begin with something really simple, enter: printC*Hetlo”) firstname=input¢“What is your first name? “) print(*Thanks.") ‘surnane=input(“And what is your surname? “) PEPIIPD save and execute the code, and as you already no doubt suspected, in the IDLE Shel the program will ask for your first name, storing itas the variable firstname, followed by your surname; also store in its own variable (curname). oe at te is ower Fee yu se nt "Now that we have the user'sname stored in a couple of variables we can call them up whenever ise) we want printC*Welcone”, firstnane, surname, you're well today.”) “. T hope BEER Bun the code and you can seea slight issue, the full stop 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”, firstnane, surnames. I hope you're well. today.) User Input ‘You don't always have to include quoted text within M7 user their name, and have the input inthe line below printC‘Hello. What’s your name?”) name=inputC) useringut py - home/pi/Documents/Python Code/ts) [Ele Edt Format fun Options windows Hep ‘prank Hello. What” your nane?™) Panesinpat() ESTEE The code from the previous steps often regarded asbeing alittle neater than having a lenathy ‘amount of text in the input command, butt’s not arule that's setin stone, so do as you lke in these situations. Expanding an the code, tay this print¢*Halt! Who goes there?”) nane=input() est Farmat Bin Stans woe ep met PEPIIED) |: 2 g00d star to atext adventure game, perhaps? Now you can expand on it and use the raw input from the user to flesh out the game ite: ‘if name=="David”: printC*Welcome, good sir. You may pass.”) else: printC*I know you not. Prepare for battle!’ SS ie Set Fart in Sta nde ep Wiavoncocaceces nase tie sagen ated oer agent them to a fight. ESTEE ust2s you learned previously, any input from a Users automatically a string, o you need to apply a ‘TypeCast in order to turn it into 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”) Fate = floatCinput(“Rate: “)) ‘EOE Famst Bun Spon nds Hep BETTSET DD 1 finalise the rate and distance code, we can ade 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 3 Floating point number rather than astring. C3 Getting Started with Python Creating Functions Nera (thence Tatts ta cirs oe a ean Maan sce aclete (Men (oa UA LMU te RCM ed oa eee Teen eco Teo a eaTe0A) enables you to define your own Functions. FUNKY FUNCTIONS ‘A function is a command that you enter into Python to do something. It's alittle ‘works on it and then returns the result, ce of self-contained code that takes data, It’s notjust data thata function works on. They can do all manner of useful things in Python, suchas sort data, change items from one format to another and check the length or type of items. Basically, a function isa short word that’s Followed by brackets, For example, len0, list or typed). FETED A function takes data, usually a variable, works on it depending on wat the Function is programmed todo and,eturnsthe end value. The data being worked an goes Inside the brackets, so if you wanted to know how many letters are in the word antidisestablishmentarianism, then you'd enter: Len¢“antidisestablishmentarianisn’) and the nurnber 28, would return, BRTERE DD You can pass variables through Functions in much the same manner. Let's assume you want the number of letters ina person's surname, you could use the following ‘ode (enter the text editor for tis example): ame=input (“Enter your surname: “) count=Len(name) print C*Your surname has“, count, “Letters in im Press FS and save the code to execute it. Python hastens of functions builnt it, Fartoo ‘mary to getintoin the limited space available here. However, to view thelist of bultin functions available to Python 3, navigate to wawv.docs.python.org/3/ibrary/functions:html, These are the predefined functions, butsince users have created many more, they're nat the only ones availabe. Additional Functions can be added to Python through modules, Python has a vast range of ‘modules availabe 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 tall the math module functions. FORGING FUNCTIONS Creating Functions Tose a function from a module enter the name of the module Followed by a Fullstop, then the name ‘of the Function. For instance, using the math module, since youve just imported it nto Python, you can utilise the square root Function To.doso, enter math. sqrt(16) ‘You can see thatthe 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. nod eet oa Oe erect foci eee Me variable, the user's na Seas accept the variable name, otherwise it print een et eas eA eer ‘What you've just done is import the Hello Fur eee eure Canine ee te nee ee te C3 Getting Started with Python Conditions and Loops eon Ieee Ce Se IE ee ccc n knead elenrmeolol oes OWA ORM Tu Ke ete elk CEN RNA Ancol NLR Nee} 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 it isn't. STEERED ct’s create 2 new Python program that will ask BRTERE DD Xow you can use anifstatement to checkif the the user to input a word, then check it to see it's word length variable is equal to Four and print 3 afourletter word or not. Start with File» New File, nd begin with Friendly conformation iit applies to the rule the input variable: wordsinputC“Please enter a four-letter word: “) wordzinput(“Please enter a four-letter word: “) _ word_length=Len(word) if word Length == 4: print (word, “is a four-letter word. Well done.”) a ~The double equal sion ( something else. means checkif something is equal to Now we can create anew variable, then use the en ‘Thecolon atthe end of I els Python that ifthis, BALD fancion and passthe word viable trough to MM tatement str do everthing after te colon get the total number of letters the user has just entered: that's indented. Next, move the cursor backto the beginning of wordsinput(“Please enter a four-letter word: the Editor word_lengthelen(word) wordsinput(“Please enter a four-letter word: “) word_Length=lenCword) if word_length == 4: print (word, “is a four-letter word. Well done”) else: print (word, “is not a four-letter word.) Press F5 and save the code to execute't. Enter a fourletter word in the Shel to begin with, you should have the returned message that t's the word is Four letter, Now pressF5 again and rerun the program but ths time enter a five-letter word, The Shell will display that t's not a four-letter word. LOOPS Condtonsandtoors CE Now expand the code to include another conditions. Eventually, it could become quite complex. We've ‘added a condition for three letter words: word=input(“Please enter a four-letter word: “) word_Length=lenCword) if word_tength == 4: print (word, “is @ four-letter word. Well done.) elif word length print (word, “is a three-letter word. Try again.”) else: print (word, “is not @ four-letter word.) eet era nae en ee ee Ne en eed Det ree ian a et en Soe eo os oe Srigerany kt STEP 1 rasaers coon Sree = i bitte x < 10 print GO) oe eens ets ae pes STEP 2 urements Perea i Eien the current value of x, th eae Pres aay PEPER the For loop ic another example. Fors eres apts prords=f*Cat™, “Dog, “Unicorn? for word in words: eae ‘example by using the range Functior for xin range C1, 10):) ) Bebe? eee ee eer ett Cio ai a 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, pip install pygame ED erences conatyenteratenyn, EEA tere tisoneaues anette ine exaple. Sadly other modules aren avayeaalable good Windows users can serch for MD athe tart buona example on non-Pi platforms isthe pygame module, which contains click the result then click Run as Administrator. Linux and Mac users many functions to help create games. Try: mport pygame. 3n.use the Sudo command, with sudo pip install package. wu bmpublcatonscom Python Modules Close the command prompt or Terminal and relaunch the IDLE Shell when you now enter: ‘import pygame, 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 ‘nique, these are usually the source of errors in execution due to them being missing. BETTS) The modules contain the extra code needed to achieve a certain result within your own code, as \we've previously experimented with. For example: ‘import. random Brings in the cade 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)) [ta ae 5 PEPTED) This code, when saved and executed, will display ten random numbers from 1 to 25. You can play around with the code ta display more or less, and fram a great or lesser range. For example: ‘import random for i in rangeces): rintCrandom.randint(1, 100)) ‘Multiple modules can be imported within your code. Sua To extend our example, use: import random import math for I in range(s): printCrandom.randint(1, 25)) print(math.pi) Bown =a BRTEEER the results a string of random numbers followed by the value of Pi as pulled from the math module using the print(math.pi function. You can also pullin certain Functions from a module by using the From and import commands, such as: rom random import randint for i in range(s): print(randint(L, 25)) be EETTSET DD This helos create a more streamlined approach to programming. You an 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.pid Of course, adding comments helps to tel others what's going on, Dey vitamin - a x Say Hello to C++ ee OC nea PES Eu ele tee cello ae) UN Ue et tue ee CEU Lae PT ce eeu CLL ele) Re Keer Teale uke teacCd Pree reco aces C++ is the driving Force behind most of what you Pee Mun cee extraordinarily powerful language to get to grips with. In this section, we look at how to installa C++ eu Cun tgccutic worabmpubcatonscom Why C++? eee gas Cr cc caterer ACHE called C with Classes, the language was renamed C++ in 1983. t's an extension of the original C language and is a general purpose object-oriented (OOP) environment. CC 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 ere of home ‘compting labs and by regular people who didn't have access tothe computing, C++, or rather C with Classes, was the brainchild of mainframes and large computing data centres. Danish computer scientist Bjame Stroustrup while working on his PhO thesis. Stroustrup's plan was to Further the original language, C's impact the digital word is immense. Many of the programs, Which was widely used since the early seventies. _applications, games and even operating systems are coded using ‘Ct For example, all of Adobe's major applications such as C++ proved to be popular among the developers of the'80s,, Photoshop, InDesign and so on, are developed in C++. You will find since it wasa much easier environment to get to ats with and that the browser you surf the internet with written in C++, as ‘more importantly, it was 99% compatible with the original C ‘well as Windows 10, Microsoft Office and the backbone to Google's language. This meant that itcouldlbe used beyond the mainstream search engine. Apple's macOS is writen largely in C++ (with sorne Co ‘coe code is much faster than thatof Python. 1] #include 2 | using namespace std; 3. | void main() 4 |O(char ch; 5 cout<<"Enter a charater to check it is vowel or not"; 6 cin>>ch; 7 switch (ch) 8 io ( 9 case'a': case'A': 10 cout< App Store. inthe Search box enter Xcode’ then turns into install App. Enter your Apple ID and press Return There are many suggestions filing the App Store and Xcode begins to download and install It may take some time ‘window butts the First option, Xcode, that youneed toclickon. depending on the speed af your internet connection FER iesorentcwnan teas RBIS ns ssnon son aon rinenectetiecninee cartes tmeumencrierreamacimeceren 10.126 or later to install and work. ‘changes tothe system. When that is done, Xcode begins to install, ‘additional components, (How to Set Up C++ ona Mac Cl With everything now installed, including the additional components, xcode launches, displaying the version number along with three choices and any recent projects that you've worked on; with afresh install though, ths is blank a Welcome to Xoode FETED S21tby clicking on Create New Xcode Project; this. ‘opens a template window to choose which platform you're developing code For. Click the macOS tab, then click the Command Line Tool option. Click Next to continue. Fillin the various fields but ensure that the Language option atthe bottom i set to C++; simply choose it from the drop-down list. When you'e filed inthe field, ‘and made sure that C++ isthe chosen language, clickan the Next button to continue, Te next step asks hereto create aGitRepostory Sug for all your Future code. Choose a location on your Mac or network location and ick the Cestebuton when Youve done althat you cantar to code. Thelen pane deta the ies used Inthe C+ program youre codhng, Conte mnainepp fein thet, BRTESE DD You can see that Xcode has automatically completed a basic Hello World program for you ‘hile it may not make much sense at present, you wil discover more as you progress, the content is just Xcode utlising what's ‘available on the Mac. Liars 1 1% hen you wanttorun the code, click on Product> Susy Run. You may be asked to enable Developer Mode nthe Mag this to authors ade to perform functors without needing your password every session. When the program executes, the output is displayed at the bottom of the Xcode window. PEs Say Hello to C++ How to Set Up C++ in Linux LINUX++ IF you're not familiar with Linux, then we recommend taking a look at one of our Linux titles From the BOM Publications range. IF you have a Raspberry Pi, the commands used below work just fine and for this example we're using Linux Mint. FETED The fist step isto ensure Linux is 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 Return and enter your password. These ‘commands update the entire system and any installed software. Fe Ee Ww Sar Temi Help PEPER ost Linux distros come preinstalled with all the necessary components to start coding in C++showever, t's always worth checking to see if everything 's present, Stil within the Terminal, enter: sudo apt-get install build-essential and press Return. you have the right components nothing is installed; iF you're missing some then they are installed by the command, wm publications com BSED sr2zinal, that’s it, Everything s already for you tostart coding. Here's how to get your frst C++ rogram up and running, In Linux Mint the main text editor s Xe, ‘hich you can launch by clicking on the Menu and typing Xed into, the search bar. Click on the Text Editor button inthe righthand pane toopen it FEPPR 10 Xed, or any other text editor you may be using, enter the lines of code that make up your C++ Hello ‘World program. t'sa litle efferent to what the Mac produced include Saves BRIM sefore you can execute the C++ file you need to and choose a folder in which to save your program. compile. In Linux t's common to use g++, an open Name the File ashelloworld.cpp (it can be any name as long asithas source C++ compiler, as you're now in the same folder as the C++ pas the extension), Click Save to continue, file, enter: g++ helloworld.cpp in the Terminal and press Return Fie 66 Vow tach Tei ee BPR the st thing to notice isthat xed has FIR ics shorttie whilethe code compiled by automatically recognised this asa C+ fle, since the dt but providing there are no mistakes or eros n fleextesion snow set o.cpp. The colour coding spresentinthe the code you are returned tothe command prompt. The compiling Cove andi you open up the Me manager you can aso see that fle’s ofthe code has create a new le. you enters into the Teil icon has C+ stamped oni youn se that alongside your C++ lets 2. out BERTI D) with your code now saved, drap into the Terminal SIIB the aout file isthe compiled C++ code. Torun again, You need to navigate to the location of the code enter: fa.out and press Return. The the C++ fileyou've just saved. Qur examples inthe Documents words ‘Hello World! appear on the screen. However, a.out ist Folder, so we can navigate to it by entering: ed Documents, very friendly. To name it something else postcompiling, you can Remember, the Linux Terminals case sensitive, so any capitals recompile with: g++ helloworld.cpp -0 helloworld, This creates an ‘must be entered correctly output file called helloworld which can be run with: fhelloworld, Fett Vow Seach Teri Hep Fit Yon tach Tb ee ora bpublcationscom Other C++ IDEs to Install IFyou want to try a different approach to working with your C++ code, then there are foltSnleyKodime) aol E-\=L1C ol Men VoL AUialeco eR Men Miro oko aCoa Cece N cor |B) ad 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. ren Ste Eclinseisahugely popular C++ IDE that offers FRSTEMTTE odelite isa free and open source IDE that's the programmer a wealth of Features, has a regularly updated and avaliable for Windows, ‘great, clean interface, is easy to use and available For Windows, Linux and macOS. t's lightweight, uncomplicated and extremely Linux and Mac. Head over to wwwelipse.org/downloads/ to powerful. You can find out more information as well as howto download the latest version. If you're stuck, click the Need Help link download and instal it at www.codelite.ora/. for more information, Viiwioer ceue™ ‘The GNAT Programming Studio (GPS) sa powerful ‘Another popular choice is NetBeans. This ‘and intuitive IDE that supports testing, debugging 's another excellent IDE that's packed with and code analysis. The Community Edition is Free, whereas the Features and a pleasure to use. NetBeans IDE includes project based ro version costs; however, the Community Editionis available for templates for C++ that give you the ability to build applications with \windows, Mac, Linux and even the Raspberry Pi Youcanfinditat dynamic and static libraries. Find aut more at www.netbeans.org/ wwrwadacore.com/downtoad. Features/cpp/index.html. ( Other G++ IDEs to instal Cl RTE Microsoft's Visual Studioisa mammoth C++ IDE that allows you to.create applications for Windows, Android, iOS and the web. The Community version is Free to download and install but the other versions allow 2 ree tral period, Go to www.visualstudio.com/ to see what itcando For you. RST Ts Save File As. Create or find @ (on File> New > Empty File or press CurisShift#+N on the keyboard. suitable location on your hard drive and inthe ile Name box, call ithelloworld.cpp. Click the Save as type box and select C/C++ Files. ‘lick the Save button. ESTER ow youcan see a blank screen, withthe tab Bee You can see that Code:Blocks has now changed labelied *Untitiedt, and the number one inthe top the colour coding, recognising thatthe file's now left of the main Code:.Blocks window. Begin by clicking in the main C++ cade. This means that code can be auto-selected from the window, so the cursors next to the number ane, and entering Codes.Blocks repository, Delete the tinclude line and —— re-enter it. You can see the auto-select boxes appearing, C Your First C++ Program Cl FERED) 2vtoselection of commands s extremely handy and cuts out potential mistyping, Press Return to getto line 3, then enter: int mainQ "Note: there's no space between the brackets PeimvcisaliSias hie gy PEErrre FETED) onthe nextline below int maind, enter a cuty bracket: { ‘This canbe done by pressing Shift and the key tothe right of Pon an English UK keyboard layout. Notice hat Codelackshas automatically rete Suey a corresponding closing curly bracket a couple of lines below, inking the pair, as well as slight indent. Thisis due to the structure of C++ andit’s where the meat of the code is entered, Now enter: My first CH program ieveiswiSiae mie. [Note again the colour coding change. Press Return at the end of the previous steps line, and then enter ‘cout << “Hello, world!\n"; std: COPIED Gals Gee zeen «emia Bas 2am oar: Just as before, Coder-Blocks auto-completes the Code you're entering, including placing a closing Siar) speech mark as soon as you enter the first. Dont forget the semicolon atthe end of the line; this sone of the most important ‘elements to a C++ program and wel tell you why in the next section. For now, move the cursor down to the losing curly bracket and press Return. aiasjors. eusiemig ioe ire Sft he Tacalnendo tert monus Fay =~ Zz 2 ) C++ Fundamentals ) Structure of a C++ Program ad een ine Reet eu Me Rag OL Tae ee een fata as small as a semicolon, and your entire program wil 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. = #INCLUDE (Baits) hetoveriiow X) The structure of a C++ program C+ wasinvented by Danish isquite precise. Every C++ code asec mate one Came student Bjarne Stroustrup in begins with a directive: #include 1979, as apart of his PhD. ‘©. The directive instructs the thesis initially C++ wascalledC pre-processor to include 2 vith Clases, which added section ofthe standard C++ Featurestothe already popular code. For example: include C programming language, includes the while making ta more iostream header to support User friendly environment input/output operations. through anew structure Blame Stroustruy INT MAIN() [Stthee X) *helloworld.cpp | {nt main) intiates the q declaration ofa function, which isa group of code statements under the name ‘main’. All (C++.code begins at the main function, regardless of where it actually lies within the code. #include int main() 2 3 4 cI 6 BRACES ‘The open brace (curly brackets) something that you may not have come across before, ‘especialy if you're used to Python, The ‘open brace indicates the beginning of the main function and contain allthe code that belongs to that Function include int main() rT aneene 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 code, explain what's going on, There are two types (of comment: /* covers multiple line comments, // single line. Lines that begin with a double slash are comments. This means they won't be executed in the code and are ignored by the compier. Comments are designed tohelp you, or another programmer looking at your code, explain what's ‘going on. There are two types of comment: /* covers ‘multiple ine comments, // 3 single ine, ane main) ev C Structure of a C++ Program Cl << ‘The two chevrons used here are insertion operators. This means that whatever Follows the chevrons isto be inserted into the std:cout statement, In this case they're the words Hello, world, hich are to be displayed on the screen when you compile and execute the code, STD \while std stands for something quite different, in C++ it means Standard. 's part ofthe Standard Namespace in C+, which covers ‘a number of ifferent statements and cornmands. You can leave the stds part out of the code but it must be declared atthe start with: using namespace std; not both. For example: #include using namespace std; COUT Inthis example we're using cout, which isa part of the Standard "Namespace, hence why t's there, as you're asking C++ to use itfrom that particular namespace. Cout means Character OUTput, which displays, or prints, something to the screen. If we leave std: out we have to declare it atthe start of the code, as mentioned previously. 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 lke, as long asits inside the quotation marks. The brackets aren't needed but some compiles insist on them, The \n partindicates a new line isto be inserted cout << "Hello, world!\n" ; AND} Finally you can see that lines within a Function cade 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 compiler Fails to build the code. The very ast ine has the closing brace to indicate the end of the main Function. Tathew | *heloworkdcop >| Finclade sing namespace staz int main () ‘ cont “helloworkicpp _~) 2] tsnciuae ‘using namespace sta: int main() cout << "Hello, world!\n"s z= C++ Fundamentals) Compile and Execute SO er Ne eseee it een N Mi cech ce eet nia Re emer ee ea aut uke ceukcet Memrn tg you prefer, the program and see how it looks. GREETINGS FROM C++ Compiling and executing C++ code from Code::Blocks is extraordi result, Here's how it's done. FR sect runny ly easy; just a matter of clicking an icon and seeing the SEED St2rtby clicking onthe Build icon, the yellow cog the CodeBlocks compiler and checked For any errors. You can see the results of the Build by looking to the bottom window pane. Any messages regarding the quality ofthe code ae displayed here. PEPPER i yourcode is looking similar tothe one in our screenshot, then look to the menu bar along the top of the screen. Under the Fortran entry in the topmost menu you can see a group of cons: a yellow cog, green play button and a cog/play button together. These are Build, Run, Build and Run functions. g Fortran wxSmith Tools Or & oO auidlog | $F Build messages | _f) CopCheck/Ve in “no project” (compiler: unknown) === 0 warning(s) (0 minute(s), 0 second(s)) s, lees "Now click on the Run icon, the green play button, ‘commandline box appears on your screen spaying the words Hello, word Fllowed by the time it’s taken to execute the code, and asking you pressa key to continue. Well done youjust compiled and executed your fist Cr+ program conpiesrdcecte COU trios cout << “Hello, world! \n" (|/Starthere 3<| *helloworld.cpp x include cout << “Hello, world\n”; A ss 2 using namespace std: 3 4 _ int min(y SIRI ws tnp vasceganance s oe : g namespace att - © sot mane 7 || cout << "He110, world!\n" 5 a 6 7 | cout << eetio, worid!\a"s a? : 10 > |, n " Es In order to apply the new changes to the code, you [Now click the Build and Run icon again to apply the need to re-compile, build, and run it again. This time, changes to the code, This time Code::Blocks refuses however you cansimpy click the Bul/Run ion thecombined.toexecute the code, dve tothe err you putin nthe Log pane at yellow cog and green pay button, thebottom othe screen you are informed ofthe ero, this se Expected '’ before token, indicating the missing semicolon FETT Just as we mentioned in the previous pages, you FETS ERERD Replace the semicolon and under the cout tne, don't need to have std:cautiFyou already declare enter a newline to your code: sing namespace std; at the beginning of the code. We could have easily clicked the Bulld/Run con to begin with but it's worth going through the avaliable options. You can also see that by building and The \n simply adds anew line under the last line of outputted text cout << “And greetings from C++!\n"; running, the file has been saved. Build and Run the code, ta display your handiwork * = 2oaaerix slorson 2 w= /PB RRBs meelsal Side h | =~ Zz 2 ) 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, i actual Fact theyre probably one of the most important Factors. THE IMPORTANCE OF COMMENTING ‘Comments inside code are basically human readable descriptions that detail what the code is doing at that particular point. They don't sound especially important but code without comments is one of the many frustrating areas of programming, regardless of whether you're a professional or ust starting out, In short all code should be commented in sucha manner asto effectively describe the purpose of alne, section, or individual elements. You should getin 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 t's ‘going to do simply by reading your comments Ina professional environment, comments are vital to the success of the cade and ultimately the company. In an organisation, many programmers work in teams alongside engineers, other developers, hardware analysts and so on f 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 trail to pinpoint theissve, Place yourself 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 littie help from the ‘original programmersin the form of ‘good comment. ‘The best comments are always concise using namespace std; int main ant main) q | BREED Se2ttsimole by creating two variables, aandb, with (one having a 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 bi a= 10; =55 sane main) You can build and run the code butit won't do ‘much, other than store the values 10 and 5 tothe integers a and. To output the contents of the variables, ad cout << a; cout << "\n"; cout << b; The cout <<"\n'spart simply places anew line between the output of toands. PEPEP DD Naturally you can declare anew variable, call it result and output some simple arithmetic: int resul result «a +b; cout << result; Insert the above into the cade as per the screenshot. “eros Ca Youcan sign avauietonwralessconasyos ETRE) Tepes step ets evar ates, Susp declare it. The code you've typed in could look like: Suze which is a global variable. Ina game, For example, this, instead! ‘aplayer’s ives go up or down depending on how well or how bad = they're doing, When the player restarts the game, the StartLives| int a= 20; returns to its default state: 3. Here we've assigned 3 lives, then amneae subtracted 1, leaving? lves lft. int result = a +b; : cout << result f FETED The modern C++ compiler is far more inteligent os than most programmers give it credit. While there ‘are numerous datatypes you can declare For variables, you can in fact use the auto Feature: include using namespace std; ‘auto pi = 3.141593; BETESED S0exifc to C++, you can aso use the Following int maine) to asign values toa variable as soon 3s you j declare them double area, radius = 1.5; int a G0); * srradiuss i— area = pi * radius * radius; ‘Ten rom the C++ 2011 standard using cry brackets EERIE ‘int result {a+b}s ¥ [eres flere vecteeee FeTeER AD You can create global 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 EXERT courte of new elements here: first, auto won't local variables: variables used inside the Function. For example: a area tick the box labelled ‘Have G++ Follow the C++11 15O C++ Language #include Standard [std=c++1J. Then, the new data type, double, which using namespace std; means double-precision floating point value. Enable C++, then int StartLives = 3; build and run the code, The result should be 7.06858, int main © { startLives = StartLives = cout << Startlives; C++ Fundamentals. Data Types THE VALUE OF DATA There are many different datatypes avaliable forthe programmer in Ces, such as an integer, floating point, Boolean, character and so cn. I's widely accepted that there are seven basic datatypes, 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 Four fer] Foot] Rouble weroret hotd These basic types can also be extended using the Following modifiers Long, Short, Signed and Unsigned, Basically this means the modifiers can expand the minimum and maximum range values for each data ‘ype. For example, the int datatype has a default value range of 2147483648 to 2147483647, a fair value, you would agree. Now, ifyouwere to use one ofthe modifiers, the range alters: 00 4294967295 2147483648 to 2147483647 Unsigned int Signed int 2768 to 32767 ‘ong int = 2147483647 to 2147483647 Signed Long int =-2147483647 to 2147483647 Unsigned Long int = Oto 4284967295 Naturally you can get away with using the basic type without the ‘modifier, as there's plenty of range provided with each datatype. However, it’s considered good C++ programming practise to use the ‘modifiers when possible. ‘There are isues when using the modifiers though. Double represents a double-floating point value, which you can use For ww bmpublcations com incredibly accurate numbers but those numbers are only accurate upto the fifteenth decimal place. There's also the problem when using namespace std; double PI = 3.141592653589793238463; int mainQ) { t cout <«< PI; Starter #include using namespace std; double PI = 3,141592653589793238463; int mainQ) { cout .precision(22); cout << PI; a Starthere 3 4 Sint main() 6 ot 7 cout precision (22); ® cout << PI: a ‘Again, build and run the code; as you can see from the command line window, the number represented by the variable Plis diferent to the number you've told C++ to use in the variable. The output reads the value of Plas 3.141502653589793115998, with the ‘numbers going awry from the fifteenth decimal place. Calculator re Scientific Dd 15.142857142857142857142857142857 Des HYP FE me Ms 2 ” sin cos._—tan v 10* log Exp Mod - ce ie « 7 8 9 x nt 4 5) 6 ml + 1 73 3 ai ¢ ) 0 . = ‘This is mainly due to the conversion from binary in the compiler and that the IEEE 754 double precision standard occupies 64-its ‘of data, oF which 52-bits are dedicated to the significant (the significant digitsin a floating-point number) and roughly 3.5-bits are taken holding the values 0 to 9. IFyou divide 53 by 35, then you artive at 15.142857 recurring, which is 15-cigits of precision ‘To be honest, iF you're creating code that needs to be accurate to more than fifteen decimal places, then you would’ be using C+, you would use some scientific specific language with C++ as the ‘connective tissue between the two languages, You can create your own data types, using an aiasike system called typedef. For example: =<] using namespace std; typedef int metres; int main) { metres distance; distance = 15; cout << “distance in metres is: “ << distance; This code when executed creates a new nt datatype called metres Then, in the main code block, there's a new variable called distance, hich isan integer; so you'e basically telling the compiler that there's another name forint. We assigned the value 15 to distance ‘and displayed the output: stance in metres i 15. Iemight sound alittle confusing to begin with but the more you use C++ and create your own code, the easier it becomes. =~ Zz 2 ) C++ Fundamentals ) Strings Seen cn C Rte ceca cunt Colt lM ee RN ole sere MV ol MUR Sle alee Ene cool Cellet Ra RRO MAL eke STRING THEORY There are different ways in which you can create a string of characters, which historically are all carried over From the original language, and are still supported by C++. ‘Tocreate astring you use the char function. Open a new C+ file and begin with the usual header: #include using namespace std; int main © bs } wealaaforson gaye ec @sirv using namespace std; int main © les easy to confuse a string with an array. Here's an array, which can be terminated with a null character: char greet[8] = {'W’, ‘e’, ‘1, *c’, ‘0%, ‘m?, BETTSEDD Guild andrun the cade, and Welcome’ appears fon the screen. While thisis perfectly fine, it's nota string, A string a class, which defines objects that can be represented asa stream of characters and doesn't need to be terminated lke an array. The code can therefore be represented as: #include using namespace std; int main © { char greet{] = “Welcome”; cout << greet << “\n"; you can enter: In C++ there’ alco a string Function, which works in ‘much the same way. Using the greeting code again, #include using namespace std; int main © a *e, Ws string greet = “Welcome”; cout << greet << “\n"; cout << greet << “\n"; 3 } te FED) There are also many different operations that you can apply with the string Function. For instance, to getthe length ofa string you can use #include using namespace std; int main © { string greet = “Welcome”; cout << “The Length of the string is: cout << greet.size() << “\n"; PPP vou can see that we used greet size0 to output the length, the number of characters there are, ofthe Contents ofthe string. Naturally if you call your string something ‘other than greet, then you need ta change the cammmand to reflect this. It's always stringname.operation. Build and run the code to see the resus. PETTSEAD You can of course add strings together, or rather combine them to Form longer strings: #include Using namespace std; ‘int main © { string greet = “Hello”; string greet2 = “, world!”; string greet3 = greet + greet2; cout << greet3 << “\n"; ‘int main QO { length = greet3.sizeQ); cout << “The Length of the combined strings is: << length << “\n"; PTT Using the available operations that come with the string Function, you can manipulate the contents of 2 string. For example, to remove characters froma string you could use: #include using namespace std; int main © i string strg (“Here is a long sentence in a string.”); cout << strg << "\n’; strg.erase (10,5): cout << strg << ‘\n"; strg.erase (strg.begin()+8); cout << strg << “\n’; strg.erase (strg.begin()#9, strg.end()-9); cout << strg << ‘\n’; FETS ER ED |S worth spending some time playing around with the numbers, which are the character positions in the string, Occasionally, it can be hit and miss whether you gett right, so practice makes perfect. Take a look at the screenshot to see the result of the code. C++ Maths Oe DUE eMC EEN UIT eter ser casio Pen Rel SenCe en cueaur gekeed eer old tier eu a er CCM nec conics a een ters Rc tae een venaG The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++ ‘Math Library, you can also calculate square roots, powers, trig and more. FPR matneratt operations faow the Matipleaton addin canbe ape 2 50h same pater asthe ought in scoe nthat #include ‘multiplication and division take precedence over addition and subtraction, You can alter that though. For now, create a new file Using MNEs oR ttt and enter int main © { #include float numbers = 100; using namespace std; IT] runbers = nunbers * 10; // This multiplies 100 : by 10 float numbers = 100; cout << numbers << “\n"; numbers = nunbers +10; // This adds 10 to the nunbers = nunbers / 10; // And this divides initial 100 1000 by 10) cout << numbers << “\n"; cout << nunbers << “\n"; numbers = numbers - 10; // This subtracts 10 } from the new 110 cout << numbers << “\n"; PEPER wile simple, does get the old maths muscle ‘numbers variable. While you can happily use an integer, if you FEI D c2n, execte the simple code ad see the resus suddenly started to use decimals, you would need to change toa While not particulary interesting, it's start into Gr float or a double, depending on the accuracy needed. Run the code maths. We used afloat here, so you can play around with the code and see the results. ‘and multiply by decimal places, as well as divide, add and subtract. (Coons CE Everything From computing cosine to arc tangent with two parameters, to the value of Pl, You can call the header with: #include #include using namespace std; int main © Sita Start by getting the square root ofa number: #include #include using namespace std; int main © { float nunber 134; cout << “The square root of “ << number << “ is: * << sqrtCnumber) << “\n"; } Here we rested anew ost cle number and Suhr used the sqrt(number) Function to display the square rotof 134, the value ofthe varibe number Bul and run the code, and your answer reads 11.5758. FETED 2lculting powers of numbers can be done with: include ifinclude using namespace std; int main © { float nunber = 12; cout << number << “ to the poner of 2 is “ << Pow(number, 2) << “\n"; ‘cout << number << “ to the poner of 3 is “ << Pow(nunber, 3) << “\n"; cout << number << “ to the power of .08 is << pow(nunber, 0.8) << “\n } FETED ere we created a float called number withthe value of 12, and the pow(variable, power) is where the calculation happens. Of course, you can calculate powers and ‘square roots without using variables. For example, pow (12,2) ‘outputs the same value as the frst cout line in the code. The value of Plis also stored in the cmath header library. tcan be called up with the M_Pl function. Enter cout << M_Pt;into the code and you get 3.14159; ar you can use it to calculate #include #include using namespace std; int main © i double area, radius = 1.5; area = MPI * radius * radius; cout << area << “\n": Now you've got the basics down, you can improve and learn more essential skills in our next guide... PY THON & C++ Coming soon! LANDSCAPE MAKE YOUR PHOTOGRAPHY OWN PC MAC OS CATALINA OUTDOOR PHOTOGRAPHY CANON Black Dog Media Master Your Tech To continue learning more about your tech visit us at: ee aa ea com Peon ence ce Vea oc a Ae aera ese eae) Print & digital editions = iPh Featuring the very latest updates = one = . Mac Step-by-step tutorials and guides ‘ E Created by BDM experts li ety Sa | Check out our latest titles today! Special Deals and Bonus Content Sign up to our monthly newsletter EM RMm noc Re Ne Cee Re oN Tn eel and get the latest updates, offers Uo Mle ORCC and news from BDM. We are here to help you Master Your Tech! bdmpublications.com/ultimate-photoshop

You might also like