0% found this document useful (0 votes)
150 views68 pages

Linux Coding Tricks and Tips - 14th Edition 2023

Uploaded by

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

Linux Coding Tricks and Tips - 14th Edition 2023

Uploaded by

grm club
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 68
Linux 4! Coding roganmingsnd = & POGramming coding Linux Next level fixes and secrets get to the heart of Linux, Python & C++ We share our awesome tips and shortcuts for coding and programming (% TRICKS & TIPS Pyaar tw 3a le | | Bile Ca033 bs iPhone iw ne 16 CRT Pass 4 : Y it A Ct (J PCy Dy A a7, a a S| aan TRICKS LAS Linux Coding & Programming Linux Coding Tricks & Tips is the perfect digital publication for the user that wants to take their skill set to the next level. Do you want to enhance your user experience? Or wish to gain insider knowledge? Do you want to learn directly from experts in their field? Learn the numerous short cuts that the professionals use? Over the pages of this essential advanced user guide you will learn everything you will need to know to become a more confident, better skilled and experienced owner. A user that will make the absolute most of their coding use and ultimately Linux itself. ~- Over the page Journey contin and we will be Heb pa ag every stage to advice, An achievement you can earn inform and ultimate by simply enabling us to inspire you to y exclusively help and teach you 90 Furthep. the abilities we have gained over our decades of experience. fete lay Sau en eae) SC een ness 7 een h oem Porn eu ecstacy Freon eee ere foe Coa eae Peay Data Types ca Coe Maths een) Pre ae eno Common Coding Mistakes LAM Te acd ALO a ee NM eK ON kA OM Le) nee Cie eeely ie paleo Mel eM ey Ax aOR eee Renee eee at ey into any form they wish. A Linux user can change their OS look and feel from one day to the next, install thousands of freely available apps and programs Clie Nel asa deel ice ke) a meet) coy) Soames Python on Linux Python is a fantastic programming language, Mateo eee Ts Peer nent eetecn satan eno leg coe DNL uel} Roem eeu ee eee eed lively community behind it that shares knowledge, CEE Psat eee ee ncaa Future releases. We've used a Raspberry Pi for this section of the book, asit's Linux based and one of the best coding Pern Ce RSA cro Dede cue ur ee CMe ce eaten con renee 7 Why Python? There are many different programming languages available For the modern computer, and some still available For older 8 and 16-bit computers too. Some of these languages are designed for scientific work, others for mobile platforms and such. So why choose Python out of all the rest? PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. ‘These pioneers of programming carved their way into anew frontier, Forging smal routines that enabled the letter’ to scroll. ‘across the screen. lt may not sound terribly exciting to a generation that's used to ultra high-definition graphics and open world, multi player online gaming, However, forty something years ago it was blindingly biliant. 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 to its limits and Founded the billion pound gaming empire that continually amazes us. Regardless of whether you use an Android device, (OS device, PC, ‘Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin to-acar, set-top box or athousand 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 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 will interact with its ts tar fot bal OO tet ae nee sO) — ¥)|¥ nscrict oot ¥) Bacc# oe Bowe en certssenteeronie g oe gare 4 rab eed void Arrayctrl::chitdLostrocus() it(curgor >= 0} Ref reshow cursor): cect sche tdbestrocue() id Arraycerl::Paint (Oras w) Lrtarnst Paine’) Size size = oftsize(); 38 Cet ak ‘ertorad Gator fe erent) whiteta = catcounet)) fetop = osttiner (a) rbostom forint } column. catcoune(): jst+) { header oti abs} Tele [Link]() - 1)} == 0) Lend (scolorbisabled, scolorPeper): obs fiteetop > stzecey) break Sop f oattanacy(a): coli. cetcount() = 015 ‘environment or users. Operating systems, such as Windows, macOS ‘and such are usually a combination of C++, Ci, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and so on, More general-purpose programming is used to create programs, ‘pps, software or whatever else you want to cal them. They're widely used across all hardware platforms and suit virtually every conceivable application. Some operate Faster than others and some {are easier to learn and use than others. Pythons 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 a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless ‘more interactions, Whilst it’s not a streamlined as a Low-Level Language, which can deal directly with memory addresses, cal stacks and registers, ts benefits that it's universally accessible and easy to learn, /7FiTe: Tavoke java, Finport java. [Link].*; class anvoke { DibnerSEicke vote maine sering (1 args) < lass = Class fornane args(0) 3 hethod'g = c-getsethod( argstll, néw Class Git ie object ret = [Link]( nuT1, nuT1 5 [Link] rjvokae seatis method: * + args [i +" of class: " + args{o] ey T+ wishino args\oneselts: * + pet 95 + cach ¢ Classnocroundexception ) 77 *Class. forname(. can't find the class + Caveh ( iosuchethodexcepeion €2°) { U7 that method doesn't exist 3 Gace { ETlegansccessexcepeion 3.) ( Five don't“Rave persission to snvoke that aechod 2 Gatch ¢ rnvocationrargereyeepeion of ) {, ‘an exception ocurred white invoking that aethod oe [Link] Sethod threw an: "+ ef, getTargetexception( ")°; D Javaisa powerful language that's used in web pages, set-top boxes, ‘TWsand even cars. Why Python? ow Python was created over twenty sixyears ago and has evolved to become an ideal beginners language for learning how to program a 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 extemal hardware and the computer itself Python is free to download, install and use andis avaliable for Linux, Windows, macOS, MS-DOS, 05/2, BeOS, IBM series machines, and even RISCOS. Ithas been vated one ofthe top five programming languages in the world and is 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. BASIC was once the starter language that early S:bithome computer users learned. Python is a more modern take on BASIC, ‘and makes for an ideal beginner's programming language. TP Python on Linux 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're sticking with Linux Mint For this particular tutorial. Feyouneedtoncetainidhecionl rehon ESERSER nour ce ve ve btyten 2a Sua? is currently installed in your Linux system. To begin. a? 3 as ong as Python [Link] installed, then the code in ur tutorials wll work. Its always worth checking to seeif the distro has been updated with the latest versions, so enter: sudo. apt-get a —_ update && sudo apt-get upgrade to update the system, davidedavid-Mint:~ with, drop into Terminal session From your distro’s menuor hit the CertealteT keys Fle Et View Search Terminal Help Crees | FETIP Nextenter python --version into the Terminal [ESPFM once the update and upgrade completes, enter: screen. You should have the output relating to python3 --version again o see if Python 3x version 2.x of Pythan inthe display. By installed; as long as you have Python 3.x, you're running the most recent major version. The numbers after the 3 indicate patches and further updates. Often they/re unnecessary but can contain vital new elements. ult, most Linuxdlstros__ is updated or come with both Python 2 and 3, as there's plenty of code out there stil available For Python 2. Now enter: python3 =-version. anvidavis ine = eet BPR sve you wantte tex, cating edge Suns version, you need to build Python From source. Start by entering these commands into the Terminal: sudo apt-get install build-essential checkinstall sudo apt-get install Libreadline-gplv2-dev Libncursesw5-dev Libssl-dev Libsqlite3-dev tk-dev Libgdbm-dev Libc6-dev Libbz2-dev ESTED Within the Python Folder, enter: /confgure sudo make altinstall This could take a while depending on the speed of your computer, Once Finished, enter:python3.7 --version tocheck the installed latest version. You now have Python 3.7 installed, alongside ‘older Python [Link] and Python 2 (Open up your Linux web browser and go to the Python download page: [Link]/ ‘downloads. Click on Downloads Followed by the button under the Python Source window. This opens a download dialogue box; ‘choose a location and start the download process. ‘of the downloaded Python source code with: tar ~xvF Python= 3.Y.Y.-[Link] replacing the Y's with the version numbers, you've downloaded. Now enter the newly unzipped folder with ed Python-3.Y.¥/ Inthe Terminal, go the Downloads Folder by entering cd Downloads/. Then unzip the contents BeTeEED othe GULIDLE, you need to enter the following ‘command into the Terminal: sudo apt-get install idle3 The IDLE can then be started with the command idle3. Note that IDLE runs different version from the one you installed from source, FETE ERE You stsoneed PIP (ip installs Packages) whichis tooltohelp you install more modiulesand extras. Enter: sudo apt-get install python3-pip \When PIP 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 distro's menu: How to Set Up Python in Linux ; 42 my Python on Linux Starting Python for the First Time TNMs eo ial aac carck kena uy you will need to manually install the Python IDLE. This is due to the Pi team removing the core Python IDLE in Favour of their own coding text editor. STARTING PYTHON For those using the Pia and new Raspbian, drop into a Terminal and enter: sudo apt-get install idle3. Older versions of Raspbian already have the official Python IDLE pre-installed. With the Raspbian desktop adedcickonthe ERIN roc example, inthe sheltenter. 242 Men bution Followed by Programming Python fer ress Ente the ex ne splays the 30DLE, This opensthe Python 3shel Wndowsand Mac werscan_ answer 4 Basal Pjthon estate hee’ and prosucedthe find the Python 3 DLE Shel om wthinthe Windows Star button eleventeuput inet nie ee FETTER The shelliswhere you can enter code andsee the RAWAM The Python shell acts very much tke a calculator, responses and output of code you've programmed since code i basicaly a series of mathematical into Python. This sakind of sandbox, where you're able totryout interactions with the system. Integers, which are the infinite some simple code and processes. sequence of whole numbers can easly be added, subtracted, ‘multiplied and so on, y (Starting Python for the First Time ow FETED While thats very interesting it's not particularly BETEE The Psthon IDLE sa configurable environment. exciting, Instead, try this: you dont like the way the coloursare represented, os then you can always change them via Options > Configure IDLE and brint(“Hel toeveryone!”) clicking on the Highlighting tab, However, we dortt recommend ust enter itinto the IDLE as youve done in the previous steps that, as you wont be seeing the same as our screenshots. ee eee « ‘Thisisa little more lke it, since youve just produced ust like most programs availabe, regardless of the {your first bit of code. The Print commands Fairly ‘operating system, there are numerous shortcut self-explanatory, itprints things, Python 3 requires the rackets_s__keysavalable. We don't have room for them all here but within the well as quote marks in order to output content tothe screen, inthis Options > Configure IDLE and under the Keystab, you can see lis, ‘case the Hello everyone! bit ofthe curent bindings. >>> print("Hello everyone | Hello everyone! Pe >>> | ["Tinneense stein | Farce Youmnsy have noticed the colour coding within BEER the Python IOLE is a power interface and one the Python IDLE. The colours represent different that’s actually been written in Python using one ‘elements of Python code. They are: of the available GUI tools. you want to know the many ins and ‘outs of the Shel, we recommend you take a few moments to view Black Data and Variables Eke Use eons [Link]/3/ibrary/[Link], which detalls many of Green Strings Dark Red ~Comments ee Purple—Functions Light Red ~Error Messages ‘Orange- Commands asm IDLE Colour Coding [eetear— veetor_exeneies | Pure | Funaions | aend) meine tres [Enormessoes | syntanteroe Sree Your First Code LSS ular WAN OLA ELSTON ecu nol Mae (re Kolmeore MU Tiea en ne WIC} Cn ola Mit ae eMC OU MM eR MLE -Uco UM ee Xo) 1g Col oO (leek dora eT] Las Colo) 1 entering your code and playing around with some other Python examples. 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. iF youve closed Python 3 DLE, reopen tin You can see thatinstead ofthe number 4, the BALE icheveroperting system version you pretend cots isthe 2-2you asked to be printed tothe the Shell, enter the Familiar folowing screen. The quotation marks ae defining whats being outputted ee tothe IDLE Shel: to print the total of 2+2 you need to remove print(*Hello") lereaes print (22) “sto predicted the word Hel poets inthe You can continue seh, printing 22, 4642343 Suda ‘Shell as blue text, indicating output From a string. Suz? and so on to the Shell. An easier way is to use a Its Fairly straightforward and doesn't require too much explanation. —_ variable, which is something we will cover in more depth later. For Now try ow, enter: print(*242") a2 What you have done here isassign the letters a and b two values:2 and 2. These are now variables, hich can be called upon by Python to output, add, subtract, divide {and s0 on For as long as their numbers stay the same, Try this: print(a) print(b) ‘Ue Est a ay tem o_o Your First Code e 1 Now let's add a surname: Sid ‘surnane="Hayward” print(surnane) ‘Younow have two variables containing a First name and a surname and you can print them independentiy (pe EO te Gun ene res wen BTTEREED The output ofthe last step displays the current values of bath a and b individually, as you've asked them to be printed separately. F you want to add them up, you can, use the following print (a+b) ‘This code simply takes the values ofa and b, adds them together and outputs the result. ‘De tar Oot beg Sours wnat He ‘oucan lay around wth ferent Kinds of arabes Su? and the Print Function. For example, you could assign variables for someone's name: rrame="David” print(nane) ERTeEED we were to apply the same routine as before, using the + symbol, the name wouldn't appear correctly inthe outputin the Shell. Try print(nane+surname) ‘Youneed a space between the two, defining them as two separate values and not something you mathematically play around with, ‘oe bet) tes game uote FETS REED | Python 3 you can separate the two variables, ‘with aspace using a comma: print(name, surname) ‘Alternatively, you can add the space yourself: print(nane+" “+surnane) “The use of the comma is much neater, as you can see, Congratulations, you've just taken your fist steps into the wide ‘world of Python. ine eae rt cnt or are tration, my Python on Linux Saving and Executing Your Code While working in the IDLE Shell is perfectly Fine for small code snippets, it's not designed for entering longer program listings. In this section you're going to be introduced to the IDLE Editor, where you will be working from now on. EDITING CODE ‘You will eventually reach a point where you have to move on From inputting single lines of code into the Shell. Instead, the IDLE Editor will allow you to save and execute your Python code. ESTEEM Fist open the Python IDLE Shell andwhen its up, JME You can see that the same colour codingis in place click on File > New File. This wil open a new window in the IDLE Editorasitisin the Shell, enabling you ‘with Untitled asitsname. This isthe Python IDLE Editor and withinit to better understand what's going on with your code. However, to you can enter the code needed to create your Future programs. execute the code you need to first save it, Press FS and you get 2 Save...Check box open. ESTER The IDLEEditor is, for allintents and purposes,a FETEEEDD lickonthe OK button in the Save box and select a simple text editor with Python features, colour Save As from within the Editor to create abackop, (EB Fame Bin tin nm ep cre FETTER you open the ile location of the saved Python code, you can see that itends in [Link] extension, Thisis the default Python file name. Any cade you create willbe \[Link] and any code downloaded from the many Internet Python resource sites willbe py. Just ensure that the code s written For Python 3 Now create anew file, Close the Editor, and open anew instance (File > New File from the Shel). Enter the Following and save itas hello py: a-"Python” be"is” cool!” print(a, b, c) ‘Youwill use this code in the next tutorial 1 tame br we PY Python on tinux Executing Code From the Terminal COMMAND THE CODE Using the code we created in the previous tutorial, the one we named [Link], let's see how you can run code that was made inthe GUI at the command line level. Artenintins oevah ne posbiewarct ERRIRE vow ours comand ine wecanet Sud? ‘executing code via the command line. One of the Python. For Python 3 you need to enter the ‘waysis with Python 2, whist the other uses the Python 3libraries command python3 and press Enter. This will put you into the and so on First though, drop intothe command ine of Terminalon command line version ofthe Shell, with the Familiar three right your operating system, Facing arrows asthe cursor (>>) ED estes before, Windows users will, the Start button and = search for CMD, then clickthe Command Line returned search; You can see that it works exactly the same, and macOs users can get access totheir command ine by licking Go> utlities > Terminal Executing Code from the Terminal ty BED oreessestotstenettecrmaaineryten BEEF teense thon snd emt previous tutorial and lst the available Files within; hopefully you way Python 3 handles the Print command over Python 2, the result should ee the hello,py File, isn't as we expected, Using Sublime For the moment, open the hellopy ie. ce Sublime Text isnt available forthe Raspberry smamecmccngcie” — EEED : Pi, you're going to temporarily leave the Pi forthe ‘moment and use Sublime as an example that you don't necessarily reed to use the Python IDLE. With the [Link] file open, alterit to Pyttions ELOY Py) include the following “ee Thiswill execute the code we created, which to remind you is pane inout emiatetsryourananaracD python” print(“Hello,”, name) print(a, b, c) Natural since this isPython 3 code using the Save the hellopy fe and drop back tothe Su? ‘syntax and layout that's unique to Python 3, it only UES command line. Now execute the newly saved works when you use the python3 command. IFyou tke, ry thesame cade with: with Python 2 by entering: — python [Link] The result willbe the original Python is cool statement, together with the added input command asking you For your name, and ying it in the command window. * ry * * * * * Sa ack aaa nem. Pa y» Python on Linux Numbers and Expressions ANAM M YE eA Le aT UAT Ie Cel oot kel A Lea SCORE LCR TeLe SOTA Rey like. Let's expand on that now and see just how powerful Python is as a calculator. You eR ee MULE aN eno) Aaah) Kem aan ae) cole Cen Come U New File) and create a simple variable and uz? ‘output in the IDLE Shell is still 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, mie and others, of what's going on without the user being aware print(*The value of A is,”, 0) ‘Save the fileand execute the code. uring the code wl erate the The value of A Letsassue thatthe variable that weve created Suda is, 10 into the IDLE Shell window, which is what we uz? is the number of lives in a game. Every time 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. aroutine along the lines of # Set the start value of A to 10 ana an10 print(“You've just lost a life!") # Print the current value of A print(“You now have”, a, “Lives left!") print(“The value of A is,”, a) Whilst we know that the variable As lives, and that the player has just lost one, a casual viewer or someone checking the code may not know, Imagine For a moment that the code is twenty thousand lines long, instead of just our seven, You can see how handy comments ae. Bay Essentially, the new code together with comments couldlook tke: x # Set the start value of A to 10 anid ‘# Print the current value of A print(“The value of A is,”, a) ‘# Player lost a life! o-a-1 # Inform player, and display current value of A lives) print(*You've just lost a life!” print(*You now have", a, “Lives left!") C (_ Using Comments ow PEPER cine comments are comments that follow a section ‘of code. Take our examples from above, instead of inserting the code on a separate line, we could use: a=10 # Set the start value of A to 10 print(“The value of A is,”, a) # Print the current value of A ana-1 # Player lost a life! print(“You’ve just lost a life!”) print(“You now have”, a, “Lives left!”) # Inform player, ond display current value of A (Lives) BPP the comment, the hash symbol, can also be used to ‘comment out sections of code you dor‘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) 4 print "The value of A is, Player lost’ life! F Inform player. and display current value of & (Lives) prantc-vou've just lost a, 1ifet"). rane(-You now have", 3, “lives Lefe!~) | Friction. alin of 4 ‘Youcan use comments in different ways. For example, Block Comments area large section of text that details what's going on inthe code such as 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. FEET BD) You also use three single quotesto comment ‘uta Black Comment or multi-line section oF comments. Place them before and after the areas you want to comment for them to work: This is the best game ever, and has been developed by a crack squad of Python experts who haven’t slept or washed in weeks. Despite being very smelly, the code at least works really well. my Python on Linux Working with Variables NARMS CUN RTL nana eae neore Clee eee worth going through the way they operate and how Python creates and assigns certain Neo WU (om VARIOUS VARIABLES You'll be working with the Python 3 IDLE Shelt in this tutorial. IF you haven't already, open Python 3 or close down the previous IDLE Shelt to clear up any old code. Insome programming lrguages youre required Yeu've seen previously that vaibles can be us to use a dollar sign to denote a string, which is Suze ‘concatenated using the plus symbol between the variable made up of multiple characters, such asa name of a person. variable names. In our example we can use: print (name + “: In Python this isnt necessary. For example, inthe Shell enter: “+ tittle). The middle part between the quotations allows us to name="David Hayward” (or use your own name, unless you're adda colon and a space, as variables are connected without spaces, also called David Hayward). so we need to ade them manually. [ie Est oh Dn Gt aoe ‘You can check the type of variable in use by HEED Youcan also BD sing the ype commond, placing thename of — aa combine varibles the variable inside the brackets. nour example, his would be. within another variable. For ‘type (name). Add anew tring variable: titles"Descended example, combine bath name from Vikings”, and title variables into anew: variable we use: character-name + title 2 “Then output the content of the new variable as: Ste acne re viking print (character) eet Numbers are stored as different variables: age-44 Type (age) Which, as we know, are integers. However, you can’t combine both strings and integer type variables in the same command, asyou ‘would a set of similar variables. You need to elther turn one intothe ‘other or vie versa, When you do try to combine both, you get an, ‘error message’ print (name + age) Working with Variables ow PEPER This presents a bit of aprablem 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, youneed to enter: int(age) + 10 “This wil TypeCast the age string into an integer that can be ‘worked with, gta sear in ec tr mei ‘hiss a process known as TypeCasting. The Python code is: aa print (character + old.”) “is “4 strCage) + * years ‘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 a the commas treat each argument to print separately >>> print (name + age) ‘Traceback (most recent call Last) File “™, line 1, n print (nave * age) Typetrror: can't convert ‘int’ object to str implicitly S38"prane (character +" s='" + str(age) +." years old David Hayward: Descended fron Vikings is 14 years olds SSs'print (character, "is", age, years old.-) David Hayward: Descended from Vikings is 48 years old. ‘Another example of TypeCasting is when you ask For input from the user, such asa name. for example, enter: ‘age= input (“How old are you? “) All data stored from the Input commands stored asa string variable. fle a shel ebup detent windows Hep rae Pa Gela ot 2, BOTT Bre eapfigessscredie” or tices" for aoe intoraton Sm typecone) see er PPI The use of TyneCastingis alco important when Soccnuee) har fia hen combining irkegersané eats Python Suelo usually converts the integer to a Float, but should the reverse ever be applied it's worth remembering that Python doesn't return the exact value. When corwerting a Flat to an integer, Python wil always round down to the nearest integer, called truncating; in our case instead of 19.99 t becomes 19, Ce at 8 bos gs an aa a TT S3Senireeases Soo typetshirt) Saris ee my Python on Linux User Input We've seen some basic user interaction with the code from a Few of the examples earlier, so now would be a good time to Focus solely on how you would get information from the user then store and presenti. 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. database can ask for personal details. Witsotatetopentne neon] [Link],— ERTRRE vow: etree vss ranestoredine cue and start a New File in the Editor. Let’s begin with uz? ‘couple of variables we can call them up whenever something realy simple, enter we want: print (“Hello”) print(*Welcome”, firstnane, surnane, “. I hope firstname-input(‘What is your first nane? “) you're well today.”) printC*Thanks.") Surnanesinput(“And what is your surname? “) Saveand execute the code, andasyouaeady no fun the code and youan see ashtissue, the Suda doubt suspected, in the IDLE Shell the program will Suz? full stop after the surname follows a blank space. {ask for your first name, storing its the variable firstname, followed To eliminate that we can add a plus sgn instead of the comma in by your surname; also stored in its own variable (surname). the code: printC‘Welcome”, firstname, surnames. I hope you're well today.”) User Input ow PEPE You don't always have to indude quoted text within the input command. For example, you can ask the User their ame, and have the input inthe line below print(‘Hello. What’s your name?*) ‘name=input() userinput py - homne/pi/Documents/Python Code/us, Ele Edt Famat Bun Options Windows Help rant Welle. What's your nane?™) ane=input() ‘What you've created here's a condition, which we ull cover soon. In short, we're using the input from the user and measuring it against a condition, So, i the user enters David a their name, the guard wil allow them to pass unhindered. Else, iFthey enter a name other than David, the guard challenges them to aight. Sia} ‘The code from the previous step is often regarded as being alittle neater than having a lengthy Siar ‘amount of textin the input command, but it’s not arule that’s set in Stone, so do as you lke in these situations. Expanding on the code, try this printC*Halt! Who goes there?’ ‘name=input() Ele E88 Farat bin dotons Mowe tp It'sa good star toa text adventure game, perhaps? Now you can expand on it and use the raw input from the user to flesh out the game a litle: STEP 7 if name=="Davia": print(“Welcone, good sir. You may pass.”) else print(“T know you not. Prepare for battle!”) mapas) e eine aka, ied ie. You ay pas.) PPD 2us:2s you learned previously, any input froma User is automatically a string, so you need to apply a TypeCast in order to tumit into something else. Thiscreatessome Interesting additions to the input command. For example: # Code to calculate rate and distance printC*Input @ rate and a distance”) rate = floatCinput(“Rate: “)) Foees Hostclaptttte! FETE ERERD 7 Finalise the rate and distance code, we can ade: distance = floatCinputC*Distance: “)) printC"Time:”, (distance / rate)) Save and execute the code and enter some numbers Using the float{nput element, weve told Python tat anything entered isa floating point number rather than a string, my» Python on Linux Creating Functions NeW Aen a OURS cia-reh nt new File to enter the editor, lets PRED 10 mocity it further, delete the Hellol-Davie’ line, Cg. Cameos laid ee sag ear Cem asens idef_Hello():) print (“Hel 10m} HeLLoC)) ee ron Hello import Hel to Fieltoc“bavid®)) Ce Mcrae e ein Reese atu Cima Pep te giea é Geer rrcns Pgs Dee sea aay Bee result a+b return result eee my Python on Linux Conditions and Loops Cerone wfol nee M Ce) ERO LT Lo ele CHAM Se ea nN Re“ CNT Oe complex. How you use them depends greatly on what the program is trying to 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 iFsomething is TRUE, then doing something else if tint. Lets create new Pthon program that vl ask cue the user to input a word, then check it to see if it's afouretter word or not. Start with File > New File, and begin with the input arable word-input(“Please enter a four-letter word: “) Suda function and pass the word variable through it to. get the total number of letters the user has just entered: word-input (“Please enter a four-letter word: “) word_Length=Len(word), Now we can create a newvariable, then use the len EB) Now you can useanif statementto check ifthe BMD ror tons variables equal to four and rine a friendly conformation if it applies tothe rule: word-input(“Please enter a four-letter word: “) word_length=len(word) if word length — 4: print (word, “is a four-letter word. Well done.”) “The double equal sign ==) means checkif somethings equal to something else FETED The colon at the end of tells Python that if this statements true do everything after the colon that's indented, Next, move the cursor back tothe beginning of the Editor: wordsinput(“Please enter a four-letter word: “) word_length=Len(word) if word_length == 4: print (word, “is a four-letter word. Well done.) else: print (word, “is not a four-letter word.”) Press FS and save the cade to executelt. Enter a Fourletter word inthe Shell to begin with, you the word is four letters his time enter a i display that it’s not aFourletter word, should have the returned message tha Now press FS again and rerun the program but Five-letter word, The Shell LOOPS Conditions and Loops ow Now expand the code to include another conditions. Ma) Eventually it could become quite complex. We've addeda condition for three-letter words: word-input(“Please enter a four-letter word: “) word_length=Len(word) if word length = 4 print (word, “is @ four-letter word. Well done.”) elif word_length = print (word, “is a three-letter word. Try again.”) als print (word, “is not a four-letter word.” ‘Aloop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same Cees a teas meet sie Coes Cs ne naa es STEP 1 Rae ean Au it parrrnetest phite x < 10:} print GD) PED the citference between ifand whileisw fs t0 Cire ears nents still true. tn our example i Parnes pit prints the current val ea ene ee Cas STEP3 Bay ee ee oe nulla jnords-[Cat™, “Dog®, “Unicorn®y) iprintCword)) Cen eg ne pee ie STEP 4 Crary raion {for x in range CL, 10):) print GO} Oe eee Ce eee eee eaten m= Python on Linux Python Modules MASTERING MODULES In this instance we're using Windows 10 to demonstrate installing modules, since they're already there in Pi OS. The same steps apply for those Linux distro that don't Feature any modules, so don’t worry about cross platform compatibility. ERED vst good te bitin functions win ts 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, a STEP 3 ) ‘The resultis an errorin the IDLE Shell asthe Pygame module isnt recognised or instal Python. To installa module we can use PIP (Pip Installs Packa Close down the IDLE Shell and drop into a command prompt o Terminal session, At an elevated admin command prompt, enter: pip install. pygane FETED some modules, especially on the Raspberry Pi ri modules aren't always available. A good example on non-Pi platforms is the Pygame module, which contains many Functions to help create games, Try: import pygame. Ee The PIP installation requires an elevated status due i installing components at different locations. Windows users can search For CMD via the Start button and right click the result then click Run as Adminis Mac users canuse the Sudo command, with s ator, Linux ani Close the command prompt or Terminal and relaunch the IDLE Shell, When you now enter: ‘import: pygane, the module wll be imported into the code without any problems. You'll Find that most code downloaded or copied from the internet will contain a module, mainstream of Unique, these are usually the source of eras in execution due to, them being missing. & Python Modules ow PEPER Muttiote modules can be imported within your code. [Link] our example, use import random ‘import. math for I in range(s): print ([Link](1, 25)) print([Link]) ia oat PPM the modules containthe extra code needed to achieve acertain result within your own code, 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 lke for i in range(10): print([Link](1, 25)) a BETS The resultis a string of random numbers Followed by the value of Pas pulled from the Math module Using the print(math.p) Function. You can also pullin certain Functions From a module by using the from and import commands, suchas: from random import. randint for i in range(5): print(randint(1, 25)) Boe = This code, when saved and executed, will display ten Sus random numbers from 1 to 25. You can play around withthe code to dsplay more orlss and froma resto leser range. For example: import random for i in range(25): [Link](1, 100)) ES eGRED Tishelpscreate a more streamlined approach to programming, You can also use import module*, ‘which wil import everything defined within the named module. However, it's often regarded as a waste of resources but it works. nonetheless. Finally, nodules can be imported as aliases: ‘import math as m print([Link] OF course, adding comments helps to tell others what's going on. mnt cement BAF =a x pom ; ale .* A | Pag Yel AAT eL Ula 0 buil ” ~ C+ton we LINUX ered na eee neue Cac ~~ Rete a eee} Fee nee meee etl Ce ee ecu eee hkere ta Coen eats cures Posen eri etesa arg C++ is the driving Force behind most of what you use ona daily basis, which makes ita complex and extraordinarily Peet cn ean ee acy behind Linux itselF, as well as most of the behind the Peet et cede eee ue gues ifnotall, operating systems. See ON acca Eee) Linux using a Raspberry Pi, From there, you can begin to Crete oe cD 4 » C++ on Linux 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 back to 1979, the start of the golden era of home computing labs and by regular people who didrit have access tothe ‘computing, C++, or rather C with Classes, was the brainchild of ‘mainframes and large computing data centres. Danish computer scientist Bjarne Stroustrup while working on his PAD thess. Stroustrup's plan was to further the original language, _C++'simpactin the digital world isimmense. Many of the programs, ‘which was widely used since the early seventies applications, games and even operating systems are coded using C++. For example, all of Adobe's major applications, such as ‘CH proved to be popular among the developers ofthe'80s, Photoshop, InDesign and so on, ae developed in C+. You wil find since ie was a much easier environment to get to grips with and that the browser you suf the Internet with written in C++, as more importantiy, I was 99% compatible withthe original C well as Windows 10, Microsoft Office and the backbone to Google's language. This meant that it could be used beyond the mainstream search engine, Apple's macOS fs written largely in C+ (with some GS (C++ code is much faster than that of Python. 1] #include 2 | using namespace std; 3 | void main() 4 |D(char ch; 5 cout<<"Enter a charater to check it is vowel or not"; 6 cin>>ch; 7 switch (ch) 8 jo ( 9 case'a': case'A': 10 cout< ononds Indu comonents Language pucks wom Summary a a aa ce pg ee SG (Microsoft's Visual Studio is great, free environment to learn C++ in. ‘other languages mixed in depending on the function) and the likes begin with Python and spend some time getting to gris with ‘of NASA, SpaceX and even CERN use C++ for various applications, programming structure and the many ways and means in which programs, controls and umpteen other computing tasks. you Find a solution toa problem through programming. Once you can happily power up your computer and whip ‘out @ Python program with one hand tied behind your back, then move on to C++. OF course, there's nothing stopping you from jumping straight into C++; if you Feel up to the task, go for it. CH is also extremely efficient and performs vwellacross the board as wells being an ‘easier addition to the core Clanguage. This higher level of performance over ‘ther languages, such as Python, BASIC and such, makes itan ideal development ‘environment for modern computing, hence the aforementioned companies using it so widely Getting to use C+ is as easy as Python, al ‘you need isthe right set of tools in which [Link] withthe computer in C+ and you can start your journey. ACr+ IDEs Free of charge, even the immensely powerful Visual Studio From Microsoft isfreely available to download and use. You can get into C++ From any operating system, be it macOS, Linux, Windows or even mobile platforms. while Python i a great programming language to learn, C++ puts the developer ina much wider world of coding. By mastering Ci, you can Find yourselF developing code forthe likes of Microsoft, Apple ‘and so on, Generally, C++ developers enjoy ahigher salary than programmers of some other languages and {due to its versatility, the C++ programmer can move between Just tke Python, to answer the question of Why Cr+ isthe jobs and companies without the need to relearn anything specific, answer fs because i's Fast, efficient and developed by mast of the However, Pythan isan easier language to begin with. If you're applications you regularly use. I's cutting edge and a fantastic completely new to programming then we would recommend you language to master. Indeed, the operating system you're Using is written in C++. = «& © © Windowst0 Mac debian ubuntu my » C++ on Linux Your First C++ Program The Raspberry Pi makes for a great coding base on which to learn C++. You won't need any complicated, third-party IDEs or to install any extra components. Everything you need to get started is already built into the Pi. HELLO, WORLI Its traditional in programming for the first code to be entered to output the words Hello, World!’ to the screen. Interestingly, this dates back to 1968 using a language called BCPL. PETTIED voucan usethe included Geary Programmer's PTSD ccocsit look ike much at the moment but you can Editor to write, compile and execute your C++ code ‘get into what the C++ header commands mean in ‘on the Raspberry Pi You can find Geary as the first entry in the due course. Geany uses syntax highlighting, meaning itcolourcodes Programming section From the main Raspberry [Link] the cade depending on the language. To activate this, save the code Geany icon to open and start coding, by clicking on File» Save As. Now name the code [Link] and click the Save button, ESTEE The Geany editor's quite powerfulwhilestillbeing ERTS The colour coding helps a lot when your coding sy to use. Allthe code you enter shows.n the Now press Enter and start anew command online main window and is numbered to help you keep track of your code. 3. Enter the following For naw, inline 1, enter: int main Siete Note: there's no space between the brackets. toe Fle Eat Seach View Document Proje Build Tels Hep Gye -aealex Res cymbals > (hetonatécpp * | Ip ila sk No symbols found ne main) PEPID on thenext tne, below int main, enter acury bracket: t ‘This can be done by pressing Shift and the key tothe right of Pon an English UK keyboard layout. Fis 68 Seach Vew Oscar Pe Geax ae <{ Syria [atone ae, (Your First C++ Program Gl Now you need to clase offthe code, by inserting the ‘opposite, closing, curly bracket. Online 7 enter: t Note that you won't need to backspace to the start ofthe tine, removing the indent, just by entering the curly bracket Geany auto- jumps to the correct part ofthe line, thus ening the code block. Fe ea oven er Done Pet a OH Pep B-toex 4e-08 a2 ESTEE Notice that Geany has automatically created a sight indent. This is due to the structure of C++ and it's ‘here the meat ofthe codeis entered. Now enter: My frst C++ program SH See View Donat Pet Sl Te +Bragiex 4 ao {rie [itm * | Note again the colour coding change. Press Return atthe end ofthe previous step's line and then enter: std::cout << “Hello, world!\n"5 Fle Et Sch View Drone Poet Bull Tool Hp S-b-'oex ae [Syma [rtonna PRP) ssentialy, these are your First steps into the world (of coding in C++. We will ook at the structure of the code in more detail on the next couple of pages; for now though, lick on the Save button as represented by a fling cabinet with a {green downward pointing arrow. File Edit Search View Document Project Buld Tools Help B+ oa R08 [amos once Eee oe ores ile in ae By, eet Se IFyou haven't done so already, its always advisable [Link] ablank folder where you can save all your code. You can have one each for Python and C++ orsimply a single folder called Code, whichever you prefer. ts not anecessity, just good housekeeping =~ (28a amo aa Seats oe > ) C++ on Linux ) Structure of a C++ Program (SEENON Ke inte Rsertent cea R ROR R Nee Mee kell ae) as small as a semicolon, and your entire program will fail to be compiled and executed. Many a professional programmer has fallen foul of sloppy structure. #INCLUDE Learning the basics of programming, you begin to understand the structure of a program. The commands may be From one language to the next but you can start to see how the code works. RSPR, onda vescaruoncr eer ered Peart | [Link] * #include a 2 3 int main() 4 5 oe eres PNTERTISTGRD The structure ofa C++ programs quite FRYER The oven brace (curly brackets) is something that precise. Every C+ code begins witha directive: ‘you may not have come across before, especially if +#include <>. The directive instructs the pre-processor to include _youlre used to Python. The open brace indicates the beginning of the Section of the standard C++ code. For example: include main function and contains allthe code that belongs to that Function includes the iostream header to support input/output operations. [Link] * [Link] * a) include strei #include at! iin) BONE Lines that begin with a double stash 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, and explain what's going on. There are two types of comment 7* covers multiple ine comments and // asingle ine. [Link] * #include int main() 1 2 3 4 5 /My First C+ program 6 7 a While std stands For something quite different, in C++ it ‘means Standard. t's part of the Standard Namespace in ‘C#, which covers a number of different statements and commands. You can leave the std: : part out ofthe code butt must be declared atthe start with: using namespace std; nat both, For example include using namespace std; [Link] * 1 #include 2 3 _int main() 4 5 /imy First C+ program 8 std::cout << "Hello, world!\n 7 |) a Inthis example we're using cout, whichis apart of the Standard Namespace, hence why its there, as you're asking C++ to use itfrom that particular namespace. Cout means Character OUTput, which displays or prints, something to the screen. iFyou leave stc: out you have to declare it atthe start of the cade, as mentioned previously. [Link] * #include SSS using namespace sti int main() Jy first c++ program cout | 2 2 3 4 5 é 7 e |) 8 ( Structure of a C++ Program Gl The two chevrons used here are insertion operators, ‘This means that whatever Follows the chevronsisto be inserted into the std:cout statement. n this case they/re the words ‘Hello, world’ which are to be displayed on the screen when you compile and execute the code. helewori cpp * #include using namespace std; int main() /My first c++ program cout <<| ©ovousune PATTEM Leading on, the “Hello, world” part is what you ‘want to appear on the screen when the code is. executed. You can enter whatever you tke, a5 long as its inside the {quotation marks. Sometimes brackets are needed, depending on the compile. The \n partingicates a new line isto be inserted, //My first C++ program cout << "Hello, world!\n"| Finally you can see that ines within a Function code block (except comments) end with a semicolon. This marks the end ofthe statement; al statements in C++ must have tone atthe end or the compiler failsto build the code. The very ast line has the closing brace to indicate the end ofthe main function. [Link] #include using namespace std; My first c++ program 2 a 3 4 _int main() 5 6 7 cout << “Hello, world!\n"; ° c Li ») = ++ on Linux ) Compile and Execute You've created your first C++ program and you now understand the basics behind the structure of one. Let’s get things moving and compile and execute, or run if you prefer, the program and see howit looks. GREETINGS FROM C++ Compiling and executing code from within Geany is remarkably simple and just a matter of clicking a couple of icons and ‘seeing the result. Here’s how it's done. (Open Geany, if you haven't already, and oad up the previously saved Hello World code you created, Ensure that there are no visible errors, such asa missing semicolon atthe end of the std:cout line. ~}> [helloworid cpp % yp rinclude int main() 2 3 4 At El UMy first Cr+ program 6 Std: scout << "Hello, world!\n 7 |) 8 \henyou cck the Butdicon,the pane atthe ue? bottom of the Geany interface displays some rests, Falis wel you wile successful compilation, Fnot then Geany sues an errr along ith theline the eror was ound on, Gea. ax seo 8 a2 IF your code i ready, look to the menu bar along the top ofthe Geany window. Notice that midway ‘along the line oF icons there's a red brick con. This is Bull, wihich ‘when clicked runs through the code, checking it against the C++ standards to see ifthere are any errors that stop it from running. le Edit Search View Document Project Build Tools Help S-B-idlieax ‘Symbols [Link] @racions || [RN tinclude nan 21 Ant main() f ‘/iMy first C++ program ER Cae Norte , PEP withthe code successfully built, i's nowtime to ‘execute it. Next to the Bulld icon there's a paper aeroplane icon, this isthe Run icon, You cant run code that hasn't been previously built or hasan errorin place. Click the Run icon, int Project Build Tools Help x ge. 7 5 ‘ pp x cr Hin) ‘my first co program td! :eout [heltowort. cpp * #include using namespace std; Ks int main() /MMy First c++ program cout << "Hello, world! \n" eosouaunn STEER sing Return/Enter inthe commandline box BETTE Now ty and buld the code once more. Thistime, closes it, returning you to Geany. Let’ alter the code notice that the bottom panelis displaying an eror, slightly. Under the include ine, enter: regarding the missing semicolon. Notice that eror reads as being a online 8, the frst character, the closed cury bracket. Thisis because cI there'san expected semicolon missing before the closed bracket. ‘Then, delete the st: part ofthe Cout ln; tke so: cout << “Hello, world\n”; ymbols |> {helloworid cpp * rout < > [[Link] * | ver 2g manespace 3: Be rinclode using namespace std; int main() x /0y first c++ program cout << “Hello, world!\n"; Gout << "And greetings From cr+!\n"; BETTER) 2¢ careful when commenting, especialy with block comments. I's very easy to forget to add the closing asterisk and forward slash and thus negate any code that fallsinside the comment block. However, you can also add comments to the end of a line of code, to describe in a better way what's rd going on: cout << “Hello, world!\n"; //This Line outputs the words “Hello, worl ~ The \n denotes a new line. Note, you don't have to put a semicolon at the end of a comment. This is because it's ane in the cade that's ignored by the compile. You can comment out several ines by using the Forward slash and asterisk 7 This comment can cover several Lines without the need to add more slashes */ Just remember to finish the block comment with the opposite asteriskand forward slash Fetoobiacae* | ‘Obviously iF you try and build and execute the code't errors out, complaining ofa missing curly bracket to finish off the block of code. IF you've made the error a Few times, then it can be time consuming to go back and rectify “Thankfully, the colour coding in Geany helps identify comments From code, syrtais [ratowoiaene* | eereeee, ith block comments, t's good practisein C++ to ‘add 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 code: 7 This conment. can + cover several lines ‘+ without the need to add more slashes */ Thankfully, Geany does this automatically but be aware of itwhen using other IDEs, = C++ on Linux ) 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 variable you can declare. Here's how it works. (Open upanew, blank C+ file and enter the usual code headers include using nanespace std; int mainQ) 1 i | [Link] * ‘include Using namespace std; 2 2 3 4 _int main() 5 6 7 a h Start simple by creating two variables, aand b, wth fone 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; int b a= 10; b= Variables cpp * ay Finclude 2 using namespace std; 3 & int nain() 5 of 5 int a; 7 ant bs a 9 a=; 20 be sq a 2 |) BERTIER) You can build and run the code butit won't do much, ‘other than tore the values 10 and 5 to the integers 8 and . Ignore the warnings about variables set but not used, the code still works To output the contents ofthe variables, add: cout << a3 cout << "\n"5 cout << bj The cout €€"*\n"; part simply places newline between the output of 1oand 5 Varabies cp * | since Sostroan say) 3 3 é : 2 a 2 a Fa # int result; Naturally you can declare a new variable, callit result and output some simple arithmetic: result =a +b; cout << result; Insert the above into the code as per the screenshot. You can assign a value toa variable as soon as you declare it, The code you've typed in could look ike this, instead: int a= 10; int b = 5; int result = a+b; cout << result; Specficto C++, you canakso use the Following to assign values to avariabe as soon as you declare ther int @ (10); int b (5); Then, from the C++ 2011 standard, using curly brackets: int result {arb}; se 9 30) el FETED) Vou can create global variables, which are variables that are declared outside any Function and usedin ‘any Function within the entire cade, What you've used soar are local variables: variables used inside the Function, For example: include using namespace std; int StartLives = 3: int main CQ startLives = StartLives = 1; cout << StartLives; #include using namespace std; int StartLives = 3; int main() StartLives = StartLives - cout << StartLives;| ‘The previous step creates the variable StartLives, which is @ global variable. Ina game, for example, a player's ives go up or down depending on how well or how bad they/re doing, When the player restartsthe game, the StartLives returns to its default state: 3, Here we've assigned 3 lives, then subtracted 1, leaving 2 ives left arabes oop * nt min) The modern C++ compiler ifr moreineligent SUZ) than most programmers give it credit. While there arenumerus data types you can declare for varibes,youcanin factuse the atoeatre #include using nanespace std; auto pi = 3.141593; int main) double area, radius = 1.5; area = pi * radius * radius; cout << area; [Link] * sp Pinclude using namespace std; auto pi = 3-141503; int main() 2 3 4 5 6 7 double area, radius = 1.5; area = pi* radius * radius; 20 a 2 |) a PEPPER though we said to ignore the warnings in Step 3, there'sa difference between a warning and anertorInthis case, it's just a simple warning, The new data type, double, means dauble-precsion floating point value, which makes the code more accurate, The result should be 7.06858, Essentially, you can often work with a warning but nat an error. 6) C++ on Linux Data Types Variables, as you've seen, store information that the programmer can then later call up, Tae Rela eee Maelo celle eee TAY eR ue LaY A Cole] eek etree le) the values the programmer assigns, depending on the data type used. THE VALUE OF DATA. ‘There are many diferent data types avallable For the programmer in C++, suchas an integer, Floating point, Boolean, character and so ‘on. It’s widely accepted that there are seven basic data types, often called Primitive Builtin Types; however, you can create your own data types should the need ever arise within your code. Integer | int Floating Point | float Character Boolean Double Floating Point Wide Character No Value char bool double wehar_t void ‘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 datatype. For example, the int data type has 2 default value range of 2147483648 to 2147483647, afair value, you would agree. Now iFyou were to use one of the modifies, the range alters: to 4294967295 147483648 to 2147483647 32768 to 32767 Unsigned Short int = 0to 65,535 Signed Short int =-32768 to 32767 Long int = -2147483647 to 2147483647 Signed Long int = -2147483647 to 2147483647 Unsigned Long int = 0 to 4294967295 Naturally you can get away with using the basictype 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 issues when using the modifiers though. Double represents a double‘loating point value, which you can use For ineredibly accurate numbers but thase 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 defaule only outputs the first five decimal places. You can combat that by adding a [Link] () Function and adding a valve inside the brackets but even then you're stil limited by the accuracy ofthe double data type. For example, try this code #include using namespace std; double PI = 3.141592653589793238463; ‘int main() a cout << PL; } [Link] * include Using namespace std; double PI = 3.141592653500703220463,| Aint main() ( cout << PI; b Build and run the code and as you can see the output is only 3.14159, representing cout's limitations inthis example. You can alter the code including the aforementioned cout: precision Function, for greater accuracy. Take precision allthe way up to 22 decimal places, wth the following code: #include using namespace std; double PI = 3.141592653589793238463; int main [Link](22); cout << PI; t include using nanespace. std: double Pr = 3. 14issz0sa5e07922304 1 5 ine main() ° cout. precision( 2): ) ‘Again, build and run the code; as you can see From the command line window, the number represented by the variable Plis different to the number you've told C+ to use in the variable, The output readsthe value of Plas 3.1415926535897931 15998, with the numbers going awry From the fifteenth decimal place Calculator - a x Scientific 9D 15.142857142857142857142857142857 DEG HYP FE M+ M- MS x = sin. cos tan v 10* log Exp Mod t CE c =| ~ (Data Types Gl Thisis mainly due to the conversion from binary inthe compiler and thatthe IEEE 74 double precision standard occupies 64-bits of data, of which 52-bitsare dedicated to the significant (the significant digits ina floating-point number) and roughly 3.5-bits are taken holding the values 0 to 9 f you divide 53 by 3.5, then you arrive at 15.142857 recurring, whichis 15-daits 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 speci language with C++ asthe connective tissue between the two languages. You can create your own data types, using an aliaike system called typedef. For example: #include using nanespace std; typedef int metres; int mainQ { metres distance; distance = 15; cout << “distance in metres is: “ << distance; [ Datatypes cpp Pinelude tusing namespace. std: typedef int metres; a 2 3 a Sint nain() 6 a 7 ]\ otros distance; @ | Gistence, = 15; << distance; File Edit Tabs Help This code when executed creates @ new int data type called metres. Then, in the main code block, there's anew variable called distance which san integer; so you're telling the compiler that there's another name forint. We assigned the value 15 to distance and displayed the output: distance in metres is 15. Itmight sound alittle confusing to begin with but the more you use C++and create your own code, the easier it becomes. om ay » C++ on Linux Strings Strings are objects that represent and hold sequences of characters. For example, you (eoltl WEN MN e108 Me Dole maore MW3 (o la MOR t< ATL E EU Cod ol called up wherever you like in the program. STRING THEORY ‘There are different ways in which you can create a string of characters, which historically are all carried over from the original Clanguage and still supported by C++. Toute aating eusethedarrcon gene TREE sudden the ce woe pes Sua? new C++ file and begin with the usual header: Suz? onthe screen. While this is perfectly fine, it's. AUER [Link] sa class, which defines objects that can be }________l represented as a stream of characters and doesn't need to be TEST a tesminated like an array. The code can therefore be represented as ican) #include using namespace std; i int main © i stings cpp * char greet{] = “Welcome”; include cout << greet << “\n"; Using namespace std; } include Contre By EI 3 int main() « 8 7 be ‘eing naneopace sed: i aa > Beeveasune PEPER 1's e239 to confuse a string with an array. Here's an array, which can be terminated with a null character: #include CAITR PPT 19.c++ there's also string Function, which works in int main ‘much the same way. Using the greeting code again, you can enter: char greet[8} = {'W" + include 7, NO"; using nanespace std; ‘cout << greet << “\n"; int main © : 1 st = “Welcome”: string greet = “Welcome”; ‘ingsopp * cout << greet << “\n"; } tet, ‘o's tat, tet, N07, || Stings % include sing namespace ste int oni) i é owe é » a ‘There are also mary different operations that you can apply with the string Function. For instance, to get the length of a string you can use: #include using namespace std; int main © { string greet = “Welcome”; cout << “The length of the string is: cout << [Link]() << “\n"; stings opp * I einc ode 2 dog nawepace sti & int main() 5 at : 3 | cour 2cThe Tengen of the string 4s B | Sout << grove ite) cn $ a P BRED Youcan see that we used greet size() to output the length, the number of characters there are, ofthe Contents of the string, Naturally, f you call your string something ‘other than greet, then you need to change the command toreflect this,’ always [Link], Build and run the code to see the results. #include using namespace st int main © { You can of course add strings together, or rather ‘combine them to Form longer strings: string greeti = “Hello”; string greet2 = “, world!"; string greet3 = greetl + greet2; cout << greet3 << “\n”; cpp * include “lone int main() ¢ string greeea = ‘Welle String greet2 = "world String greets = greet + greet2: ‘cout using namespace std; int main © { int. Length; string greet1 = “Hello”; string greet2 =“, world!”; string greet3 = greet + greet: Length = [Link](); cout << “The Length of the conbined strings ‘<< length << “\n"; FETEEERD Using the avaiable operations that come with the string Function, you can manipulate the contents of a string. For example, to remove characters from a string you could use: #include using namespace std; int main © { string stra (‘Here is @ Long sentence in a string.”); cout << strg << ‘\n’; [Link] (10,5); cout << strg << ‘\n’ [Link] ([Link]()+8); cout << strg << ‘\n’s erase ([Link](}+9, [Link]()-9; << strg << ‘\n’s strg cout FTE ERERD ts worth spending some time playing around with the numbers, which are the character positions in the string. Occasionally, it can be hitand miss whether you get it right, so practice makes perfect. Take a look at the screenshat to see the result ofthe code. File Edit Tabs Help C++ Maths ferere eT RAUL ee eek R ele E ule Lae een eee) (ayes built-in scope for some quite intense maths. C++ has a lot to offer someone who's implementing mathematical models into their code. It can be extremely complex or CaN NEST C++ =MC2 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. FSTTSEDD <-+smatheratical operations follow thesame patterns asthose taught inschoo in that mul ‘and dision take precedence over adltion and subtraction. You that though, For naw, create anew fileand enter: #include using namespace std; int main CQ float numbers = 1 numbers = nunbers + 10; // This adds 10 to the initial 100 cout << numbers << “\n"; nunbers = nunbers = 10; // This subtracts 10 from the new 110 cout << numbers << “\n"; FEED Muttnication and division can be applied as such: #include using namespace std; int main © { float nunbers = 100; numbers = nunbers * 10; // This multiplies 100 by 10 cout << numbers << “\n"; numbers = nunbers / 10; // And this divides 1000 by 10 cout << numbers << “\n"; r wile simple it does get the od maths muscle Supe warmed up. Note that we used a float for the numbers variable, Whi you can happy use an integer, you suddenly started iouse decimals you would ned to change toa Fost ora double, depending onthe accuracy needed, Run the and ee thereat FETIP cain, execute the simple code and see the results. While not particularly interesting, it'san Introduction to C++ maths. We used afloat here, so you can play around with the code and multiply by decimal places as well as, divide, add and subtract. ‘The interesting maths content comes when you cal ‘pon the C+ Math Library Within thisheader are dozens of mathematical functions along with Further operations Everything from computing cosine to arc tangent with two parameters, to the value of PL. You can call the header with: ifinclude ifinclude using nanespace std; int main © 1 + [Link] * I rinclude 5 Using nanespace std: ‘ 5 ine wain() 7 wo |) ESTED tart by getting the square root of 3 number: #include ifinclude using nanespace st int ain O { float nunber = 134; cout << “The square root of “ << number <<“ ‘is: “ << sqrt(number) << “\n"; } rates its oc Bon mint i ea” PETER Hece we created a new float called number and used the sqrt(number) Function to cisplay the square root of 134, the value ofthe variable, number. Build and run the code and your answer reads 11.5758, FETED 2lculating powers of numbers can be done with #include #include using namespace std; int main © float nunber = 125 cout << nunber' <<“ to the poner of 2 is “ pow(number, 2) << “\n?; cout << number << “ to the poner of 3 is “ pon(nunber, 3) << “\n"; cout << number << “ to the poner of 0.8 is “ << ponCnunber, 0.8) << “\n?; Here we created afloat called number with the value of 12 and the pow(variable, power) is where the calculation happens. OF course, you can calculate powersand square roots without using variables. For example, pow (12, 2) ‘outputs the same value as the first coutline in the code. BETSET RD the value ofPisalso storedin the cmath header library. Itcan be called up withthe M_P! Function Enter cout << M_PI; into the code and you get 3.14158; or youcan useitto calulate #include #include using namespace std; int main © a double area, radius = 1.5; MPI * radius * radius; cout << area << “\n”; area (C++ Maths > C++ on Linux User Interaction There's nothing quite as satisfying as creating a program that responds to you. This basic user interaction is one of the most taught aspects of any language and with it you're able to do much more than simply greet the user by name. HELLO, DAVE You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard input stream, to prompt user response. EE vciayanicarorecnate RRR tc ccrmoyctan cons varton system memory, soitcan be retrieved and used. Therefore, any _outputting "What is your age’ tothe screen, as indicated with the input mus first be declared asa variable, soit’sready tobe used by __chevrons. Cin uses opposite Facing chevrons, indicating an input. The the user. Star by creating a blank C++ file wth headers. inputs putinto the integer age and called up in the second cout ‘command, Build and run the code, ‘serinteraction cpp * ize entre, EE Using namespace std; File Edit Tabs Help int main() ¢ 1 . 3 a 5 7 a 20 ESTISE DD The data type of the variable must also match the type of input you want From the user. For example, Ea ri si rem ie BETEP DD youre asking a question, you need to store the See ee ere input asa string; to ask the user their name, you #include would use: using namespace std; Hincludertostren int main © using namespace std; errs int main © cout << “what is your age: “; string names a cout << “what is your names“; cout <<"\nYou are “ << age << “ years old.\n"; cin >> names ¥ cout << “\nHello, “ << name << “. I hope you’re well today?\n"; vseintracion pp * } pele ont lig nteepce 3 connanee nt sain) Soy a an os . Bn mint) foun Ewa 38 your age: “: : ee BN) SER ee ) 2 Bb ‘The principal works the same asthe previous cade. The users input, their name, is stored in a string, because it contains multiple characters, and retrieved in the second cout line. As tong asthe variable name’ doesnt change, then you. ‘an recallit wherever you lke in your code. FETTSEED Youcan chaininput requests tothe user but just make sure you have a vali variable to store the input to begin with, Let's assume you want the user to enter two whole numbers: ifinclude using namespace std; int main © ‘int num, num2; cout << “Enter two whole numbers: “: cin >> uml >> nun2; cout << “you entered “ << numl <<“ and * << num << “\n”; i HRRCSSSErane Likewise inputted data canbe manipulated once Su? you have it stored in a variable, For instance, ask the user for two numbers and do some maths on them: include using nanespace st int main © 1 float num, num; cout << “Enter two nunbers: \n"; cin >> mum >> mum2: cout << num using namespace std; int main © { string mystrs cout << “Enter @ sentence: \n"; getLine(cin, mystr); cout << “Your sentence is characters Long.\n”; : << [Link]() << Build and execute the code, then entera sentence with spaces. when you're done the code reads the numberof characters. you remove the getline line and replace It with cin >> mystr and try again, the result displays the number of characters upto the fist space. Gettin fs usally a commandthat new C++ programmers forget to include. The terminating white space is annoying when you cant figure out why your code isn’t working, n shot, it's best to use getline(cin, variable) in Future: #include using namespace std; int main © a string names cout. << “Enter your full name: \n”; getline(cin, nane); cout <« “\ntlello, * << name << “.\n"; ' serinteraction pp Sine exist) By) srthinecins nal 3B | cove

You might also like