100% found this document useful (1 vote)
171 views71 pages

Linux Tricks and Tips - 12th Ed 2022

linux
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
100% found this document useful (1 vote)
171 views71 pages

Linux Tricks and Tips - 12th Ed 2022

linux
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/ 71
NCU} ET RO eas PCLT} Friel Ever ything you need to take snp ead your Linux programming skills to the next level Ty ETc a Ce) the heart of Linux, Python & C++ We share our ENR elite CRMs iT) ET Tere TUT)TRICKS & TIPS Tech Guides Neda Readly RIC ais cA ole Mi Nim mae Re www.pclpublications.comTRICKS aL) Linux Coding 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 the new advanced user guide you will learn everything you will need to know to become a more confident, better skilled and experienced owner. i Over the page Auser that will make the ar Journey continue, absolute most of their coding and we will be with, ‘oll at every stage to advice inform and ultimately ‘spire you to 90 Further. use and ultimately Linux itself. An achievement you can earn by simply enabling us to exclusively help and teach you the abilities we have gained over our decades of experience.fen cnid Ce a ce sa Les eurveaed CMSs een aes caso erect h einer Sessa ee ecu Eee geese Pee eee ered 24 Using Comments PCa ees Frees Er era ead Er MeRec eee es eres Ere tae este) cee Rene SOMgeseeaar eu) Structure of a C++ Program ecece Me iscctcd Praca Using Comments Renee Peay Sars (errr ecg Px eU aera Common Coding Mistakes, “There's more to Linux than simply being a free to use operating system. Its unique configuration allows the user to customise and personalise the OS 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 Clifeleel dela. aee Cl CoML tePython on Linux eC Lele ceca hell eater eta e anil eer a eet od Sees e Oe Lele en UE Ls) Sa Cua ce aoe Me DO Uae: eo rd oo coe TT SATE Sl ance eee koa ee tee EMP e eater it) platforms available. The Pi's Features and Functions eae eaeete nau enact) eee Seedmy Python on Linux Why Python? SEE chs ee EMME eee mente iu kcn rs tcn Eee Meso een mia iacut cece rca lentes Pret steutehcee at] Python out of all the rest? ic work, others for mobile platforms and such. So why choose PYTHON POWER Ever: ce 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 'N'to scroll across the screen. Itmay not sound terribly exciting toa generation that's used to ultra high-definition graphics and open world, multi- player online gaming. However, Fortysomething years agoit was, blindinaly briliant. Naturally these bedroom coders helped form the Foundations for ‘every piece of digital technology we use today. Some went on to, become chief developers for top software companies, whereas ‘thers pushed the available hardware to its limits and Founded the billion pound gaming empire that continually amazes us. Regardless of whether you use an Android device, iOS device, PC, Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin toa car, 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 of the device and that core canbe built using a variety of programming languages. ‘The languagesin use today differ depending on the situation, the platform, the device's use and how the device will interact with its Tee PG ano Pont Bad Gen Ase ene vivre) @ > Bases > 0@ “setcursor(. cert: somtdootrocuei oid ArrayetrsschildostFocus() ifleursor >= 0) Befreshow cursor) centtrchataboeteecue() wid aprayeert spsintlorat w) ¢ ‘rmnetePaine) jee) ¢ colum.Getcount() -)) == 0) d Color fe = blend(scolorbisabled, scotorPaper): SFrrenati a) sitll catcome» ¢ column. cetcount () = 11‘environment or users. Operating systems, such as Windows, macOS. ‘and such are usually a combination of C++, CH, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and so.on, More general-purpose programming is used to create programs, ‘apps, software or whatever else you wanttto cal them. They/re ‘widely used across al hardware platforms and suit vitually every ‘conceivable application. Some operate Faster than others and some are easierto learn and use than others. Python isone such general- purpose language. Python is what's known asa High-Level Language, in thatit ‘talks! to the hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless ‘move interactions, Whilst t's nat as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that i's universally accessible and easy to learn, ie! rnvoke: java spore java ang, eFlece.*; class tnvoke ¢ Public static void main( string [] args) { "Oss ase: fornane( rge[0) 9: hiethod'm = cigettethod® argsiii, néw class eso, * Object rév = w.invoke( nul1, nulT 95 Syaten.out.prineine Yetstivoked. static method: * + args(2] eof class: sargs(0 » exch @ ehaeaegelptentle: © « pee: HT elaSe Fothame 5 can't nd’ che class } catch ( NosuchMethodexception e2) { sate ght Bete as > ¢ Tse Son't ave peraiasion £0 faveks that inethod } Gatch C rnvocationrargetexception e4 ) { Pian exception ocurred white invoking that inechod ed i Sethod’ threw an: "+ getrargesexception( “9°33 » Javaisa powerful language that's used in web pages, set-top boxes, Tvsand even cars. / ( 2 ow (why Python: Python was created over twenty six years ago and has evolved to, become an ideal beginner's language for learning how to program 2 computer. ts perfect forthe hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves or apiece of external hardware and the computer itself. Python i free to download, install and use and is avallable for Linux, Windows, macOS, MS-D05, 05/2, 8e0S, IBM series machines, and even RISC OS. Ithas been voted one ofthe top five programming languages n the world andis continually evolving ahead of the hardware and internet development curve. So to answer the question: why python? Simply put, is Free, easy to learn, exceptionally powerful, universally accepted, effective and 2 superb learning and educational tool. BASIC was once the starter language that early ‘-bit home computer users learned. ea Python isa more modern take on BASIC, it's easy to learn ‘and makes for an ideal beginner's programming language.5 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. PSTISPDD Fist younced to ascertain which version of Python 's currently installed in your Linux system. To begin ‘ith, drop into a Terminal session from your dstro's menu or hit the CUrisalteTkeys. davidedavid-Mint:~ Fle Edit View Search Terminal Help FSTEeED Next enter python =-version into the Terminal screen, You should have the output relating to version 2.x of Python in the display. By default, most Linux distros, come with both Python 2 and 3, as there's plenty of code out there stil available for Python 2. Now enter: python3 --version. davidedavid nine: ~ bore eer | PEPIIED) |: ou: case we have both Python 2 and 3 installed, ‘as long as Python 3.xxisinstalled, then the code in ourtutorials will work. I's always worth checking to see if the distro has been updated with the latest versions, so enter: sudo apt-get update && sudo apt-get upgrade to update the system, Once the update and upgrade completes, enter SAD pythons version aganto seit Python 3x is updated or even installed; as long as you have Python 3.x you're running the most recent major version, The numbers ater the 3, indicate patches and further updates. Often they're unnecessary but can contain vital new elements,How to Set Up Python in Linux a FER owevestyouantthe ites, cting edge ERB warn re ryenon der enter version you ned to bul Python om source, Stat ventions by entering these commands into the Terminal: 5 ~ do nate oltinstalt do opt-get install build-essential checkinstall ST SETTER Ths cold tale awhile cepecng onthe sped ofyourcomuter libncursesw5-dev libssl-dev Libsqlite3-dev tk-dev Once fleshed, enter: PIERO REEVES TON to check the Hinisre se inaled bes verson Younow hae Phan 2 stale alongside older Python 3.xx and Python 2. BETTE open up your Linux web browser and go to FETEEERD Fo" the GUIIDLE, you need to enter the following the Python download page: www.python.org/ ‘downloads. Click on Downloads Followed by the button under the Python Source window. This opens.a download dialogue box, SUd0 apt-get install idle3 ‘choose a location and start the dawnload process, command into the Terminal The IDLE can then be started with the command idle3, Note that IDLE runsa different version from the one you installed from source. inthe Terminal goth Downloads flderby FE outs need AP Pp instals Packages whchisa tntering ed Domtoads/ Thenuralp the contents tooltohepyouhstalimore odulsand extras ofthe downioaced thon sous code th A £5 SL. -¥-tar-x2reoucing he Y's ith the version numbers noe echas hannah acento you've downloaded. Now enter the newly unzipped Folder with ed ee a ie ed rac, oe cae ace a Python-3.Y.¥/, pip3 install --upgrade pip When complete, close the Terminal and Python 3.x will be available via the Programming section in your distro's menu.my Python on Linux ) / Starting Python for the First Time IF you're using the new Raspberry Pi together with its latest release of the Pi OS, then l SOUR UO eteh eMule] Mire] Gare aero PAM MaKe coda Mone MEeUiANe} the core Python IDLE in favour of their own coding text editor. STARTING PYTHON For those using the Pi4 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. ERTeG RED With the Raspbian desktop loaded, click on the FR carci nnentence 22 Str, Paeoms eben el nacre After pressing Enter, the next line displays the answer: 4. Basically, Python has taken the ‘code’ and produced the Find the Python 3 IDLE Shel from within the Windows Start button relevant output. menu and via Finder ee ESTeeE RD The Shellis where you can enter code and see the into Python. Tiss kind of sandbox, where you're able to try out ‘some simple code and processes. ‘The Python Shell acts very much lke a calculator, since code is basically a series of mathematical, interactions with the system. Integers, which ae the infinite sequence of whole numbers can easly be added, subtracted, rmultipied and so on, Siar responses and output of code you've programmedSiar) While that's very interesting, i's not particularly ‘exciting, Instead, try this: print(*Hello everyone!”) Just enteritinto the IDLE as you've done in the previous steps. Tsisaite more the since you've st prodiced ida your First bit of code. The Print command is fairly. ssFemlnatin,npontthings than regure teak ss welasquote mars moder toot contet tothe sren nth Sethe ne erenone! bt >>> print("Hello everyone!) Hello everyone! >>] BETED You may have noticed the colour coding within the Python IDLE, The colours represent different ‘elements of Python code. They are: Bleck Data and Variables Green-Strings Purple—Functions ‘Orange -Commands ‘Blue User Functions Dark Red —Comments Light Red Error Messages IDLE Colour Coding ‘ren | Svngs | vaeiie wore a ee Barked | Conor tt red [Ener messsoes | _syntansevor y (Starting Python for the First Time ow FETTER) The Python IDLEis a configurable environment. IF you don't lke the way the colours are represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don't recommend that, as you won't be seeing the same as our screenshots, ETE ust like most programs available, regardless of the ‘operating system, there are numerous shortcut keys available. We don't have room for them all here but within the ‘Options > Configure IDLE and under the Keys tab, you can see a list of the current bindings. cite Gel Steamers cents =| Teenie al BETTIE BD) the Python DLE isa powerinterface andone that’s actually been written in Python using one of the available GU! toolkits. If you want to know the many ins and ‘outs ofthe Shel, we recommend you take 3 few moments to view ‘wwnw.docs.python.org/3/library/idle.html, which details many of the IDLE's Features.Your First Code ecu AT ACr ec RecN assets Meee iar) Sen Matic eure t em ed erat reels es 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. EETEGEDD "youve closed Python 3 IDLE, reopenit in FETED) ou can see that instead ofthe number 4, the Whichever operating system version you prefer. In ‘output is 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 print¢“Hetlo") Rpt AE Shel tte tal c)2 Youre! arenes print(2+2) Ere 21st2s predicted, the word Hello appearsin the Eee ou can continue as such, printing 2+2, 46442343 Shell as blue text, indicating output from a string, and so on to the Shel. An easier wayisto use a Its fairly straightforward and doesn't require too much explanation. variable, which is something we will cover in mace depth later. For Now try now, enter: print(“2+2") aeSiar What you have done here's assign the letters 8 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.0n for as ong as their numbers stay the same. Try this: printCa) print(b) The output ofthe last step displays the current SUG values of both a and b individually, as you've asked them tobe printed separately. you 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. oe oe es oe et a or tmnt tae iin BSP You can play around with different kinds of variables and the Print function. For example, you could assign variables For someone's name: name="Davia” printCname) Your First Code FETT) Nowlet’s adda surname: ssurname="Hayward” print(surname) ‘You now have two variables containing a first name anda sumame and you can print them independently IF we were to apply the same routine 3s before, using the + symbol, the name wouldn't appear correctly in the output in the Shel. Try it: print Cname+surnane) ‘You need a space between the two, defining them as two separate values and not something you mathematically play around with print(name, surname) ‘Alternatively, you can add the space yourself: print(name+” “+surname) “The use of the comma is much neater, as you can see. Congratulations, you've just taken your First stepsinto the wide ‘world of Python, InPython 3 you can separate the two variables with a space using a comma’my Python on Linux Saving and Executing Your Code AW CRWCel Leite RAR tat-M 1B) M8 la1-1 eel ee Cole ecole Ea) ee eel 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. PEPIIEDD it, open the Python IDLE Shell and when i's up, ick on Fle> New Fle, This will open a new window ‘with Untitled as its name. This isthe Python IOLE Editor and within it you can enter the code needed to create your future programs. The IDLE Editor is, for allintents and purposes, @ Siar simple text editor with Python Features, colour ‘coding and so on; much inthe same vein as Sublime. You enter ‘code 2s you would within the Shel, so taking an example From the previous tutorial, enter: print (“Hello everyone!”) ee ee ‘lick on the OK button in the Save box and select a destination where you'l save all your Python code. ‘The destination can be a deviated folder called Python or you can ust dump it wherever you like, Remember to keep a tidy drive though, tohelp you outiin the FutureEntera name for your code, ‘print hello! For example, and click on the Save button. Once the Python code is saved it's executed and the output wll be detailed in the IDLE Shell In this cas, the wards Hello everyone!. Tiss how the vst maory of your Python ode EMD ive conics tera te Eaton ners savethe code andlook atthe output nthe Shel Sometimes things will differ, depending on whether you've requested a separate Window but essential thas the process. the proces we wil Use throughout ths book unless otherwise stated. ie £6 Se) Sein Sto ror Se \F you open the file location ofthe saved Python code, you can see that itendsin a.py extension, ‘Thisis the default Python file name. Any code you create willbe \whateverpy and any code downloaded from the many internet Python resource sites willbe py. Just ensure that the code is written For Python 3. TT Saving and Executing Your Code Bisa) Let's extend the code and enter afew examples From the previous tutorial: ‘surname="Hayward” print(name, surname) print Ca+b) IFyou press 5 now you'llbe asked to save the file, again, as t's been modified from before. BBD you cick the ok button, thei wilbe Suze ‘overwritten with the new code entries, and execute, wth the outoutin the Shel es nota problem uth ist these Few lines but if you were to edit a larger file, overwriting can become an issue. Instead, use File > Save As From within the Editor to-create abackup. Now create anew file. Close the Eaitor, and open Sra anew instance (Fle > New File from the Shel), Enter the following and save itas hello py: a="Python” be"is” c="cool!” print(a, b, ¢) ‘Youwill use this code in the next tutorial Thlopy. hanalpiDoamanaiiynon crop O47)ty Python on Linux Executing Code From the Terminal COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, et’s see how you can run code that was made inthe GUI at the command line level. IR hon inno comes vith two posible waysof Now yeu'eat the command tne we cantar waysiswith Python 2 whisethe ther usesthe Python Srares command pythan3 an press Emer Ths wl puryouinto rs on Fratthough drop into the Commandine gr Terminolon command ive version ofthe Shel, wth the famlr te ight {your operating system Facing arrows as the cursor (>>) wm BEEED forrrerreatetooneroe cote looked at previously, such as BED Just a before, reusing a Raspberry Pi: Windows users wil a=2 need to click the Start button and search For CMD, then click the nas Command Line returned search " You can see that it works exactly the same. and macOS users can get a totheir command tine by clicking Go > Utities > Terminal eeExecuting Code from the Terminal tv Nowetec ent oletieconnard ine ESEE te est uming ton cater he SIEPE session and return you back to t suas Python 2 command line is quite obvious. Whilst it prompt. Enter the Folder where you saved th doesn't error out in any way, due to the differences between the previous tutorial and list the available files within; hopefully you way Pythan 3 handles the Print command over Python 2, the result should see the hellopy file. isn’t as we expected, Using Sublime for the moment, open the hellopy fie FTTD Fromwithin the same folder as the code you're PEED Since Sublime Text isnt available forthe Raspberry going to run, enter the Following into the Pi, you're going to temporarily leave the Pi for the command tine: ‘moment and use Sublime as an example that you dor't necessarily need to use the Python IDLE. With the hello py file open, alteritto include the Following: python3 hello.py Thiswill execute the code we created, which to remind yous Bs naw nputC“What is your name? “) a="Python” printC*Hello,”, name) = ce"cool!” r print(a, b, ¢) or v Beara 2tually since thisis Python 3 code, using the BETe RTO Seve the hellopy file and drop backto the syntax and layout that's unique to Python 3, It only ‘command line. Now execute the newly saved ‘works when you use the python3 command. IF you tke try thesame code with: with Python 2 by entering python3 hello.py CREEL The result willbe the original Python is cool statement, together with the added input command asking you Far your name, and displaying it in the command window.ee SCORE 1,357 ae. lala iach ack cae tae eee artamy Python on Linux Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the Rees en nate Meee enue nice eee ct ccm cl can work within the IDLE Shell or in the Editor, whichever you like. IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, maths is the driving force behind the code. STEER RD ren uo the GUI version of Python 3, mentioned you can use either the Shell or the Editor. For the time being, you're going to use the Shell ust to warm our maths muscle, which we believe isa small gland located at the back of the brain or not). PEPER the shell enter the following: 22 54356+34553245 (99867344*27344484221 ‘You can see that Python can handle some quite large numbers. ESSER You can use all the usual mathematical operations: New Fle) and create a simple variable and Sia print command: a=10 print(‘The value of A is,”, a) ‘Save the file and execute the code. BRTeED Rennina the code will return the ine: The value of A 's, 10 nto the IDLE Shell window, which is what we ‘expected. Now, add some ofthe types of comments you'd normally ‘see within code: # Set the start value of A to 10 010 # Print the current value of A print¢*The value of A is,”, a) Resave the code and execute it You can see thatthe ‘output in the IDLE Shel isstil the same as before, despite the extra lines being added, Simply put, the hash symbol (#) denotes ane of text the programmer can insert to inform them, and others, of what's going on without the user being aware. PEPTSPDD ct's2ssume thatthe variable A that we've created isthe number of tivesin a game. Everytime the player des, the value is decreased by 1. The programmer could insert a routine along the lines of: a=a-1 print(*You’ve just lost a life!”) print(*You now have”, a, “Lives left!”)Whilst we know that the variable is ves, and that the player hasjust lost one, a casual viewer or ‘someone checking the code may not know. Imagine for a moment that the code is twenty thousand lines long, instead of just our ‘seven. You can see how handy comments ae. Siar) # Set the start value of A to 10 a-10 # Print the current value of A printC*The value of A is,”, a) # Player lost a life! n0-1 # Inform player, and display current value of A cr) print(*You've just lost a life!) print(*You now have”, a, “Lives Left!”) Essentially, the new code together with comments could look ike: You can use comments in different ways. For ‘example, Block Comments are a large section of text that detalls what's going on inthe code, suchas telling the code reader what variables you're planning on using: # This is the best gane 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 ow FETED ine comments are comments that follow 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 a=a-1 # Player lost a life! printCYou’ve just lost a printC“You now have”, a, “Lives left!”) # Inform player, and display current value of A (lives) STEP 9 ‘The comment, the hash symbol, can also be used to ‘comment out sections of code you don't want to be executed in your program. For instance, if you wanted to remove the first print statement, you would use # print¢“The value of A is,”, a) F printc"the value of A is,", a) = Player lost'a life! Inform player. and display current value of A (lives) prancc“Tou've just lost a, Life!” Print(-You non have", 8, “Lives left!) | Forint currnt salve of 4 PEPPER) You also use three single quotes to comment ‘outa Block Comment or multitine section of comments. lace 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. Esa seemsmy Python on Linux Working with Variables eee ec CKm ue Cantatas se iccea Mae es Merete Meee ea he area berces uss urte cil ZINTA co R711) VARIOUS VARIABLES. ‘You'll be working with the Python 3 IDLE Shell inthis tutorial. F you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. in some programming anguages you're required touse a dollar signto denote string, which isa ‘variable made up of multiple characters, such asa name ofa person. InPython tis isnt necessary For example, inthe Shell enter: rname=”David Hayward” (or use your own name, unless you're aso called David Hayward). [ie Es Oot Don Ge ro BETTER You can check the type of variable inuse by [ssuing the type () command, placing the name of the variable inside the brackets. In our example, this would be: ‘type name). Add a new string variable: title="Descended from Vikings”. FETED Youve seen previously that variables can be concatenated using the plus symbol between the variable names. In our example we can use: print (name + *: 4 title). The middle part between the quotations allows us to adda colon and a space, as variables are connected without spaces, so we need to add them manually Youcan aso SUaPS) combine variables within another variable. For ‘example, to combine both name and title variables into a new variable we use charactersname +“: “ + title “Then output the content of the new variable as: print (character) Numbers are stored as different variables: age=44 Type Cage) Which, as we know, are integersHowever, you can’t combine both strings and integer type variablesin the same command, as you ‘woulda set of similar variables. ou need to either turn one into the ‘other or vice versa, When you do try to combine both, you get. an error message: print Crane + age) This a process known as TypeCasting. The Python BED print (character +“ is “+ str(age) + “ years old.”) ‘or you can use: print (character, “is, age, “years old.”) Notice again that in the last example, you don't need the spaces between the words in quotes as the commas treat each argument to print separately >>> print (nane + age) Traceback (most recent call Last): Pile S rine’ (name + age) Typetrror: Can't convert “int* object to str inplicitly Se rane (character #32"! + str(age) +" years eld years ole. > David haynoras Descended tron*Vikines is 41 years el. PEPER) srother example of TypeCasting is when you ask For Input From the user, such as a name. for example, center ‘age= input C“How old are you? “) All data stored from the Input command i stored as string variable. le Et shel Debug apts wndows HP eyahon 34.3 Coefoul Ook 19 0, THAT (2.34) on time Eee Smee e sare Working with Variables Cc 1» Bisa) ‘This presents abit ofa problem when you want to ‘work with a number that's been inputted by the User, as age + 10 won't work due to being a string variable and an integer. Instead, you need to enter: intCage) + 10 ‘This wil TypeCast the age string into an integer that can be worked wit. pe “cenyr igre. ior 28 are"yud Oa" The se of ToeCatng also portant when dealing with Floating point arithmetic; eemember: ‘numbers that have a decimal point in them. For example, enter: shirt=19.99 Now enter typeCshirrt) and you'l see that Python has allocated the number 3s a float, because the value contains 8 decimal point. STEP 9 Python 3-4? (Gataalt, Oct 19 2014, TBST tion Liman Eps Sopra Merester or ticese(* ts o> Sypecanart) clase fieat'> \When combining integers and Floats Python usually converts the integer to a float, but should the reverse ever be appliedit's worth remembering that Python doesn't return the exact value. When corwerting a loatto an integer, Python will always round down to the nearest integer, called truncating; in our case instead of 19.99 t becomes 19. | Ble Edt Shel Debun_Sptons windows tap fyihon 3-8-3 (aetaalk, Get 19 Bove, TBST) Hype Scopytghe™. Seresits” of "Licensed" f DB enareeiatns Ssotinecanire) iemy Python on Linux User Input We've seen some basic user interaction with the code from a few of the examples Ce MMC ere nates een Maree C camry eee ent eas USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding. For example, a game may ‘ask For a character's name, whereas a database can ask For personal det ETT fitsnotalready, open the Python 31OLE shell FETeAE DD Now that ve have the user's name stored ina andstart aNew Fin the Editor. Let's begin with couple of variables we can call them up whenever something realy simple, enter: we want: print¢*Hetlo”) print¢‘Welcone”, firstname, surname, “. I hope: firstnamesinput(“What is your first name? “) you're well today.”) print*Thanks.”) surnane=input (“And what is your surname? “) SS Taya Save and execute the code, and as you already no Cipaer ae Pun the code and you can see a slight issue, the EDD seircscis cena cen ene eer tien Srcinneisiocewommeenns iene = printC‘Welcome”, firstname, surnanet. I hope you're well today.)‘You don't always have to include quoted text within, the input command, For example, you can ask the Siar User their name, and have the inputin the line below: print(“Hello. What"s your name?) nane=inputQ userinput py - /home/pi/Documents/Python Codes, le Edt Farmat sun Options windows Hep Fine ("Hello, What's your name?) ane=input() FID stone rs sens ctr ‘stone, so do as you like in these situations. Expanding on the code, print“Halt! Who goes there?”) name=input() PPD 2 good start toa text adventure game, pechaps? [Now you can expand on it and use the raw input From the user to flesh out the game alittle: if name-—"Dovid”: print¢*Welcone, good sir. You may pass.”) else: print(*I know you not. Prepare for battle!” User Input ow ‘What you've created here is aconeition, which we will cover soon. In short, we're using the input from the user and measuring itagainsta condition. So, ifthe user enters David as their name, the guard wil allow them to pass unhindered, Else if they enter a name other than David, the guard challenges them to fight. FERED ust2s you learned previously, any input froma user is automaticaly a string, so you need to apply a ‘TypeCastin order to turn itinto something else. This creates some interesting additions to the input command. For example: # Code to calculate rate and distance printC*Input a rate and a distance”) rate = floatCinput(“Rate: “)) ‘Tofinalise the rate and distance code, we can add: distance = floatCinput(“Distance: “)) print(*Time:”, distance / rate)) Save and execute the code and enter some numbers. Using the Float(input element, we've told Python that anything enteredis a floating point number rather than a string Ssemy Python on Linux Creating Functions Nears eh user eog eur eel mata nee rl eed eMC ee Cmte eet inten tao Taen enables you to define your own functions. FUNKY FUNCTIONS ‘Afunction is a command that you enter into Python to do somethi ‘works on it and then returns the result. W'S notust data that a Function works on, They can {do all manner of useful things in Python, such as sort data, change items From one Format to anather and check the length or type of items. Basically, a Function is ashort word that's Followed by brackets. For example, lent), ist() or type(). FETTER 4 function takes data, usually variable, works on depending on what the Function is programmed to do and,eturns the end value. The data being worked on goes inside the brackets, so if you wanted to know how many letters ‘aren the word antidisestablishmentarianism, then you'd enter: ‘Ten(“antidisestablishnentarianism™) and the number 28 ‘would return, It's alittle piece of self-contained code that takes data, FTE EER You can pass variables through Functions in much, the same manner Let's assume you want the numberof letters in a person's surname, you could use the Following code (enter the text editor For this example) nanesinput (“Enter your surname: “) count=Len(name) print (“Your surname has“, count, “letters in it.") Press F5 and save the code to executelt. BEEP cron has tens offunctionsbultintot, far too many to getintoin the imited space avaiable here. However, to view thelist of builtin functions avaabe to Python 3, navigate to wor docs python ora/braryifunctions nem. These are the predefined functions, but since usershave created many more, they're not the only ones available.Ational functions canbe added to Phen SIEPE through modules. Python has a vast range of tdules valle tht can cover numerous proaramning utes “hey ad funcionandcan be ported andvhen eae Fos trample, to use avenced Mathematics functors ete import math ‘nce entered, you have access to all the Math module Functions, Creating Functions QT justimported it into Python, you can utilise the square root function, Todo so, enter: math. sqrt(16) You can see that the code is presented as module function(data) FORGING FUNCTIONS ae une aOerueEuaOMc ea ‘across some excellent examples in the future; you can also create your own with the def command, PIR cr00s0 File > New File to enter the esitor let's PC Mee aT ete ae idef Hel lo():) print Cello") Hel loc Cee ee Meenas atnctcn Oe eon STEP2 Yee s CES reg ae Pee idef Hel locname): HelloC David )) eae epee ras ron Hello in STEP 4 Yous acy Genie ns SI gist Co Ts ios ani Sen ssi tetas eet def adda, b):}my Python on Linux Conditions and Loops eon Ce Se SMe Cee EMMI nn RcUT Se CR Cle Conan tu cuneate aces united creas they could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS Keeping conditions simple to be if something is TRUE, then doing something else i STEER {2tscreate anew Python program that wil ask the usertoinputa word, then checkt to see it’s 2 fourletter word or not. Start with File > New Fil, and begin with the input variable: wordsinput(“Please enter a four-letter word: “) n't. PRTISE RD Now wecan create a new variable, then use the len function and pass the word variable through tto ‘get the total number of letters the user has just entered: word=input(“Please enter a four-letter word: “) word_length=Len(word) with makes learning to program a more enjoyable experience. Let's start then by checking Now you can use an if statement to check ifthe ‘word length variable is equal to four and print a Friendly conformation ifit applies to the rule: wordsinput(“Please enter a four-letter nord: “) word_length=Len(nord) if nord_Length == print (word, “is a four-letter word. Well done.”) “The double equal sign >ch; 7 switch (ch) 8 jo { 9 cai case’ 10 cout Save As. Now name the cade helloworld.cpp and click the Save button, sonmeg BREED The Geary editors quite powerfulwhile stil being RESSYAM The colour coding helps alot when your coding ‘easy to use, All the cade you enter shows in the Now press Enter and start a new command on line main window and is numbered to help you keep track of your code. 3. Enter the following For now, in tne 1, enter tne maine) Note: there's no space between the brackets. os 29(—fve ———EEE File ESt Search View Document Project Build Tools Hep S-B- alex [hetoworhepp #include Ne symbols found ne asin) 3BRTSSERD nthe next ine, below int maind, enter acuty bracket { ‘This can be done by pressing Shift and the key to the right of Pon an English UK keyboard layout. Fle St Seech Vow Onsen Pape S-B-eGiox (ayrtos > [ratonaacns = an Notice that Geanyhas automaticaly cesteda slight SUG jindent. This is due to the structure of C++ and it's. where the meat ofthe code is entered, Now enter: My first C++ program a @rentene || tinue eran | Bintan BT cam taret co program § |, SESE es PEPPER you haverrt done so already, i's always advisable to-create a blank folder where you can save all ‘your code. You can have one each For Python and C++ or simply a single Folder called Code, whichever you prefer. Its not a necessity, just good housekeeping. DeBes = = aCG Li ) = ++ on Linux ) Structure of a C++ Program (C++ has a very defined structure and way of doing things. Miss something out, even as small as a semicolon, and your entire program will Fail to be compiled and executed. Many a 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 can start to see how the code works. PTS nt maind inites the declaration of a under the name’main.llC++ code begins at the main Function, regardless of where it actualy ies within the code. ee eee a helloworld.cpp * ] #include . The directive instructs the pre-processor toinclude a you're used to Python. The open brace indicates the beginning of the section ofthe standard C++ code. For example: include main Function and containsall the code that belongs to that Function. includes the iosream header to support input/output operations, helloworld.cpp * helloworld.cpp * Ip include 2 3 _ int main() 4 5 /Mmy first C++ program 6 ||) 8 ‘C++, which covers a number of different statements and commands. You cantleave the stdz: part out of the code but it must be declared atthe start with: using namespace std; not both. For ‘example: #include using namespace std; helloworld.cpp include int main() 1 2 3 4 a 5 Hy first ore program 6 std::cout using namespace std; int main() Jy first c++ program cout | = 2 ig) 4 5 6 7 o (Structure of a C++ Program Cll BBB) the two chevrons used here are insertion operators. ‘This means that whatever follows the chevronsis to be inserted into the std:cout staternent, In this case they/re the words "Hello, world’ which are tobe displayed on the screen when you compile and execute the code. helloworld.cpp * IB #include 2 using namespace std; 3 4 int main() 5 6 /My first C++ program 7 cout using namespace std; int main() / My First c++ program ‘cout int main() UMy first c+ program sttseout ce “Hello, world!\n"; ) ing a couple of icons and When you click the Build icon, the pane at the bottom ofthe Geany interface displays some results. Fall is well, you wil see a successful compilation, not then Geany isues an error along withthe line the error was found on, a2 IF your codes ready, look to the menubar along the top of the Geany window. Notice that midway STEP ‘along the tine of icons there's red brickicon. This is Bull, which ‘when clicked runs through the code, checking it against the C++ standards to see if there are any errors that stop it From running, le Edit Search View Document Project Build Tools Help Sv-B-eoaleax Rie; r symbols |> [helowesld cop % “@recions |p *inclode omen (3) nt mint) Uimy tase c++ program Hot cout ce Able, mortar nnd Bvoeaen, STEP 4 ee ee cxecute i Next tothe Bul eon ther'sa paper aeroplane icon this the Rn on. You cant run code thet has been previous bull oh anerrrin lace lek the Runicn, int Project Bild Tools Help x | Se-\4\5 ex] aint) my First Cr+ program tat scout | helloworld.cpp * #include using namespace std; int main() Jy first Cr+ program cout | helloworld.cpp hatin Up rinclude BU) caing nanespace std; rants) || BE i: in remvanables ||/$ i ) 412 Bo] smy Firat cos program 7 | cout Se" hello, worl \n" 2 3 cout

You might also like