You are on page 1of 82
NEW) EASY TOFOLLOW USER GUIDES CODING FOR chet hudalile BLACK & WHITE ee) biiNe Starting something new can be daunting. Learning a skill or RESCUE aacun tai you have no-one at hand to help. Conversely as the complexity of our consumer technology increases, the size of the requisite instruction manual decreases or in some cases it simply disappears. Nae el eR CR El Beli ee od See cccu Lee ea ETT asked aloud,’What does this button do?““Why doesn’t that work?” Miah U Nasser ee RM aU E colle De eee eRe eee Cag SORE Matsa ORCL occ (R Cel Ee op RIC ls (oe em Cun cutter arena keccts a) De el eo ae emi Mi EUR Sy Policemen RR Ue Sete ey mute amie Fl] aspects of the technology that you may have been previously Pe recut aeetecat ie Ser T Tt ECan Manan eae Each eis toa confident and experienced user. Over the page our journey begins. We would wish you luck but we're sure with our support you won't need it. ’ [ COELG Beau lelel mene Prac ; = intval(Sstudio); Pi 7 ; “ “oy i i er a Fs Ret ueerTp nina mC CL i ates > Fe ella Pe De eae s Cet a Me studio ape( st@_day", ar (oan Ses Via aol aL Nee el ea Een tval C$: 36 Equipment You will Need eos Peete Leeann cn Rt ee ict keeaan ta Other C++ IDEs to install Cerca rT e Ld ROR ere aca Sees chen Cee eta Beer ace ce a aC) Ee ee Sr FL ma on Fee CL ud ta aura ad Mn a anne eon oc yr - ) ema eadd ee Why Linux? Maar Deemed Rt) Nici Seon eens een noe Installing Linux Mint in VirtualBox feedback aN ed eu ea eaa] fete eee er ira >> it. Cle @H ssiblesstatus)) { Fy ene function eS my Pisce em oa ane Fi oe el unt" > CTT “.,.learning how to code is an on-going experience, where you learn 1) _GCETEAS Eee 21S something new every day ero cae) ber ree and VIVA nn Molen EOD) pC Meo eNotes 78 AZofLinuxCommands your code Coe | eater cone coer c eaten ——— Coding and Programming Sena nenter ia ust ie en sy Ree ees cle carlo ents learning to program is an amazing skill and one that will stand you in good stead for the Future. One of the hardest steps in learning to code is the First: Pee cue ACen aed you go to Find the tools you need and what do all those SN a ua AU Sct ty eta aera ers nee ed First tentative steps into the world of coding. Choosing a Programming Language It would be impossible to properly explain every programming language in a single book of this size. New languages and ways in which to ‘talk’ to a computer or device and set it instructions are being invented almost daily; and with the onset of quantum computing, even more complex methods are being born. Here is a list of the more common languages along with their key features. Weirror_ob.select = 0 » bpy.context.select a) objects[one.nam ee la SES cae ‘SQL stands for Structured Query Language. SQL isa standard language for accessing and manipulating databases. Although SOL is an ANSI Corea re ere tas sree ee ees See este on ee ete eg commands such as Select, Update and Delete ina similar manner. Pea JavaScript often shortened to Js) isa lightweight, interpreted, object-oriented language with First class Functions. JavaScript runs on the client side of the web, that can be used to desian or program how the web pages behave on the occurrence of an event. JavaScripts Pe een esate nurseries Poe eens PN Java isthe Foundation for virtually every type of networked application and isthe global standard for developing enterprise software, web-based content, games and mobile apps. The two main components of the Java platform are the Java Application Programming interface (AP!) and the Java Virtual Machine (JVM) that translates Java code into machine language. fee eee eek eed bud a variety of secure and robust applications that run on the .NET Framework. You can use Cif to create Windows client applications, XML Web ea eee ee eee ney curly-brace syntax of CH will be instantly recognisable to anyone Familiar with C, oor! can Pythons a widely used high level programming language used eo es eee Tena Rossum and First released in 1991. An interpreted language, Python has a design Reyes er a eon caarry ue ne Rad Pees cm Cee et ene ear) language. t has imperative, object-oriented and generic programming Features. twas designed witha bias toward system programming and embedded, resource-constrained and large systems, with performance, efficiency and flexibility of use asits design highlights. eee oer ea eee Lea eet eee eee oan eet es art cee Ruby has drawn devoted coders worldwide. Ruby is seen asa flexible language; Pee ee ee eee eee eae ety Bory “PERL Dee tera ee tee et range of tasks including system administration, web development, network programming, GUI development and more. Its major Features are that it's penetrate er Es er top in ey powerful built-in support For text processing and has one of the mast impressive Poe emt Swift is a powerful and intuitive programming language for macOS, 105, watchOS and tvOS. Writing Swift code s interactive and fun; Sree se etre eae saeco developers love, Swift code is safe by design, yet also produces software that runs lightning fas. A coding tutorial app, Swift Playgrounds, is available on iPad. Coding and Programming Learning to Code — Study Tips Programming is one of the most valuable skills you can pick up these days, PEMCN limetecm aessccenehich eis tcacdcca lig icine: aac) fap -rleE oe Ree a coco WL UB COL Mla ok se1s eM Ae LLan ke o arelANa oh to start and it’s easy to get sucked down paths that could waste a whole lot of your time and money. IF you're just getting started on your coding journey, here are some tips to set you off in the right direction. CHOOSE YOUR LANGUAGE LEARN WHAT BEING A CODER MEANS. It may sound obvious but Take sore time to look at the things coding languages are used for 50 if you choosing the are interested in web desian, look at how JavaScript is being used on the sites fight coding or you use every dayriFyou arein to mobile apps, lock into Java or Swift and see programming language te hhow they make apps wark.IEcan also be useful and encouraging ta check ou Start leaming is important hat qualified coders can expect to get paid by looking at local job stes. We iF youwantthe creative ‘are not saying that f you learn to code Python you are ately going to process to be successful. F be offered £70,000 year job but it can help spur youcn to study harder. you need learn to code fora spedficreasor Finding ajob for example, then you obviously need to learn the language that’s relevant. IF {you simply want to learn coding then picking ’ language like Python, that is both powerful and relatively easy to lear, can make success more likely, PUT THEORY INTO PRACTICE IF you are completely new to coding, learning any programming -ompletely bogged sand explanations isoften better to lear through practice, orto a task you want to perform with cade, and then work ards to lear howto complete that tack. By learning small chunks and repeating what you have already learned at differing — led Spaced Repetition. Learning to Code ~ Study Tips CE SET UP YOUR ENVIRONMENT Saya) Take some time to look at the things coding languages are used for, soiFyou are interested inweb design, look at how JavaScript isbeing used on the sites you use every days if you are into motile apps, lock into Java or Sift and see hhow they make apps work. Ian also be useful and encouraging to check out what qualified coders can expect to get paid by looking at localjob stes. We are not saying that iF you learn to.code Python you are immediately going to be offered a £70,000 a year job but it can help spur you on to study harder. Sometimes, though admittedly not always it's good dea to get a more rounded view of computer science before you cig down into mote specific programming language study. There ae several fee “introduction to ‘Computer Science” courses vallable online, including a great one from Harvard University (va the worw.eds org website). Anather study tool that can be usefulis to play coding games. Two ofthe best of these types of learning E games are CodeCombat and CodinGarne. Search online to find them. rae) BO-a|s vg rmuncon ines D Taner Bay read Biche ten LEARN FROM OTHER CODERS The fantasti Stack Overfiow is one of the best places to find answersto problems and to ask your own questions to other coders around the world, There are many other language- specific Forums online but whichever site you pick, don't be afraid to ask questions. You might find that others are a bit snappy if you don't follow the questioning rules of that forum but ust Figure out what you did wrong and learn to ask better ‘questions. Don't worry though, ask your questions, listen to the answers and remember to thank people fer their help, remembering to come back when you are more experienced and answer a few questions yourself if you can. DON’T SET YOURSELF DEADLINES ‘fatal possible, that is, Deadlines, although @ part of a professional programmers if, an definitely hurt your progress when in the pracess of learning to cade, This is especially true of selFimposed deadlines, and at this point they almost certainly willbe, as they can damage your progress when not reached. Tying to rush through anystage = of learning to code will not do you any good, and may make later stages harder if you de not fully understand the basics, " Eb» Coding and Programming Coding Tools and Resources Learning to code isn’t just about studying the syntax of a language and memor is} Eee ath na ea iesceneh cts led cehtis ei sats language, you won't be able to challenge and refine your skills. GITHUB to GitHub but i's nd is hugely al on Features such as bug tracking, Feature , task management and wikis Fo 2 TEXT EDITORS I you are serious about learning to code, yous Cet ar e simple text editor Finding the right one For ‘you, and For the language you are working Ce spe Pie aoe une ha Cat ees erate em pea Rene ee neem gris ue Cen eed Ce ye eee eg Tene ree etd Care seisceicay Gece re! Ee erate his HEROKU Ifyou are developinga web app, you will need to host it before people can access it. GitHub can host your cade but that doesn't ‘mean that end-users willbe able to use the working app. This, iswhere a service lke Heroku comes into its own, Heroku isa loud platform that lets you bull, deliver, monitor and scale apps, the Fastest way to go from idea to URL, bypassing all those infrastructure headaches. It makes the processes of de ving configuring, scaling, tuning, and managing apps as simple and straightforward as possible, so that you can facus on what's most Important: bullding great apps that delight and engage customers STACK OVERFLOW a Stack Overfiow ———— isa question and answer site for professional = andameteur ¥ programmers. Wes builtand tun by users as = part of the Stack Exchange network oF QBAsttes. with its users help, the sites bulding a library of detailed answersto every question about programming, Ths siteisall about getting answers; it’s nat a ciscussion Forum so there's na chit-chat. Good answers are voted up and ise to the top and the best answers show up first so that they are always easy to find, The key to getting the most from Stack Overflow i te Focus.on questions concerning actual problems you have faced. include details about what you have tried and exactly what you're trying to do. Tags make it easy to find interesting questions. ll questions are tagged with their subject areas. Each can have up to $ tags, since 8 ‘Question might be related to several subjects, INTEGRATED DEVELOPMENT ENVIRONMENT Integrated Developme nt Environments unlike text editors, offer a complete coding environment. Ths makes it easier For some programming beginners to get to grips with a newlanguage. Integrated Development Environments, also known as Code Editors, are sofware ‘applications that provides comprehensive Faces to ‘eemputer programmers For sftware development. An IDE normally consists ofa source code eeitor, bile Say Hello == to Python CRs et PCLT eur Cet c clr ay Ca fee ene Race Meer cig PE Re en Ree he eee scree Bee Rest or at Eu eMC Creer Ree eC LT Un euro Eee CS Run REL) Oe ess 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 Pte M ear euktsem tse 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 @ new Frontiey, Forging small routines that enabled the letter to scroll across the screen. It may not sound terrily exciting to@ generation that's used to ultra high-definition graphics and open world, mult player online gaming. However, farty-semething years ago it was blindingly brillant. Naturally these bedroom coders helped Form the Foundations For every piece of digital technology we use today. Some went on to become chief developers For top software companies, whereas ‘others pushed the avalable hardware to its limits and founded the bition pound gaming empire that continually amazes us, Regardless of whether you use an Android device, iOS device, PC, ‘Mac, Linux, Smart TY, games console, MP3 player, GPS device built-in toa car, se=top bax ora thousand other connected and ‘smart ‘appliances, behind them alls programming, Allthose aforementioned digital devices need instructions to tell them what todo, 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 an the situation, the platform, the device's use and how the device willinteract with its vl vriaoeny) O/B Bee # 110 owe Setcursor(p.¥) on certscnildooerocustl: eranrs oo old arreyctrL: su ldostrecust) Bement ifteurgor >= 0} Pefreshfos(cursor): centtrenitaloateceus(s oom a> [6 ctr ewes id _Aerayctr :sPaint(Draes w) ¢ Grote ‘eat Pai ne) See Size site = oocoize Sears a Sons aorocusbeen 0; B comms Getcinontta fevers nt is = theader GetserolLO; sore ferl{s'= 0; js column. cetcoune(); jar) ( [Sarat nv’ ox' Jhaader-cerisbmaden yal goes TPCT se't ew: vertgrid = {je'== colum.cetcount() - 10) >= 6) [Secs Sen 5 [S dcrcnce eter fe « slend(Scoterdisabled, scolorba FF svn Stet yy [Saar sitet « cotcoune()) ¢ Bion Tjtop eestuiner i) - sb; Sires Senne Fileesop t stzercy) break: Seeen lens tabottom = Ftep t onteznecy(a)s FE savant Regt item 0) rilae jeg Solam.cntcount (Dz jor) ¢ lat Geeraethe3s int en = eotumi3! margin: m= header Tabl}) etMargin(: ited sazeces) break; environment or users. Operating systems, such as Windows, macOS and such are usually combination oF C++, Ci, assembly and some. foim of visual based language. Games generally use C++ whilst web pages can use a plethora of available languages suchas HTML, Java, Python and soon, ‘More general-purpose programming is used to create programs, apps, software or whatever else you want to call them. They re widely used across all hardware platforms and suit virtually every conceivable application. Some operate Faster than others and some are easier to learn and use than others. Python is one such general- purpose language, Python is what's known as a High-Level Languag to the hardware and operating system using a variety of arrays, variables, objects arithmetic, subroutines, loops and countless ‘more interactions, Whilst it's not as streamlined as @ Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that it’s universally accessible and easy to learn, /#i Te: tnwoke Java, fngort java.lang.reflect.*; lass invoke { public static void main( string [] args ) ¢ try Glass ¢ = class.forname( args{0) ): Nethod'm = c-getmethodc argsi1], new Class ull 9; Object ret = _m.invoke( nuT1, System.out print inc STavoked static method args +" of class: a SS arae(ol 3 Withino args\neesults: * + ret >; } catch ( Classnacroundexception ef 7i'Classfornane() can't. find the class ) Catch C sosuchnethodencept ion €2°) 77 that method doesn't exist > Gavch'¢ TegatAccessException e2 ) ¢ 7j'we don't Rave permission to Savoke that fethod } Gatch ( mnvocationtargetexception es) { Fan exception ocurred wile invoking that frethod a SySten.out.printin( hethod threw a getrargetexceptton( "404 i BD sterovettavne inhi phn oer inthat it ‘talks’ Python was created over twenty sixyears ago and has evolved to become an ideal beginner's language for learning how to programa ‘computer. Its perfect For the hobbyist, enthusiast, student, veacher and those who simply need to create their own unique interaction between either themselves or a piece of external hardware and the computer itself Pythons free to download, install and use andis available For Linux, Windows, macOS, MS-DOS, 05/2, B05, IBM iseries machines, and ‘even RISC 05. It hasbeen voted one of the top Five programming languagesin the wortd and is continually evolving ahead of the hardware and Internet development curve, Soto answer the question: why Pythor? Simply put, it’s Free, easy to learn, exceptionally powerful, universally accepted, effective anda superb learning and educational PEE ue Totten 259 7f P9227 THEN LET Buse sox 388 BRint ar Sx-a, pus" ” 7 130 Next 4 200 IF (b¥-1) py THEN LET s=s42. BASIC was once the starter language that early B.bit home computer userslearned. Python is a more modern take on BASIC, it's easy to learn and makes For an ideal beginner's programming language. Why Python? Ce => Say Hello to Python) Equipment You Will Need Sole nna nN bas CONTI Ke hk Le ne LEE er- Meu ne Colt) don’t need an incredibly powerful computer and any software that’s required is fire 1) C) 2) WHAT WE'RE USING Thankfully, Python isa multi-platform programming language available For Windows, macOS, Linux, Raspberry Pi and more. IF you have one of those systems, then you can easily start using Python. __| COMPUTER ‘Obviously you're going to need a computer inorder to lear howto program in Python andto test your code. You can use Windows (from XP onward) on either a 32, ‘or 6-bit processor, an Apple Mac or Linuxinstalled PC. AN IDE AnIDE (Integrated Developer Environment) is used to enter and execute Python code. It enables you to inspect your program code and the values within the code, as wellas offering advanced features. There are many diferent IDEs avalable, so Find the one that works for you and gives the best results, PYTHON SOFTWARE 1macOS and Linux already come with Python preinstalled as part of the operating system, as does the Raspberry Fi. However, you need to ensure that you're running the latest version of Python. Windows users need to download and install Python, which welll cover shortly, __ TEXT EDITOR \Whista text ecitor is an ideal environment to enter code int, i'snot an absolute necessity. You can enter and execute code crectly from the IDLE but a text eter, such as Sublime Text or Notepads offers more advanced Features and colour coding when entering code, INTERNET ACCESS Python isan ever evolving environment ane’ as such new versions often introduce: new conceptsor change existing commands and code structure to make it a more efficient language. Having access to the internet will keep you up-to-date, help you ‘out when you get stuck and give access to Python's immense number of modules, TIME AND PATIENCE Despite what other books may ead you to believe, you won't become a programmer in 24chours. Learning to codein Python takes time, and patience. You may become stuck at times and other times the code wil flow tke water. Understand youTelearning > something entirely new, and you wil get there, Equipment You Will Need THE RASPBERRY PI Why use a Raspberry Pi? The Raspberry Pi isa tiny computer that’s very cheap to purchase but offers the user a fantastic learning platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras. Naa the Raspberry Pi 3s the latest version, incorporating a mare powerful CPU, more memory, Wi-Fi and Bluetooth support. E You can pick up a Pi for around €32 or as.a part of kit for £50: E depending on the kityou'e interested in, fila eN] sey The FUZE isa learning environment built on the latest mode! of the Raspberry Pi. You can purchase the workstations that come with an electronics kitanc even 3 robot arm for you to-bulld and program. You can find more information on the FUZE at www.Fuze.co.uk Wie have several great Raspberry titles valabe va www £ bdmpublications.com. Our P books cover how to buy ou 5 first Raspberry P, F setitupanduse E ijthere are some great step Ebystep project examples and E uidesto get the most from the Respberry i too. ‘The Raspberry P's main operating system isa Debian based Linux distribution that comes with everything you need in Easimple to use package. I's streamlined for the Piandis an ideal platform For hardware and software projects, Python ‘programming and even as. desktop compute ; => Say Hello to Python) Getting to Know Python ano A Ne ca lee emcee ATe CUS -1e) AN mete nL) you to fully harness the power of a computer, in a language that’s clean and easy to understand. WHAT IS PROGRAMMING? It helps to understand what a programming language is before you try to learn one, and Python is no different. Let's take a look at how Python came about and how it relates to other languages. ‘A programming language Isallist of instructions that computer follows. These instructions canbe as simple as displaying your name ‘or playing a music file, or ‘as complexas building 2 ‘whole virtual world, Python is programming language cconceivedin the late 1980s by Guido van Rossum ‘at Centrum Wiskunde & Informatica (Cw) inthe Netherlandsas a successor to the ABC language. Guido van Rossum, the father of Python. PROGRAMMING RECIPES Programs are like recipes For computers. A recipe to bake a cake could go ike this: Put 100 grams of selFraising flourin a bowl. ‘Add 100 grams of butter to the bowl ‘Add 100 mililitres of milk Bake forhalf an hour CODE ——— lst lke a recipe, a pragram consists of instructions that you Follow inorder. A program that describes a cake right run ike tis: bow = te flour = 100 Bite [| butter = 50 fee [milk = 100 bowl .append¢ [flour butter milk] m I cake.cook¢bonl) PROGRAM COMMANDS You might not understand some of the Python commends, ike bow. append and cake.cook{bow), ‘The Firsts a list, the second an object; we'll look at both in this book. The main thing to know § that it's easy to read commands in Python. Once you learn what the commands do, it's easy to Figure out how a program works. HIGH-LEVEL LANGUAGES Computer languages that a easy to read are known as “high-level” This is because they fly high above the hardware (also referred to as ), Languages that “ly close to the metal,” ke Assembly, are known as "lovilevel” Low-level languages commands read a bit lice thiscmsg db ,@xa Len equ $ - msg, PYTHON 3 VS PYTHON 2 ZEN OF PYTHON Python lets you access all the power of a computer in a languag} that humans can understand, Behind allthis isn ethos called "The Zen of Python.” Thsis collection of 20 software principles that influences the design ofthe language. Principles include “Beautiful Is better than ugly” and "Simple is better than complex." Type import this into Python and it wil display al the principles eeu ued UC ie aaa ee etre ae Lng see Dee rel WORLD OF PYTHON there are two buttons ae reaee Frequently update Sees PYTHON 2.X Jaen epee a) iets emt ont eeu eae rts ae ces nae medias eee ete a teenie Seeger a Features, These Features Gee Biyag eee ans erty rovid Morne FRRERD 222200 3s arowing popularity has meant that its now prudent ta start learning to develon Rees eee at the previous version. eae meter OE AEE ACM How to Set Up Python in Windows Windows users can easily install the latest version of Python via the main Python Denese AO esos aT eat ae ee ent eee ere platform of choice for building their code, it's still an ideal starting point for beginners. INSTALLING PYTHON 3.X Microsoft Windows doesn’t come with Python preinstalled as standard, so you're going to have to install t yourself manually. Thankfully, t's an easy process to Follow. Ee Start by opening your web brows ‘ora/dewnioads. Look For the button a ‘mentioned you may see later versions of 3), Download the latest version for Windows ad button for version 3.x, and File is downloaded, double-click the executable and the Pyehan installation wizard will launch, From here you have two choices: Install Now and Customise Installation, We recommend opting for the Customise Installation ink. Install Python 3.6.2 (32-bit) a. pythdn windows cowmurpythor ing the download link For Python 3.x in our case this is Python 3.6.2 but as Ee Choosing the Customise option allows you to specify certain parameters, and whilst you may stay with the defaults, i's goodhabit te adopt es sometimes (not wath Python, thankful) installers cen inclade unwanted additional tures. On the first screen available, ensure all boxes are ticked click the Next button. Optional Features pythor windows ue ian Tet Ee ‘The next page of options include some inte additions to Python. Ensure the Associate fl Python, Create Sho! (on ta Environment Va Precompile Standard stall For All Users options are ticked. These make using Python later much easier. Click install when ire ready to continue. J Advanced Options pythdr windows wos tea] a Ee ‘You may need to confirm the installation with the ‘Windows authentication notification. Simply click Yes and Python will begin to install. Once the installation is comple the final Python wizard page wil allow you to view the latest release notes, and Follow some online tutorials, Setup was successful J @ python windows before you close the insal vcard indo SUPE however, it's best to click on the link next to the shield detailed OsablePath Length Limi. this willow Python tobypas the Windows 20 character ination, enabing you to execute Python programs stored n deep folders arrangement, near cle esto authenate the process thenyou can Cas the instalation window © Disable path Close =— pos Windows 10 users will ow Find the installed Python a. Bomonisizo0 3x within the Start buttor Recently Added section. The a First link, Python 2.6 (32-bit) we willlaunch the command line version of Python wher clicked (more on that ina moment). To open the IDLE, type IDLE into Windows start How to Set Up Python in Windows eal Ea Clicking on the IDLE (Python 3.6 32-bit) lnk wil launch the Python Shell, where you can begin your Python programming journey. Don't worry if your version is newer, 25 long asit’s Python 3.x our code will work inside your Python 3 interface. IFyou now click he Windows Startbutton again, and this time type: OMD, youll be presente with the ‘Command Prompt link Clickit ta get to the Windows command line erviranment. To enter Pythan within the command tine, you to type: python and press Ente “The command line version of Python works in Step 8;note the three leftfacing arrows (>>>). Whilst i's perfectly Fine erwiranment, i's not tea user-friendly, so leave the cammanc line For now. Enter: Exit) to leave and close the Command Prompt window, How to Set Up Python on a Mac eer MaUA NRE CAME em en Dede ae RUM seo er ell) Vere) Nee e Aenea ae am Colt NOR eC ROMER ie) [enon lec (ot INSTALLING PYTHON Apple's operating system comes with Python installed, so you don't need to install it separately. However, Apple doesn’t update Python very often and you're probably running an older version. So it makes sense to check and update First BED pen a new Terminal window by clicking Go > Ublities, then double-click the Terminal ican, Now enter: python ==version. You shoul see Python 2.5.1" and even later iF Apple has updated the OS and Python instalation Either way, t's best to check fr the lat (Open Safari and head over to wwwwpython.org/ SME coviicais ustaswiththe Windows setup procedure on the previous pages, you can see two yellow download buttons: one For Python 3.6.2, and the other For Python 2.7.13, that version numbers may be different due to the Frequent 25 of Python. BED ick on the latest version of Python 3.x, in our case this s the dawnload button far Python 3.62 This wll automatically download the latest version of Python and depending on how you've got your Mac configured, i automatically starts the installation wizard. BED the Python installation wizard open, click on the Continue button to begin the installation. I's ‘worth taking a moment to read thraugh the Important information section, in case it references something that applies ta your version ‘oF macO, wher ick Continue again. “The next section details the Software License Aareement, and whilst not particularly interesting to mos folks, it's probably worth a read. When you're ready, click on the Continue button once again ( How to Set Up Python ona Mac ea ‘There'snething much ee lefttodo inte Python BMD station wz you canclk the Close button If you now drop backintoTeinal session and reenter the command: python3 =-version, you can see the new version is ‘ow isted-To enter the command ine version of Python, you ned toenterspython3 Toes exitO Phaly youre be presented with the amount of ue ‘space Python will take up on your system and an Inalbutton whch you nee tock tostar he actual talon cryin 3ontoyour ac Yura nod ener our patncrd toaxthenkat the metalation ces “The insalleton should take to longthe older ute ‘Mac Mini we used in this section is a little slower thanmore modern Mac machines and only tock around hy second forthe talon Successful prompt tobe dsplyed ‘Younead to search ninde For the rython OLE uP) when you've Found it, click it to launch and it should looksimlarta hat ofthe Windows OLE version shown on the prewovs page. The ony diferene being the Mac detected hardate platform W's uning on oy Pann anos Python 3.6.8 (3.6, 0:4147MIEDWKL, Dee 22 26, BEY Cape ince bute 56) Tope scoryiohtr, “credts" or “Tecan for sore tater => (Older Mac versions may have trouble with the newer versions of Python, in which case you will ‘need to revert toa previous Python 3x build: as long as you're using Python 3.x, the cade in this book will work Far you, ‘Python 3.1.2 (F312; 79360M, Nar 24 2010, 0 [6cc 4.071" (apple ine. build 3493)] on’ darwin ‘opyright", "credits" or "license()" for mo 78) ) Say Hello to Python) How to Set Up Python in Linux Python version 2.x is already installed in most Linux distributions but as we're going to be using Python 3.x, there’s a little work we need to do First to get hold of it. Thankfully, it’s not too difficult. PYTHON PENGUIN Linuxis such a versatile operating system that it's often difficult to nail down just one way of doing something. Different distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial. Fistiounesta acetainwticwesionofPibon RREREB sane dsoswiazomatalypaie SU?) iscurrently installed in your Linux system; as we SNPs) the installation of Python to the latest versions. imentoned wre going to be sing Linux Mint 78. forthssecion, whenever the system updated, To check Fst doa ster update swath macOs, dp into 9 Terminal iy presng eat tod upgrade sudo apt-get update 8& sudo apt-get upgrade david@davi-mint~ Fle Edt View Search Terminal Help Enter your password and let the system do any updates hecer python versioninatie remind RTE) oncethe octezncurrée scones you smn ‘screen. You should have the output relating to UEP may need to answer “Y’ to authorise any upgrades, verson2xof Pehoninthe splay. Oursintniscase Python enter python =-verston ace FPyévon 2x update or ever 2742. installed. n the case of Linux Mint, the version we have is Python, 3.5.2, whichis fine For our purposes. davide david-mint ~ Fle Edit View Search Terminal Help res) ( How to Set Up Python in Linux eS Howe Foun ibelseon 362 e506 REESE in tbe Pton le ever SUPE the Python website at the time of writing, you need SEP) mente Lotito ton oc Sat yearn te conan a sudo apt-get install build-essential checkinstoll sudo apt-get install libreadl ine-gplv2-dev Libncursesw5-dev libssl-dev libsqlite3-dev tk-dev Libadbm-dev Libe6-dev Libbz2-dev This could alittle while depending on the speed of your computer. ‘Once Finished, enter: python3.6 ==version to check the Installed latest version. FIRS on uoyeurLins web browserandot0 Forthe GIDL, youneed to ener the folowing the Python download page: www. python.ora/ command into the Terminal: downloads. Click on the Dowload Python 3.6.2 (or whichever version it’s on when you look) to download the seurce Python: 36.2tarxfile ‘The IDLE can then be started with the command: idle3. Note, thot IDLE runs 8 different version rom the one you installed From source @ python = "Dowionsurynonaaz sudo apt-get install idle} Download the latest source rele hnoeTempa cote coyotes) ETERS sev esonnth> ep rtsraaged shia ute entering: cd Downloads/. Then unzip the ee Pily tool to help you install mare modules and extras. content the owned Pynncarte code wr tay =avf) Ener da opk-petnstatlpython-pip Pyshon 3.6, 2:tanx Nowe tenet DHE TE inte ck fr thls pd wth vod Anstell =-urgrace pip = when complete, close the Terminal and Python 3.x wil be avalable va the Programming section in your distro's menu, E> Say Hello to Python) Installing a Text Editor (ee ena etude eee em Ue he Tease Aunt cunt Rece owt Mining et ete Uae Negr-le-lexeMerUel-) nee ne SMU CMe eso ee Mol =e (oleLel >) lke oe Lane Keols (om SUBLIME CODE Sublime Text is an excellent, cross-platform text editor that's designed for entering code. It has a slickinterFace, many Features and performs magnificently. In short, it's an ideal starting point. FEE oc scinnsmpngioveswineten ERED snc ren yoena snmctosuy ~ —_—_—S 7 - @ me - Sublime Text ‘Welcome to the Sublime Text 3 Setup Wizard ‘he tl Sie Test 9 ny ont Rerecrmere’ fat you cereal ste apctre re crwure However Ifyou want tospecya particle ELD eirsates shine cetast atic nee operating system version, then click on the. SNES background and white text; whilst this is perfectly Download found inthetop menubar ontheste. Thevallopen fnefor most users ts no alwaythe moet comfortable viewing a page with inks Fr the latest version For OSX Windows, Windows setup. Thankful, there are countless themes you can apply by tat end Linux machines clicking Preferences> Colour Scheme, We ve opted For IDLE In this screenshot Sublime Text 3 Download Installing a Text Editor ‘Sublime Text offers some excellent Features over SUED oF the standard Puthon DLE For example, enter the following: print (“Hello everyone!”) “This isan actual Python command, which wil print the words Hello everyone! on the screen, Notice how Sublime automatically recognises tis as cade and places the quotes and parentheses. BR sens kntcrvicncnevanreven Soon, asyou become more Pythorsaws, lind Snare that the standard IDLE isn’t quite up to the task (of keeping up with your code, alterations and injections of code ‘michway through along program. However, Sublime will eep you Updated and you can even utlise indents easily. We've net ging to esto heaviyinto the uP ‘code right now but an indent is part of Python programming, whee a statement ndates thatthe folowing Indented commands most be unt a partcar event has happened: after which the indents stop. Pressing Cts] willindent a line of code in Python, Sublime comes wha numberof rentald ou) plugins for Python code, allowing you to experiment wwthyourcade neaGine. Taye probable bewiderng a this point in time but you wil likely Find them useful as your Python skils increase. [AP Reference owever ae recommend yu ue the IDLE to une P il begin with. Although the Python IDLE isn’t as advanced a Sule, esa perfect base on whieh to buid your a, ‘Once you've mastered Python, and the way it works, you can move conto atext editor For the beter Features. sajheloto ces rap Say Hello to C++ eee eRe acura what you see in Front of you when you power up Niuean Comune tier nr Ieee arc Kees Cee tet ieee cut enc world For you in terms of desirable professional skills and the ability to code amazing apps and games. ee eae ee) Tau eS Se ee ce ecu aa DOI ee Me Tr saeco ee Ou hc a nT PCR e See Uk SCE ae ne mole as) EI vbdmpubiationscom | EP Say Hello to C++) Why C++? C++ is one of the most popular programming languages available today. Originally called C with Classes, the language was renamed C++ in 1983. It's an extension of the original C language and is a general purpose object-oriented (OOP) environment. C EVERYTHING Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs, device drivers and even entire operating systems. Dating back to 1979, the start of the golden era of home computing, C++, or rather Cwith Classes, was the brainchild of Danish computer scientist Bjarne Stroustrup while working on his PhD thesis. Stroustrup's plan was to further the original C language, “which was widely used since the early seventies. C++ proved to be popular among the developers of the '80s, since it vas a much easier environment to get to grips with and more importantly, it was 98% compatible with the original language. This meant that It could be used beyond the mainstream GB crcweemrintatontt stron ‘computing labs and by regular people who dict have access to the ‘mainframes and large computing data centres. C+simpactin the digital world is immense. Many ofthe programs, applications, games and even operating systems are coded using Cr+. For example a of Adobe's major applications, such as hotashap, InDesign and so on, are developed in C++. You wil Find that the browser you surf the internet with is written in Cer, as ‘well as Windows 10, Microsoft Office and the backbone to Google's search engine. Apple's macOS is written largely in C++ (with some 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 i switch (ch) a jo [ 9 case'a': case'A': 10 cout< Learning the basics of programming, through Python for example, enables you to understand the structure of a program. The commands may be different, but you can start to see how the code works. ra #INCLUDE = as ThestrucureofaC++ program ile Edit View Search Tools Documents Help is slightly different to that oF SURES RTSICASSIM: tina con antec . Somme | GaGccccroc GueEel | see ea Cee ee CCwith Classes, which added «©. The directive instructs the "| *newcode.cpp REECRENLGEISRIE: greptonara rassnt C programming language, section of the standard C++ #include Gas ee NRE eeNN: gunna rn ce input/output operations. 70 (C++ was invented by Danish Blame Stroustrup, Inventor oF C+, INT MAIN() ’ *newcode.cpp (~/D int main() initiates the File Edit View Search Tools Documents Help declaration of a Function, which i Bogoupofeedesomnors = ; Seuepcowmares fo ale «|x o0|a ee A function, regardless of where it |¢’ *neweode.cpp * sauce ce a #include int main() BRACES . *newcode.cpp (~/Documents) 4 The open brace is File Edit View Search Tools Documents Help something that you may emecnexes” = gg mlm | x BO) ag before, especially iFyou're used to Python. The ‘open braceindicates the | ¢'| #newcodecpp beginning ofthe main Kineton andcontaneal |#inelude the code that belongsto | that Function ae ae COMMENTS Lines that begin with a double slash are comments. This means they won't be executed in the cade and are ignored by the compiler. Why ate they there? Comments are designed to help you, or another programmer looking at your code, explain what's going on, There are two types oF comment: /* covers multiple line comments, // a singletine . *newcode cpp -/Documents) Fle Edt View Search Tools Oocumerts. Help Hoals~v|xooajag [e trewcodecpp % lainctude sing namespace Ant maint) 4 I) My fest cos program! Sta: !cout Getting to Know C++ Cea << The two chevrans used here are incestion operators. This means that whatever Follows the chevrons ito be inserted into the stcl:cout statement. Inthis case the words are Hello World, which are to be displayed on the screen when you compile and execute thecode, . *snewcode.cpp (-/Decuments) Fle Edi View Search Tools Documents Help poeajne~ yoo|ag Ch *newecode cpp x leinclude int main) { 1, My first Cos program! Std:icout << ("HELLO World! \n") OUTPUTS Leading on, the (‘Hello World") partis what we want to appear on. thescreen when the code is executed. You can enter whatever you like, as long asit’s inside the quotation marks, The brackets aren't needed but some compilersinsist on them. The \n part indicates @ new line is to be inserted I) My first Cet program! Std:tcout << ("HELLO World!\n")| AND} Finally yu can se the ines within funtion codeblock except Cemmonts) ene witnasemicton This mets the ene the statement andl staterentsin C+ must have one tthe endo the compiler wil fal tobull the code The very last tne haste closing bree tindcate the end ofthe man Function EP Say Hello to C++) How to Set Up C++ in Windows Tate lM EN eR lege anol cA A aN oA CCS ETT a mK are loads of IDEs and compilers available, including Visual Studio From Microsoft. However, in our opinion, the best C++ IDE to begin with is Code::Blocks. CODE::BLOCKS Code::Blocks isa free C++, C and Fortran IDE that is feature rich and easily extendible with plugins. It's easy to use, comes with a compiler and has a vibrant community behind it too. Start by visting the Code:Blocks download site, at ‘www-codeblocks.org/downloads. Fram there, click ‘on the ‘Download the binary releases’ ink to be taken to the latest downloadable version For Windows, — = = epi Whenyoue located thei cickon the Sourceforge nectikat te ol thetine anda deorioadnotiation vendo spears: cikon save Fle stat the dowiloa and soe te exectoble to your PC Locate the downloaded Codetlodsistaler and double-click toseat Follow theonsue nstructonsto begin the hstalion, Welcome to CodeBlocks Setup Seno puis trou erate of cae =e ‘There ou can ee, there are several windows BIEu ‘versions available. The one you want to download hasmngwsetipexe atthe endof the ure vetson number At the time of writing this is: cadeblocks-17.12mingw-setup.exe. The ifference thatthe mingwwsetup version includes a C++ compiler FETED Once you agree othe licencing terms, a choice of installation options becomes available. You can opt For a smaller install, missing out on some ofthe components but we recommend that you opt For the Full aption, as default. and debugger From TOMGCC (a compiler suite) @ r 7 Choate Comancrts Bg rosmersisntae oe nich ane Coltce auantsatal ST seectensectesat: Ru aptote tk, at eres ¥ 0 ete ord Deft etal = Segre yas oe (yipomerottee nner temamemean cana ether cease Cte = an os a ry spenreaed 255488 (- How to Set Up C++ in Windows ea sufficient (unless you have any special requirements af course), When you click Next, the install begins; when it'sfnished a notification pops up asking you iF you want start CodeBlocks now, soclck Yes, files. 's your choice but the default is generally ete rs beas ead Vepfoarro cer Woden St ener — Bir ot anton aoe tor bre 87. ea atta outta Smet = - emetic pai, (une shee poes end Verb Poanrs Mowe Wndou Bit Meu Next chaose an install location forthe Code:Blocks. BTS There's alot you can do in Code:Blocks, so youneed to digin and find a good Cr+ tutorial to help you ‘getthe mos: fram it. Hawever, to begin with, click on File >» New > Empty File, This createsa new, blank window For yout type in installed on your system. F'you don't have any, click on the First eetected option: GNU GCC Compiler and click the Default button to setit asthe system's C++ compiler. lick OK when you're ready to continue, “The firs time Code:Blocks loads eruns an auto detect For any C++ compilers you may a\ready have PPT DD The program starts and another message appears Informing you that Code:Blocksis currently not the default application far C++ files. You have two options, to leave ‘everything 2s itis or allow Code:locks to associate all C+ file types. Again, we would recommend you opt For the last choice, to associate CodeBlocks with every supported Filetype. PEPER 15 ne new window, enter the Fallowing: #include Int main My first C++ program Std: :cout << “Hello World!\n"; } Notice how Code:8locks autoincerts the braces and speech quates PPTSETDD ick File > Save as and save the code witha cap extension (helloworld.np, For examale Code: Blocks changes the view to colour code according to C++ standarés. To execute the cade, click on the Build and Run ican ‘along the top ofthe screen. It's a green play icon together with a yellow cog, a EP Say Hello to C++ ) How to Set Up C++ ona Mac To start C++ coding on a Mac you need to install Apple's Xcode. This is a Free, Full featured IDE that’s designed to create native Apple apps. However, it can also be Reselekee eeked ec Rei XCODE Apple's Xcode is primarily designed for users to develop apps for macOs, 10S, tvOs and watchOS applications in Swift or Objective-C, but you can use it For C++ too. BETEG EID izrtby opening the App Store on yourMac, Apple RESUS) when you're ready, cick on the Get button which ‘Menu > App Store. nthe Search box enter Xcode and then turn into ‘install App’ Enter your Apple 1D press Return, There will e many suggestions filing the App Store and Xcode begins to download and instal. t may take some time window but it’sthe first option, Xcode, that youneed toclickon, depending on the speed of your internet connection BETTIE 12ke 2 momentto browse through the app's ESTED hen the inscallationis complete click onthe Open information, including the compatibility to ensure button to launch Xcode. Click Agree to the licence you have the correct version of macOS. Xcode requires macOS. teims and enter your password to allow Xcode to make changes 10.12.6 arlaterto install and work. tothe system, When you've done that, Xeade begins to install additional components. Xcodd gi Essmsssssez How to Set Up C++ on a Mac ea FEPIED Wwith eversthing now installed, induding the PED Thenext step asks where to create ait Repository ‘additional components, Xcode launches, cisplaying forall your future code. Choose a location on your the version number along with three choices and any recent projects Mac, or anetwork location, and click the Create button. When. that you've worked on; although fora fresh instal this shows blank, you've done all that, you can start to code. The left-hand pane details the Files used in the C+ program you're coding, Click on the a main.cpp file in the list. PRTTTD stzrtby clickingon Create NewxcodeProject:this PRIA) You can see that code has automaticaly ‘opensa template window from which to choose the completed a basic Hello Word proaram for you platform you're developing code Fr. Click the macOS tab, then the The differences here are thatthe int main () function now contains Command Line Tool option and finally, Next to continue ‘multiple functions and the layout is slightly different. Thisisjust Xcode utilising the content that's available to your Mac. PEPER) ilinthe verious Fields but ensure that the FETED When youwant to run the code, click on Product > Language option at the battom is set to C+. Simply Run, You may be asked to enable Developer Mode choose it from the drop-down list. When you've filedin the fields, on the Mac; this isto authorise Xcode to perform Functions without ‘and madle sure that Cs isthe chasen language, clickon the Next needing your password every session. When the program executes, button to continue. the outputs displayed at the bottom of the Xcode window. Say Hello to C++ How to Set Up C++ in Linux LINUX++ We're going to be using a fresh installation of Linux Mint for this particular tutorial. More on Linux Mint can be Found in the next section ofthe book The st step with ensuring Une ready or our ou C++ code is check the system and software are Upto date. Opena Terminal and enter: sudo apt-get update BE sudo apt-get upgrade, Press etum andenter your password. ese commands updates the entre tem and any installed sotware File Edit View Search Terminal Help ere d for david: ff Bea Most Linux cistros come preinstalled with allthe necessary components to stat coding in C>+ However, i's always worth checking to see if everything is present, sostill within the Terminal, enter: sudo apt-get install build-essential. and ress Return. Ifyou have the right components, nathing sinstalled but iF you're missing some then theyare installed by the command. ew serch Teal ee worm bempubliationscom Amazingly, that's it Everything isall ready for you to start coding, Here'show to get your First Cr program up and running. In Linux Mint the main text editors Xed canbe launched by clicking on the Menu and typing Xed intothe search bar. Click on the Text Editor button inthe righthand pane to ‘pen Xed. InXed, orany other text editor you may be using, enter the lines of code that make up your C++ Hello World program. To remind you, its #include int main) { My first Ces program std::cout << “Hello World!\n"; | cay ties cn page b ETE When you've entered your code, click File» Save As ‘and choose a folder where you want to save your program. Name the ile as heloworld.cpp, or any cther name just as long asit has.cpp as the extension. Click Save to continue. ETA The first thing you can see isthat Xed has ‘auromatically recognised this as 2 C++ Fle since the File extension is now setto.cpp. The colour coding is present in the code andif you open up the file manager you can also see that the file'sicon has C++ stamped on it, PPT) With your code now saved, drop into the Terminal ‘again. You need to navigate to the location of the C++ file you've ust saved. Our example isin the Documents Folder, sowe can navigate tot by entering: ed. Documents. Remember, the Linux Terminal is case sensitive, so any capitals must be entered correctly, File Edit View Search Terminal Pre] rr eee | =r (_ How to Set Up C++ in Linux Ee Before you can execute the C++ file youneed to compile. In Linux it's common to use g++, an open source C++ compiler and as you're naw in the same Folder as the Cifile, goto the Terminal, enter: + heLlonorld..cpp and davidemi: Fle Edit View Search Terminal Help Documents $ g++ roar) led PEPIIE DD there willbe a brief pause as the cade is cr byat+ and providing there are no mistakes or errarsin the code you are retuned to the command prompt. The compiling of the code has created a new Fle. you enter Us into the Terminal you can see that alongside your C++ fileis aout davide File edit View Search Terminal Help re soe) Documents $ 1s forrest) Trea) PEND The cut fleisthe compiled C+ code, Torunthe code enter ./a.0ut and press Return. The words Hello Worl appears on the screen, However, aout nt very friendly Tomname it something else post-complling, you can recompile with: gt+ helloworld.cpp -0 helLoworid,Thiscreates an cutout Fle called hellowarld which can be run with: /helLoworld, Feet Wew search Terinal Hei verrbdmpubiations. com BED 52) :cto10~ ) Other C++ IDEs to Install IF you want to try a different approach to working with your C++ code, then there are plenty of options available to you. Windows is the most prolific platform for C++ IDEs Pagel as am eeu ential cisl clom DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but Find the one that works best for you. PPSE TED lipse is 2 hugely popular C++ IDE that offers the programmer a wealth of Features. thasa ‘great, clean interface, is easy to use and available For Windows, Linux and Mac. Head over to www.eclipse.org/downloads/ to download the latest version. f you're stuck, clickthe Need Help lin For more information. CodeLite isa Free and open source IDE that’s regulatty updated and available for Windows, Linux and macOs [t's lightweight, uncomplicated and extremely powerful. You cen find out more information as well as howto download and instal it at www. codelite.ora/. FD The CNAT Programming Studio (G5) is powerful 4nd intuitive IDE that suppor’ testing, debugging and code analysis. The Community Edition's Free, whereas te Proversion costs; however, the Community Edin isavailable For Windows, Mac, Linux and even the Raspberry Pi You can findit at wurwadacore.com/download, Another popular choices NetBeans. This REZ is another excellent IDE that’s packed with features anda pleasure to ute NetDeenstD€ Indudes projec based templtesfor tht ge you te ably to buld applcetone wth Gyr and staticbrares Fndost more at wercnetbeans.org/ Features/cpp/index.htmt. 46 Other C++ IDEs to Install ea RUINEGR emp Microsoft's Visual Studios a ‘mammoth C++ IDE that allows you to create applications For Windows, Android, iOS and the web. The Community version is Free to download and install butthe other versions allow a Free trial period. Go to wwwvisualstudio.com/ to see whatitcan do for you. Eee Thiscrossplatform IDEs designed to create C++ applications For desktop and mobile environments. It comes witha cade ecitor and integrated tools for testing and debugging, as well as deploying to you chosen platform. t'snot Free but there sa trial period on offer before requiring purchasing: www.ct.io/qt-features-libraries-apis-tools- FUE The Anjute Devstudioisa Linux only IDE that Features some of the more advanced Features you ‘would normally find in a paid software development studio. There's 2 GUI designer, source editor, ap wizard, interactive debugger and ‘uch more, Goto www.anjuta.org/ For mare information, ea aa5 * IVE a cee This excellent IDE allows developers, cowrte C++ code for desktop and ‘web applications across al the major platforms. There's an advanced text eclto, integrated debugger and a configurable workench to help you create your code, It's available For Windows, Mac and Linux ands free to download and use: www.monodevelop.cony. PUES Sloodshed Dev C++, despite its colourful name, isan older IDE that is for Windows systems onl. However, many users praise its clean interface and uncomplicated way of coding and cornpling. Although there's net been much Lpdating For some time, it's certainly one to considerif you want. something different: wuw.bloodshed net/devepp.html, Uttimatet+isa cross-platform C++ IDE thet boats rapid development of code through the smartand aggressive Use of C++. For the novice, its a beast of an IDE but behind its complexity isa beauty that would make a daveloper’s knaes go ‘wobbly, Find out more at www.ultimatepp.ora/index. html. Coding on Linux Pte ee ar cue LS Poe en Cea em Cin ary Pee raed ier Re eT Regret ea Tunas eng Pee eine Cees rican learning to master it and the operating system will een ats ee ees Ber EU U cuca ea ere so we've crafted this section to help you get to grips with how everything fits together, and how to make RCE Runes vrmwbdmpubicationscom — (CT) EP Coding on Linux Why Linux? Many developers, across all the available programming languages, use Linux as an operating system base for their coding and testing, but why? Linux has many advantages over other systems and while it also has some quirks, it makes For a great Pete acod LUM CoReole oa FREE AND OPEN Linux a Fantastic Fit for those who want to develop multi-platform code. The efficiency of the system, the availability of applications and stability are just a few good reasons. The fist thing we need to acdress is that there sno such operating Linux works considerably differently to Windows or macOS, I's system called Linux Linuxisin Fact the operating system kernel, the Free fora start, Free to download, install on as many computers as core component of an 05. when talking about Linuxwhatwe, and you ike and use Foran unlimited amount of time. t's also free to ‘others, ae referring to are one of the many distributions, or distros, upgrade and extend using equaly free programs and applications. that use the Linux kernel. No daubt you've heard of at least ane of | This Free to use element is one ofthe biggest draws far the the current popular distras: Ubuntu, Linux Mint, Fedora, openSUSE, developer. While a Windows license can cost up to €100 and a Mac Debian, the lst goes on. Each one of these distros offers something one considerably more, a developer can quickly cownload a distro a lite different For the user. While each has athe Linux kernel at and get to work coding in a matter of minutes Itscore, they provide the user with a different looking desktop. environment, different preloaded applications different waysin Alongside the free to use aspect comes a level of freedom to which to update the system and get more apps installed and asightly customise anc mould the system to your avn use. Each of the different look and feel throughout the entire system. However, at available distros available on thelinternet have a certain ‘spin, the centre lies Linux which s why we collectively say, Linux In that some offer increased security fancy locking desktop, a Linuxis.a great operating system in £2 whichtostart coding. BB eo 9 A ‘gaming spectic spin or something directed towards students. This extensibilty makes Linux a more desirable platform to learn coding (on, 2s you can quickly shape the system into a development base, including many different kinds oF IDEs For the ikes of Python, webs development, C++, Java and so on, Another remarkable advantage is that Linux comes with most of the popular coding environments built in, Both Python and Ce are preinstalled ina high percentage of avaliable Linux distros, which ‘means you can start to program almost as soon 2s you install the system and boot itup forthe First time, Generally speaking, Linux doesn't take up as many system resources 2 Windows or macOS. By system resources we mean memory, hard drive space and CPU load the Linux code has been streamlined and isree from chird-party ‘blaatwvare’ which hogs thse systems resources. A more efficient system of course means more avaliable resources forthe coding and testing environment, and the programs you eventually create, Less use of resources also means you can use Linux on older hardware that would normally struggle or even refuse to runthe latest versions of Windows or macOS, Sorather than throwing away an old computes it can be reused with a Linux stro, Why Linux? ¢ However it's not ell about C++, Python or any ofthe other more popular programming languages. Using the command line of Linux, also called the Terminal, you're able to create Shell scripts, which are programs that are designed to un From the command line and are ‘made up of scripting languages. They are used mainly to automate tasks or offer the user some form of input and output For a certain ‘operation. They are surprisingly powerful and we look at how to create them within this section, Finally, although there are many more advantages to lst there are thousands and thousands of free programs and apps avalable that cover near every aspect of computing. Known as packages, there are (at the thme of writing) over 8,709 specific programming applications just For Linux Mint alone Linux therefore isa great resource and environment for programming in. Is perfectly sulted For developers and is Continually improving and evolving. If you're serious about getting into coding, then give Linux atry and see howit works For you. ‘There are thousands of free packages available for programmers under Linux. Each distro offers something unique to the user butall have Linux atthe core, vmmerbdmpubliationscom (=) ) Coding on Linux Equipment You Will Need Out of all the many different distros available, Linux Mint is considered one of the best for both the beginner and more advanced user alike. It’s an excellent coding Pel reac tle (o0 ol eee ae elle heeds at Ee Reta) Pe eae aL FROM FREEDOM CAME ELEGANCE With Mint’s versatility, you have several choices available to install Mint. Take your time and see which method works best For you. SYSTEM REQUIREMENTS, “The minimum system requirements for Linux Mint 18 areas Follows: Obviously the better the system you have, the better the experience willbe, and quicker too. — cpu 700MH2. RAM 512MB Hard riveSpace 9B (20GB recommended) ‘Monitor 1024 x 768 resolution USB INSTALLATION You caninstall Linux Mint onto your computer via USB or DVD. Wellllook into each lite later on but if you're already Familiar with the process or you're thinking of USB and just gathering the harcware you need, then you're going toned 3 minimum 4GB USB flash drive to contain the Linux Mint ISO. PYM ea Waele] DVD installation of Linux Mint simply requires a blank DVD-R isc. OF course, you also need a DVD Writer drive before you ‘ean transfer or bumn the ISO image to the disc. VIRTUAL ENVIRONMENT Installation toa virtual envionment i¢ a Favourite method of testing and using Linux distros, Linux Mint works exceedingly vwellwhen used in a virtual environment. More on that later, “There are many cfferent virtual environment apps available; however for this book we are using VirtualBox from Oracle. You can get the latest version from wwwvirtualbox.org ( Equipment You will Need ea sh ameey all) E Ie. goes without saying realy, that an internet connection is vital For making sure that Linux Mint isup to date with the: latest updates and patches, as well asthe installation of Further software. Although you dontt need an internet Connection to use Linux Mint, you're sure to miss out ona: ‘world of free software available For ths distro. MAC HARDWARE although Linux Mint can be installed onto a Mac, there's a school of thought that recommends Mac owners use a viral environment, such as VircualBox or Parallels; and why not, macOS is already a splendid operating system. If you're ‘wanting to breathe new ife into an older Mac, make sure It's ‘an Intel CPL maciel and not the PowerPC models. “Fy Coding on Linux Transfer Mint to DVD or USB DVD BOOTABLE MEDIA We're using a Windows 10 PC here to transfer the ISO toa DVD. IFyou're using a version of Windows from 7 onward the process is extremely easy. Beep '° 1 0 image of Mint you've already downloaded. You can usually ind thisin the Downloads Folder of Windows 7, 8.1 and 10 computers; unless you specified a different location when saving it to use the builtin image burning Function, pyre Py a) to ch Eero E ny oa) DD son TD) wwnbémpublctionseom discs read, Windows will display 2 pop-up message asking you vt to do with the newiy inserted disc ignore this, as you're going Ee Right-click the Mint SO and frarn the menu select ‘um Disc image. Depending on the speed oF the PC, itrmay take @Few seconds before ansthing happens. Don't worry too ‘rwch, unless it takes more chan a minute in which case it might be worth restarting your PC and trying again, With luck. the Windows Disc Image Burner shauld launch, Ee Rightclick the Mint SO and from the menu select Burn Disc image, Depending on the speed of the PC, tray take a Few seconds before ansthing happens. Don't worry too ‘ch, unless i takes more than a minute in which case it might be worth restarting your PC and trying again, with luck, the Windows Disc Image Burner shuld launch, Windows Disc Image Burner x Disc image fle imuxmint-18.1-cinnameor-64bit Jeo Disc bumes 8-ROM Drive (0) Statue Burning disc image to recordable dsc. USB BOOTABLE MEDIA (Transfer Mint to DVD or USB? eal USB media is Faster than a DVD and it's often more convenient as most modern PCs don't have an optical drive installed. The process of transferring the image is easy but you need a third-party app First and a USB flash drive of 4GB or more. Doubleclick the downloaded Rufus executable; you ‘ean click Yes to the Windows security question and "Yes to checking for updates, With Rufus launched it should have already identified your inserted US8 Flash drive; Fnot just remove and reinsert @ Pafus 2.11.995 = x Device wr | (868 USB Fla (E) [7.968] 4 | Partition scheme and target system type | MBR partition scheme for BIOS or UEFI ¥ File system FATR2 (Default) J) luster size BSTESEDD At fistolance the Rufusinterface can looka little confusing, don’t worry though is really quite simple. To begin with click on the dis and drive icon next tothe ‘Create a bootable disk using.” section and the "FreeDOS pulldown, ‘menu. This will launch a Windows Explorer window where you can locate and select the Linux Mint SO. hen youre ready clon the Starcbutton atthe SEPA) bottom of the Rufus app. This will open up nother Gialogue box asking you to dounload and se ane version oF Salinux Stina sa selection of boot oars ued alow 2 Imoder to access nd boot rom a USB lsh dive. es neces, sodickon ves tocontmue Bee Thenext step asks which image mode you want the Mint 0 to be written to the USB lash drive In, Both methods work Fr different situations but generally, the recommended 1SO Image Mode isthe more popula’, Make sure thi ‘mode is preselected and click OK to continue, Flawed by OK again tecconfirm the action ESSE The Mint 50 snow bein. Flash drive. The process shouldn't take too long, 2gain depending on the speed of the USB device and the PC. You ‘may find Rufus wil auto-open the USB drive in Windows Explorer ding the process; don't worry you can minimise or close it iF you want. When the process's complete click on the Close button. Create a bootable ask using [BOIRBBE 3 Create extended label and icon tes Bee [too Start Cancel GOING VIRTUAL Using a Virtual Machine (VM) will take resources from your computer: memory, hard drive space, processor usage and so on; make sure you have enough of each before commencing, Eu The ist task is getting hold of VirtualBox. Ifyou Ea haven't already, head over to wwrw.virtualbox.org and cick on the large ‘Download VirtualBox .1' box. This willtake computer you're using isableto host a you to the main download page, Locate the correcthost for your computer and enter the BIOS. As the computer star system, Windows or Mac the host isthe current installed operating Del, F2 or whichever key is necessary to Ente system, and click to begin the dawnload, with the correct packages downloaded, and before install anything, you need to make sure that the ¥. Te dothis, reboot the ress the ee WZ g VirtualBox VirtualBox 5.1 atthe VirtualBox download page, Aseach BIOS is laid out differently it's locate the VirtualBox Extension Pack lik. The to assess where to lookin each personal example Extension Pack supports USB devices, as wellas numerous other However, a ageneralrule of thumb, you're looking For Inte! extras that cam help make the VM environment amore accurate Virtualisation Technology or simply Virtualisation it's usually within emulation ofa rea’ comput the Advanced section of the BIOS, When you've locatedit, Enable, save the settings, ext the BIOS and reboot the compute’ V7) VirtualBox Download VirtualBox TD) wwnbémpublicationseom ( Installing VirtualBox ea Te With the computer back up and running locate BSED When installing vitwalBox your network connection the downleacied main VirtualBox application and willbe disabled for avery bref period, This due double-click to begin the installation process. Click Next to continue, to VirtualBox creating a linked, vrtual network connection so that when you're ready, ‘any VM installed willbe able to access the Internet, and your home network resources, via the computer's already established network 89 Ora VunBoe 3.10 Stop > connection. Click Yes then Install to begin the instalation, Welcome to the Oracle VM Warning: VirtualBox 5.1.10 Setup venel Network Interfaces Te Sep Yd eae Once nao 3808 pein te race vate Leer Eesoar datinmascnaioate Sereda oacin semty FEPTD The default installation location of VirtualBox PPE vournay wellbe asked by windowsto accept a should satisfy most users but iFyou have any speciat security notification; click Yes For thisand you may location requirements click on the Browse button and change the encounter a dialogue box asking you to trustthe installation from install folder. Then, makesure that allthe iconsinthe VirtualBox Oracle. Again, click yes and accept the installation ofthe VirtualBox Feature tree are selected and none of them have ated Xnext to. _application. When t's complete click nish to start VirtualBox, them. Click Next to move on. See then ou rt fab tad Oracle VM VirtualBox 5.1.10 installation is complete. (sconce redo org ay ese betes ne ge eto 0 (mtr enters 1A tat werterddive ther ets Shisurer state ne ‘Beauresreaae a9 ene lates Crogan resoradtinato, fronee PPT Thissection can be left alone to the defaults, should EFM with virualbox up and running youcannow you wish. Itsimply makes ife alittle easier when instal the VirtualBox Extension Pack, Locate the dealing with VMs; especialy when dealing with downloaded VMs, as downloaded addon and double-click. There may be a short pause you may encounter inthe Future. Again, clicking Next will mave you while VirtualBox analyses the pack but eventually you receive a conto the next stage, message to installit obviously click Install to beain the process, scroll cdown the next screen to accept the agreement and click Agree. Cleese nernewennes Cloeseasnotaton tedesn Flows oratine oscars gate te rca vers 5.230 tec erat BY) coding on Linux Testing Linux Mint's Live Environment UEFI BIOS The Unified Extensible Firmware interface (UEFI) Is used to Identify hardware and protect a PC during its boot-up process It replaces the traditional BIOS but can cause issues when installing Linux Mint. Insert your DVD or USB Flash drive into your PC anc, Ee with iF you haven't already, shutdown Windows. In this instance we're using the USB boot media but the processis virtually Environment. T identical. start the PC and when prompted press the appropriate Boot Sequence and change the First boot device From its original keysto enter the BIOS or SETUP; these could be, for example, F2, setting, usually Internal HDD or similar, to USB Stora Deloreven Fiz the USB mecia opto Fi turned to Legacy mode, there are 0 ways of booting into the Mint Live ist viathe BIOS you're already in, Locate the There are different versions of a UEFI BIOS, so Alternatively use the Boot Option Menu, With this covering them all would be impossible. what you're ‘option you can press F12 (or something similar) looking for isa section that details the Boot Sequence or B todispiay alist of boot media options; from there, yu cas Mode. Here youhave the option totum off UEFland choose Legacy the appropriate boot mecla. Either way, you can now save and exit CF disable Secure Booting, Mint does work with UEFI but itcan be a the BIOS by navigat coenable eto boot, Changes and Exit 10 the Save & Exi option and choosing Save worm bempubliationscom TESTING MINT Testing Linux Mint's Live Environment jpg With the UEFI BIOS side of things behind us, it's time to see what the Linux Mint desktop has to offer, albeit in the test, Live Environment. Linux Mint now boots up and youre taken drecty to the Mint default desktop; we have the Cinnamon mainstream version in the screenshot here. You can see three icons ‘an the desktop: Computer, Home ancl stall Linux Mint BED ‘Along the bottom of the desktop isthe Mint Panel ‘and the Mint Menu, Click the Menu and i cisplays the core applications along with a search bar and various cons ined Lp down the lefthand side, These are quick launch icons that will change to the more recently used apps as you use Mint BED te erecien he bottor Strip indicate the session Logout and Q. icons Files, clicking this wil launch Nemo, the Linux Mint Cinnamon File manager. the quick launch ions: Lock Screen, (ebvstcown Linux Mint). Just above the Lock Screer BaD Tothe far right of the Panel, you can see sever icons; these indicate the current logged in user unt (whichis Live Session User at present), active network -ctions (where you can acjustor setup your WiFi-r wired connection), volume controls, time and date, and All splays all opened apps. intern ‘windows, which when click E=ED There are alco some quick launch icons on the: Panel next tothe Mint Menu Show Desktop, which val return you to a blank desktop while minimising all open apps; Firefox web browser: the Terminal command line; and Nemo File ‘manager. You can use any oF these ina live session but anything stored won't be savedon quitting hier BED Before you instal Mint, ou need to make sure y have an active internet connection. Ifyou have 3 wired, themet connection, and it’snataleeady plugged inta the computer, do so now. IF you're using WF, click on the network con Find your router id Fey) Coding on Linux Installing Linux Mint onaPC GOING MINT \We're assuming at this point that you're still n the Live Environment and that you've set up and activated your WIFI connection, or plugged your computer into your router via a wired connection. Ee Providing you're connected tothe Internet (net then do so now) and you're inthe Live Environment, start the installation process by double) Coding on Linux ) Installing Linux Mint in VirtualBox With Oracle's VirtualBox now up and running, and continuing from the previous Telefon Mae aCe Man A YUU Lena ROU) Ren Ke LR ne you install Linux Mint. CREATING THE VM There are plenty of options to choose from when creating @ VM. For now though, you can set up a VM adequate to run Mint Cinnamon and perform well. EEE EID With VitualB0x open, cick on the New icon in the top right ofthe app. This wil open the new FEED The next section wil define the amount of system ‘memory (RAM) the VM has allocated. Remember YM Wieard, this amount willbe taken from the available memory installed in your computer so don't give the VM too much, For example, we © * have 868 of memory instaled and we're gwving 2G8 to the VM, \whhen you're ready, click Next to continue, (| = me st eevee. oy i i ‘a 4 i es PEPTSPD 0 che box nexzto Name, type Linux Mint and VirtualBoxshoule automatically choose Linux as the Type and Ubuntu (64-bit) asthe Version. IFnot then use the drop-down boxes toselect the correct settings; remember FEI pc sconsnneejousantocene ded scanner ‘Mint mainstream is based on Ubuntu. Click Next when you're ready to proceed. at oe a “The pop-up window that appears ater licking Saat Ceeate is asking you what type of virtual hard disk you want to create. Use the default VD! (VirtualBox DiskImago) in this ease, asthe others are often used to move VMs from ane VM. application tothe next. Make sure VDIis selected and click Next as « = C= FERED) the auestion of whether to opt for Dynamically or Fie size virvathard cists may come across as being somewhat confusing othe newcomer esicali a Dynamically Allocated vital hard dskis a more Flexbie storage ‘management option. Ie on’take up much space within your physical hard dseto begin wth ether. Ensure Dynamically Allocated isselected and click Next, aoe PPT DD The virtualhard cisk willbe a single Folder, up tothe ‘size you state in this section. Ensure the location of the virtual hard disk, on your computer, has enough Free space available. For example, we've used a bigger storage option on our clive, named it Linux Mint and allocated 25.50G8 oF space to the virtual harddisk Installing Linux Mint in VirtualBox ea Fee ter clicking Create the intial set up of the vm is complete; you should now be looking at the ‘newly created VM within the VirtualBox application, Before you begin though, click the Settings button and within the General section click the Advanced tab. Using the pul-own menus, choose Bidirectional’ For bath Shared Clipboard and Drag'n Drop, fer | camer [coer = Ga | aoe po —— a Dene oe PETE DD low that by clicking onthe System section then the Processor tab, Depending on your CPU allocate as many cores as you can without detrimentto yourhost syste we've opted For tive CPUs. Now clckon the Display section, slide the video Memory upto the maximum and tick Enable 30 ‘Acceleration’, Click Ok to commit the new settings. BETTER ikon the start button and use the explorer button in the ‘Select Start-up Disk window to locate the downloaded 150 of Mint; the explorer buttonis afolder witha green arrow. Click Start to boot the VM with the Linux Mint Live Environment. You can now install Linux Mint as detailed inthe previous installing Linux Mint ona PC section, a_i Sy Coding on Linux Getting Ready to Code in Linux TAKING COMMAND The command line is at the core of Linux and when you program with it, this is called scripting. These are self-contained programs designed to be run in the Terminal. Ee “The Terminals where you begin yourjourney Ee What you currently see in the Terminal is your login vith Linux, through the command tine and thus name Falowed by the name of the computer, as you ‘any scripting From. In Linux Mint, itcan be accessed by clickingon named it when you firs installed the OS onto the computer. The the menu followed by the Terminaliconinthe panel, or entering ine then ends with the current Folder name; at firs this isjust a tilde ferminal'into the sear which means your Home folder. The Flashing cursor atthe very end of the lines ‘where your text-based commands will be ente Ea The Terminal wil give you access to the Linux Mint Shel called BASH; this gives you access to inderlying operating system, wi ‘you can begin to experiment witha simple command, Print Warking powerful lnguage to learn anc use. Everything in Mint, and Linux rectory (guid), which will put to the screen the current Folder ’ a whole, including the desktop and GUI, is amedule running from you're in, Type: pwd and press Enter thecommand line, aevdodue fie & Terminal Help Fle_Est View Search Terminal Help worabempubliations com BTS Allthe commancs you enter will workin the sare manner. You enter the command, include any pparamoters to extend the use ofthe command and press Enter to execute the command line you've entered. Now type: uname =a and press Enter. This will splay information regarding Linux Mint In scripting, you can use allthe Linux commandline commands within your ovm scripts. File Edit View Search Terminal Help ( Getting Ready to Code in Linux &@ Ee ‘The list of avallable Linux commands is vast, with some simply returning the current working rectory, white others ate capable of delating the entira system in ~aninstant, Getting to know the commands part (of learning how to script By using the wrong command, you could fend up wiping your computer. Type compgen =¢ to view the available commands doudedavid mint ie E6e_View Search Terminal Hep HERE BE DRAGONS! There's an urban myth on the Internet that an employee at Disney Pixar nearly ruined the animated movie Toy Story by inadvertently entering the wrong Linux command and deleting the entire system the film was stored on. withthe system, The Terminal sa Far more powerFulenvironment than the desktop, which has several safeguards in place in case you accidentally delete all you recover deleted files. e Terminal doesn't offer that luxury. IF Terminaland then enter the commands: rm, al the files in tha Folder would be instantly deleted. They won't appearin the Rubbish Bin ether, they're gone For good. davidedavid-mint ~/mt File Edit view Search Terminal Help estes Jou were to access a folder with files within via the BED Therefore i's always a ood idea to workin the Terminal using a two pronged approach. First, use the desktop to make regular backups ofthe Folders you're working in when inthe Terminal. This way, should anything go wrong, there's ‘quick and handy backup waiting For you Ee 6, before blindly entering a ‘command you've seen on the internet. Fyou see the command: sudo dd if=/dev/random of=/dev/sda and use itina script, youll soon come to egret the action asthe command will wipe the entire hard drive anc flit with random daca, Take 3 ‘moment to Google the commend and see what it does, 7oogle Sy Coding on Linux Creating Bash Scripts —Part 1 GET SCRIPTING ‘A Bash scriptis simply a series of commands that Mint will run through to complete a certain task. They can be simple or remarkably complex, it all depends on the situation, Bea Youll be working within the Terminal and with a BEE Tobeginwith, and before youstart to write any text editor throughout the coming pages. There scripts, you need to create a folder where you can ate alternatives to the text editor, which we'l(ook ating moment puta ourscrpts into. Start with mkdir Scripts, and enterthe butfor the sake of ease, me'llbe doing our examplesin Xed. Before folder ed Sri pts/. This will be our working Folder and from here you begin, however, un through the customary update check: Sudo you can create sub-folders if youwant of each script you apt-get update && sudo apt-get upgrade Fle ES View Search Terminal Hep peers apres Ee There are several text editors we can use to create Ee Windows users willbe aware thatin order for a a Bash script: Xed, Vi, Nano, Vim GNU Emacs any batch file to work, asin be executed and followthe 0 on. Inthe end it all comes down to personal preference. Our programming withinit, it needs to have a BAT file extension. Linux Useof Xed is purely cue to making it easierto read the script in the isan extension-ess operating system but the convention isto give screenshots you see below. scripts a.sh extension, File Et View Search Terminal He wornbémpubliationscom Bap Let's start witha simple script to output something to the Terminal. Enter xed heLLoworld. sh Thiswill launch ed and create ale called hellowortd sh. In Ked, enter the following: #1/bin/bash, then one new line: echo Hello Wortat Fle ESt_ View Search Terminal Help Boo n~ youjag ‘Theft /bin/boshline els he system what Shell SUE you're going to be using, in this case Bash. The hash (8) denotes comment ine, one tht stnore by the system, the txamaion mark) meas tat the comment sbypased andl force thescrpetoexecat the tne 8 command, This so know aserasheang Fe Et View Search Toots Docume. Hale Dwaln~ xoojaa PEED) You cansave thisfle clicking Fle» Save, and exit, back to the Terminal Entering Ls, will reveal the script inthe folder. To make any script executable, and able to vith chmod +x h every scrint you create. ‘un, you need to modify its permissions. Oo this helLoworld. sh, You need to do this w fle Et View search Terminal Help ( Creating Bash Scripts—Part 1 eo Fle Eat View Search Teeminal Help BED Although it's not terribly exciting, the words ‘Hello World! should naw be disslayed in the Terminal. The echo commandis responsible for outputting the words after itinth you can make the echo command output to other sources, grag Fle ES View Search Toole Documents Poo m~ you ag echo Nello world! This is ay first seript im Linux Mi BED ‘Think of echo as the old BASIC Print command. It splays either text, numbers or any variables that are stored in the system, such asthe current system date, Try this example: echo Hello World! Today is $Cdate +A). The S(Gate +%A) scaling the system variable that stores the current day OF the w vorerbdmpubliations.com Coding on Linux Creating Bash Scripts —Part 2 VARIABLES Just as in every other programming language a Bash script can store and call certain variables from the system, either generic or user crested. Bea Let's start by creating a new script called hello.sh; HEE The output now will be Hello David. This s because xed hello. sh. init enter i] bin/bash, then, ‘ach automatically assigns variables forthe user, echo HeLLo $1. Save the file and exit Xed, Backin the Terminal which are then hele and passed to the sciot.So the variable make the script executable with: chmod 4x hello.sh, '$1 now holds David. You can change the varieble by entering ferent: ./hello.sh Mint. Flee View Search Termial_Helo FESS File Eat View search Terminal Help i : Perry Patty pee Cee) Fle Eat Vw Seach Tee Docent lp Steet) Aoainviyoniag Croat Pee Cee or BaD Asthe script hello. sh. Now, executable, run ie with 2/ EeED You can even rename variables. Modify the hell. fou probably expected a simple sh script withthe Following: firstname=$1, Hello is displayed in the Terminal, However, f you then issue the surname=$2, echo Hello $firstname $surname. Putting command with a variable, i begins to get interesting, For example, _eachstatement on a new line. Save the script and ext backinto ty «fhello.sh David the Terminal FE Yom Sn Yr Boa n~\xyoon|aa Bu hatosh % worabémpubliationscom ‘When yourun the scriot now you can use two custom variables: .7heLo.sh David Hayward. ange the two variables with your ewn name; unless Natural you're also called David Hayward. At the moment we're just printing the contents, so let's expand the two-variable use alittle File Edit View Search Terminal Help para Pater) eee) ello. coed Hello Linux Mint eee) Create anew scritcaled addi ton: sh, sing SUE the same format as the hello.sh script, but changin the variable names Here we've acted finstrumber end Secondhumberandused the echo comand to output some Shot arthmetiby lang an integer expression, echo The Sum is $(C$firstnumbersSsecondnumber)). Save the script. and rmekeit executable (chmod +x addition.sh). Fle Et View Search Toots Documents. Help poeale~ yoo ag firstnomber=s secondnonberas Jecho The sum is $C bere ber? ‘When younow un the adlionsh srt we an Suz?) enter two numbers: ./addition.sh 1 2.The reste hopefuly be 3, th he Tena spaying The sum isa. Tiyitatha fee ciferontmumbors and see what happens, See aif you can alter the sit and rename do mutation, and sbtacton st View Search Terminal Help eT eee eee ere ores ares ( Creating Bash Scripts —Part 2 ha BED Let's expand things further. Create a new script called greetings .sh. Enter the scripting as below inthe screenshot, save itand makeit executable with the chmod ‘command. You can see that there are a Few new additions to the script now Fle Edt View Search Tools Documents He Poa n~\/xonjag ecgssh echo =n ead farstnane tear We've added a nto the echo command here which wil leave the cursor on the same line as the tion, instead ofa new line. The read command stores the nput as the variables Firstname and sumame, to then read back laterin the last echo line. And the CLear command clears the screen, Fle ESt_View Search Terminal Help EEzD ‘Asa inal addition let'sinclude the date variable we used in the last section, Amend the lat line of thescristtoread: echo Hello Sfirstnane $surnane, how re you on this fine $(date 4XA)?. The output should display the current day ofthe week, calling it from a system variable Fle Et Yew Seach Tons Docent ip - Doalnw|yoejag Bh getngssn x ‘chen ead surname leche Welle Sfirstnane $surnane, how are you on this fine S{dat verbdmpubliationscon — (( 3) Coding on Linux Creating Bash Scripts —Part3 IF, THEN, ELSE With most programming structures there will come a time where you need to loop through the commands you've entered to create better Functionality, and ultimately a better program. Ee .t'slook atthe if, Then and Else statements now, ‘which when executed correctly, compare a et of Instructions and simply work out that IF something is present, THEN dosomething, LSE do something different. Create @ new scriot called greating2. sh and enter the text inthe screenshot bel into Aba ns xoajaa BED Greeting2.shis a copy of greetinash but witha slight difference. Here we've added a loop starting attheif statement. This means, iF the variable enteredis equal to DDavid the next line, THEN, isthe reaction to what happens, in this case it willoutout to the screen ‘Awesome name; Followed by the variable (whichis David), Fle_E6t View Search Terminal Help wormbempubliations com BED The next line, ELSE, is what happens ifthe variat doesn't equal ‘David. In this case it simply outputs tothe screen the now Familiar Hello.’ The last lin, the Fl statement, s the command that will end the oop. If you have an If ‘command without a Fi command, th le Ede Vew Search Terminal Help this fine wednesday? BEZD cro around with the script a little, changing the name variable that triggers 2 naybe even issuing 2 response where the First name ‘and suiname variables match a spec goo ag o8

You might also like