Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
350 views
163 pages
The Complete Coding Manual Vol. 31 2019
The Complete Coding Manual Vol. 31 2019
Uploaded by
Miikie HX
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
Download
Save
Save The Complete Coding Manual Vol. 31 2019 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
350 views
163 pages
The Complete Coding Manual Vol. 31 2019
The Complete Coding Manual Vol. 31 2019
Uploaded by
Miikie HX
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
Carousel Previous
Carousel Next
Download
Save
Save The Complete Coding Manual Vol. 31 2019 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save The Complete Coding Manual Vol. 31 2019 For Later
You are on page 1
/ 163
Search
Fullscreen
BDW's Definitive Guide Series Lotta MOTTE to improve MmGBooooG 1B hire Volume 31 100% INDEPENDENTDiscover more of our complete manuals on Readly today... Povo SF Thecomplete Thecomplete fe. Thecomplee Python Ubuntu Linux Mint M _,.Manual Manual © The Complete yy The Complete The complete ordPress§’ = Linux || Cloud Manual Manual near Manual Se cd ets Windows 10 Manual 3s © _ The Complete Samsun Gala: Nonua{% BDM's Definitive Guide Series Discover how to turn your ideas into code Programming is everywhere. From clicking an icon on your desktop. and opening a web browser to calculating the vast distances between the stars or flying through themiin the latest video game. It’s one of the most important digital skills you can have in the modern world and it's only going to get bigger as we move into a new generation of interconnected devices and mediums. Starting to learn to code isn't easy but we're here to help you get going. In the pages of this book you can learn how to start coding using Python, C++, Linux scripting, FUZE BASIC with the Raspberry Pi, Windows batch files and Scratch. We also cover the common pitfalls and mistakes every coder falls into and ways to avoid them in the Future; also where you can Find help and howto experiment with your code. We've put together a great collection of tutorials and step-by- step guides to help you understand how to start coding and what you need to turn your ideas into ones and zeros that will help you become a better coder. Learning how to code is an on-going experience, where you learn something new every day and every time you run your code. Come with us and let’s start coding! Wal Shtcclntiaaetmcke sss [erenpees Eeomvicaions i wanusinpticaonscomCP eels ine einer IK AMMAN) 8 Choosing a Programming Language 10 Learning to Code - Study Tips 12 Coding Tools and Resources 14 Being a Programmer 18 Why Python? 20 Equipment You will Need 22 _ Getting to Know Python 24 How to Set Up Python in Windows 26 How to Set Up Python on a Mac 28 How to Set Up Python in Linux 30 _ Installing a Text Editor 32 ) Say Hello to C++ 34 WhyC+#? BOM Definitive Guide Series | Vole 21 36 38 40 a2 44 46 Equipment You will Need Gatting to Know C++ How to Set Up C+ in Windows How to Set Up C++ on a Mac How to Set Up C++ in Linux Other C++ IDEs to install 48 ) Coding on Linux 50 82 4 56 58 60 62 64 66 68 Why Linux? Equipment You will Need Transfer Mint to DVD or USB Installing VirtualBox Testing Linux Mint’s Live Environment Installing Linux Mint on @ PC Installing Linux Mint in VirtualBox Getting Ready to Code in Linux Creating Bash Scripts- Part 1 Creating Bash Scripts- Part 270 Creating Bash Scripts-Part 3 116 Loops and Repetition 72 Creating Bash Scripts- Part 4 118 Creating a Batch File Game 74 — Creating Bash Scripts~ Part 5 76 Command Line Quick Reference ® Programming with Scratch and Python 78 BZ of Uns Commands 122 Getting Started with Scratch 424 Creating Scripts in Scratch . : . Een Reale a | 82 _ Introducing the FUZE Project 128. Using Sprites in Scratch 84 Setting Up the FUZE 130. Sensing and Broadcast 86 Getting Started with FUZE BASIC 132 Objects and Local Variables 88 Coding with FUZE BASIC - Part 1 134 Global Variables and a Dice Game 90 Coding with FUZE BASIC -Part 2 136 Classes and Objects. 92. Coding with FUZE BASIC- Part 3 Using a Breadboard ® h 140 Common Coding Mistakes 142 Beginner Python Mistakes 144. Beginner C++ Mistakes 146 Beginner Linux Scripting Mistakes 148 Code Checklist 150 Whereto Find Help with Code 94 96 Using the FUZE IO Board 98 Using a Robot Arm with FUZE BASIC 100 FUZE BASIC Examples Part 1 102 FUZE BASIC Examples Part 2 104) Codi 106 What is Batch File? 152 Test Your Code Online 108 Getting Started with Batch Files 154 Python OS Module Error Codes 110. Getting an Output 156. Python Errors 112 Playing with Variables 158 Where Next? 114 Batch File Programming 160 Glossary of Terms enn nbicationscom sonsoetnieuideseres eines GUNN>) Coding and Programming ») So you want to start coding? It’s not going to be an easy road, and there are many pitfalls along the way, but 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: which programming language to learn. Then, where do you go to Find the tools you need and what doall those terms mean? Don’t worry, we're here to help you on your way. In this section we look at what you need to take those first tentative steps into the world of coding. 8 Choosing a Programming Language 10 Learning to Code ~ Study Tips 12 Coding Tools and Resources 14 _ Being a Programmer BEE) 80s 2c sees tresB=] n\e]UT=\¢(= ea tenn ia It would be impossible to properly . Re arsy = —2 = Fal explain every programming language in eh Tol) a single book of this size. New languages at ror_mod.use x — Petes arta Wirror_mod (Hae or device and set it instructions are being a i _yY = Fal invented almost daily; and with the mod = onset of quantum computing, even more Ceol nnyo) aan See ad oot y i isa list of the more common languages Seibel pe UT) along with their key Features. Weirror_ob.select = 0 OU) Peele eee sas a) objects[one.name rine ne - ee - eee eS aoe= P Te) SSQL stands for Structured Query Language. SQLs a standard language Ope nt eee ere omer) (American National Standards Institute) standard, there are different versions of the SQL language. However, to be compliant, they all support atleast the major ‘commands such as Select, Update and Delete ina similar manner. 7 . Ne a JavaScipt (often shortened to Js) is lightweight, erpreted, objec oriented language with first lass functions. JavaScript runs on the lent side of the web, that can be used to design r CE eee aa ee ea Pee eee ee ele tee coger) se vee ~y Boros e ¥ Zz 3 Ts) _ ae Javais the Foundation for virtually every type of networked application and is the global standard for developing enterprise Paar ed a eg a CC eee en eae uae ed ava Virtual Machine (JVM) that translates Java code into machine language. feo tas peer eset eT Pere e eee ee eae Fe eaten ce ee re eee aa eee Cte eee ney curly-brace syntax of Ci will be instantly recognisable to anyone Familiar with C, ooeened CSeyeiueln ee eae obi te ee cetera Rossum and first released in 1991. An interpreted language, Python has a design philosophy that emphasises code readability and a syntax that allows programmers, active eet eee aS et aa Ds corm eee tee tet ce Uy language chasimperative, objectorented and generic programming eS oe Pea ru once cue amie ses = Ppomnoaounenvc per onemnecetrstee se ean cee Perey io Bremer ne ee a aoe Re eee ea eee a essential parts of Ruby can be removed or redefined, at will. Ex eo Prey ing parts can be ca Pee test ea ee aes es aa SO eee ee ae oe 10, watchOs and tvOS. Writina Swift code is interactive and Fun oe eee mete eats Coen een lightning ast. coding tutorial app, Swift Playgrounds; is available on iPad. Ce ee Cll”=P Coding and Programming Learning to Code — Study Tips Programming is one of the most valuable skills you can pick up these days, particularly for your career prospects; and great just to test your brain and get to create something cool too. When you're new to coding, it can be hard to know where 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 Ritekca etiam nad males cun CHOOSE YOUR LANGUAGE ee Ae Ee) LEY Itmay ound obvious but ‘eke some time to look at the things coding languages are used for; so iF you E choosing the ae interested in web design, look at how JavaScripts being used on the sites right coding or {you use every day; iFyou are into mobile apps, look into Java or Swift and see programming language to how they make apps wark. It can also be useful and encouraging to check out start learning fs important ‘what qualified coders can expect to get paidby looking atlocaljobsites. We iFyouwantthe creative are not saying that if you learn to code Python you are immediately going to = process tobe successful If ‘you need learn to code fora specific reason, Finding ajob for example, then you obviously reed to learn the language thats relevant. IF ‘you simply want to learn coding, then picking ‘language lke Python, thats both powerful } and elatively easy to learn, can make success E more kel. be offered a £70,000 a year job butt can help spur you on to study harder. Cmte Sarena eul] IFyou are completely new to coding, learning any programming language can seem lke a huge task. Getting completely bogged down in pages and pages of code examples and explanations Isnotlkely to make the learning process much Fun. n our experience itis often better to learn through practice, or to choose atask you want to perform with code, and then work backwards to learn how to complete that task. By learning small chunks and repeating what you have already learned at differing intervals called Spaced Repetition. ETD) 206s oetntive Guide Series | Volume 21SET UP YOUR ENVIRONMENT Take some time to look atthe things coding languages are used for 50 if you are interested inweb design, look at how JavaScript is being Used on the sites you use every day; if you are in tomobile apps, look into Java or Swit and see how they make apps work. Itcan also be useful and encouraging to check out what qualified coders can expect to get paid by looking at local job sites. Weare not saying that if you learn to code Python you are immediately ‘aing to be offered a £70,000 a year ob but it can help spur you onto study harder. Sb Oa: |F see intent ce =e = eae —5 cs a DON'T SET YOURSELF DEADLINES \Fatall possible, thatis, Deadlines, although a part of a professional programmers life, can definitely hurt your progress when in the process of learning to cade. This s especially true of selmposed deadtnes, and at this point they almost certainly willbe, as they can damage your roaress when not reached. Trying to rush through any stage learning to code will not do you any good, and may make later stages harder ifyou do not fully understand the basics sweroublicationscom (Learning to Code —Study Tips STUDY IN DIFFERENT WAYS Sometimes, though admittedly not always, i's good idea te get a more rounded view of computer science before you dia down into more spedic programming language study. There are several fee “introduction to ‘Computer Science” courses available online, including a great one from Harvard University (via the warw.eds.ora website), Another study toolthat can be useful sto play coding games. Two of the best of these types of learning ‘games are CodeCombat and CodinGame, Search online to fine ther, ‘ NN eRe hee) ) ‘The fantastic Stack Overflaw is one ofthe best places to find answers to problems and to ask your own questions to: caders around the world, There are many ather language- specific Forums online but whichever site you pick, don't be afraid to ask questions. You might find that others are abit snappy Ifyou don't Follow the questioning rules of that forum bbutiust gure out what you did wrong and learn to ask beter questions, Dor't worry though, ask your questions listen to the answers and remember to thank people For thei hel, remembering to come back when you are more experienced and answer afew questions yourself you can, soMsdetintveGudeseres vies QECoding Tools and Resources Learning to code isn’t just about studying the syntax of a language and memorising commands. IF you don’t have the tools and resources needed to test and express that language, you won't be able to challenge and refine your skills. GITHUB You can use GitHub to crea whether you want to experiment programming language or host Any kind of file can be uploaded to GitHub but designed particularly for code files and is huge popular. It provides access control and several tres such as bus tracking, Feature Cae tsHEROKU IF you are developing a web app, you will need to host it before people can accesst. GitHub can host your cede but that doesn’t mean that end-users willbe able to use the working app. This, is where a service like Heroku comes intoilts own, Heroku isa cdoud platform that lets you build, deliver, monitor and scale app, the Fastest way to go from idea to URL, bypassing allthose infrastructure headaches. It makes the processes of deploying, configuring scaling tuning, and managing apps as simple and straightforward as possible, so that you can Focus on what's most Important: ullding great apps that delight and engage customers. Coding Tools and Resources INTEGRATED DEVELOPMENT ENVIRONMENT Integrated Development Environments, unlike text editors offer a complete coding environment. This makes it easier For some programming beginners to get to grips with a new language. integrated Development Environments also known as Code Editors, are software applications that provides comprehensive acities to ‘computer programmers for software development ‘An IDE normally consists of a source code editor, build ‘automation tools and a debugger. Most modern IDES have inteligent code completion ‘One of our Favourite IE's is Aptana Studio 3, Aptana allows youto develop and test your entire web application using a single environment. There's support for the latest browser technology specs suchas HTML5, CSS3, JavaScript Ruby, als PHP and Python, STACK OVERFLOW iow nea eg SICK Overflow Satur isa quesion = = and answer sce For professional and amateur programmers. Wes builtand run by users as part of the Stack Exchange network of QaA sites. With = its usershelp, the site is building a library of detailed answersto every question about programming, Thissite i all about getting answers; i's nota clscussion forum so there's no chit-chat. Good answers are voted up and rise tothe top and the best answers show up irs so that they are always easy to ind, The key to getting the most From Stack Overflowis to Focus on {questions concerning actual problems you have Faced. Include details about what you have tried and exactly what youre trying to do. Tags make it easy to find interesting questions. all questions are tagged with their subject areas, Each can have up to 5 tags, since a ‘question might be related to several subject, swrrpubications.com SNIPPETS Snippet isa programming term fora small region of reusable source ode, machine code of text. Snippets are often used to clarify the meaning ofan otherwise “cluttered” function arto minimise the use of repeated code that is common to other Functions, Snippets isa powerful application for Mac and Windows that stores the most valuable pleces of cade that you can reuse in different projects many times. The main ideas to make the process of reusing as easy as possible to avoid wasting your valuable time on waiting the same code again. You can download the Snippets manager free from ee PeeDUC CeCe ae Us Cac ere ssf who creates code. What they're creating the code for can be anything From a video game to a critical element on-board the International Space Station. How do you Peer cen net Side Series | Volume 21‘Times have changed since program but the core values still remain. Being able to follow a logical pattern and see an end results one ofthe most valued skils ofa programmer. Whatever kind of programmer you want to be takes time, patlence ert MORE THAN CODE For those of you old enough to remember the 80s, the golden era of hame ‘computing, the world of computing was a very different scene to how its today. -bit computers that you could purchase asa whole, as opposed to being inkit Form and you having to solder the parts together, were the stuff ‘of dreams; and getting your hands on one was sheer bliss contained within 2 large plastic box. However, It wasn't so much the new technology that computers then offered, moreover it was the fact that For the First time ‘ever, you could control what was being viewed on the ‘television’. Instead of simply playing one ofthe thousands of games available at the time, many users decided they wanted to create their own content, their ‘own games; or simply something that could help them with their homework ‘or home Finances. The simplicity of the 8-bit home computer meant that ‘creating something from a few lines of BASIC code was achievable and so the frst generation of home-bred programmer was born, From that point on, programming expanded exponentially. It wasn't long before the bedroom coder wasa thing of the past and huge teams oF designers, coders artists and musicians were involved in making a single ‘game. This ofcourse led to the programmer becoming more than simply ‘someone who could Fashion a sprite on the screen and make it move at the press ofa key. Naturally, time has moved on and withit the technology that we use, However, the Fundamentals of programming remain the same; but what ‘exactly does ittake to be a programmer? The single most common trait of any programmer, regardless of what they're doing, isthe ability to see a logical pattern, By this we mean ‘someone who can logically Follow something from start to finish and envisage the intended outcome. While you may not feel you're such 2 person, itis possible to train your brain into this way of thinking. Yes, takes time but once you start to think in this particular way you willbe able to construct and Follow code. Second to logic is an understanding of mathematics. You don't have to be ‘at a genius evel but you do need to understand the rudiments of maths. ‘Maths's all about being able to solve @ problem and code mostly falls under the umbrella of mathematics, Being able to see the big picture is certainly beneficial for the modern programmer, Undoubtedly, as 2 programmes, you willbe part of team (of other programmers, and more than likely part of an even bigger team ‘of designers, all oF whom are creating a final product. While you may only be expected to create a small element ofthat final product, being able to ‘understand what everyone else is doing wll help you create something that’ ultimately better than simply being locked in your own coding cubicle, Finally, there's also a level of creativity needed to be a good programmer. ‘Again though, you don't need to be a creative genius, just have the Imagination to be able to see the end product and how the user will interact wit it ‘There is of course alot more Involved in being a programmer, Including learning the actual code itself, However, with time, patience and the determination to learn, anyone can become a programmer, Whether you want to be part ofa triple-A video game team or simply create an ‘2utomated routine to make your computing life easier, t's up to youhow Far to take your coding adventure!> Say Hello to Python ‘ Python is one of the most popular modern programming languages available today. Not only is it easy to learn and understand but also remarkably powerful; and with just a few lines of code you can create something spectacular. This section covers what you need to get up and running with Python, which version to install and use and how to set everything up in Windows, macOS and Linux. There's a lot you can do with Python and this is just the beginning. 18 WhyPython? 20 Equipment You will Need 22 Getting to Know Python 24 Howto Set Up Python in Windows 26 _ Howto Set Up Python on aMac 28 Howto Set Up Python in Linux 30 _ Installing a Text Editor sos tfat eset ne( index GS sweroublicationscom DM's Definitive GudeWhy Python? SEEM ins eMC ent eee schema tuts inl computer, and some still available For older 8 and 16-bit computers too. Some of Ce ecoa ele le. E- 1k ene Meee ele AOL Moen Teme eee) such. So why choose Python out of all the rest? PYTHON POWER Ever since the earl ast home computers were availabl snthusiasts, users and professionals have toiled away until the wee ‘These pioneers of programming carved their way nto a new Regardless of whether you use an Android device, 10S device, PC, Frontier, forging smal routines that enabled the letter‘ to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin across the screen It may not sound teribly exciting toa generation to acar, set-top box ora thousand other connected and ‘smart’ that's used to ultra high-definition graphics and open world, multi appliances, behind them allis programming. player online gaming, However, fortysomething years ago It was blindingly biliant Allthose aforementioned digital devices need instructions to tel, them what to do, and allow them to be interacted with, These Naturally these bedroom cadershelped formthe foundations for instructions form the programming core ofthe device and that core every piece of disital technology we use today.Some went onto _can be but using a variety of programming languages. become chief developers for top software companies, whereas others pushed the available hardware to its limits and founded the The languages in use today der depending on the situation, the billion pound gaming empire that continually amazes us. platform, the device's use and how the device will interact with ts fe ca tare foes add Gaho Gee sD 4B 8) + vrcnaceey) @| S| Bee #/>/0@ ponte ‘Sexcursor(p:y)s {Boom cert: cataootrocusiS: on 2 leseee void Arrayctrl: :childLestrocus() Seems ‘elreshrow (cursor): centiidatassteocust)? void scraycerL::Paintloreas W) { ‘ermine paint) eoderGetseroll(): je = 0; 35 < colum.catcount()z 3x4) ( Tee cw —headercetTabmiatn(}9) vertgrid'* Lje'= colum.cetcount() - 3)) >= 0) A JEmacness [erwin | || lor fc = alend(scolorainabled, scolorbaper); esac” Grace Shey Soecce Siren | Miitets 2 owtcaunel)) ¢ fe sanes Bean, tp cewteinev i) « =by eee les Tiley’ stone breaks Semitic Beer 205 t crtinacy (ids eon an Sse: 4 = columacatceunt ts 344) ( leawater Goya tnt fy Rdader Servsoiaatniyys | cami | Scaorme ce ine en = cotamn nora [Scaanacr | Gcsormer se oa Emenee: Brace en = header 10b()).cottarain(2: JEreree n> risa i460 sazeren) brea Rae Graces rite 8 soot ie ineenvironment or users. Operating systems, such as Windows, macOS and such are usually a combination of Cs, Cf, assembly and some form of visual-based language. Games generally use C++ whilst web ages 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 want to call them. They're ‘widely used across all hardware platforms and suit vitally every concelvable application. Some operate Faster than others and some are easier to lear and use than others. Python is one such general purpose language. Python is what's known as a High-Level Language, in that it talks" to the hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless. more interactions. Whilstt's not as streamlined as a Low-Level Language, which can deal directly with memory addresses, cal stacks and registers its benefit is that it’s universally accessible and easy to learn // Fie: tnvoke. java fimport java. lang.reflect.*; Vass tnvoke {0 Dublic static void main( string [] args) { "lakes = class.fornane( args{0l : hatha‘ chgetnettadt atl, how class Object tee = mfnvoke( null, nulT 9; systen-out .printinc Tvoked statig method: " + args(1] eof ctass: © SP args(0: +" with no args\nresults: "+ ret 3; catch ( Classnotroundexception ¢ ) { 7 Class-forname(.)-can't find the class Gach ( Nosuchtethodexception e2) { 7 Shas method doesnt exist } Ghreh'( Filegataccessexception 3 ) { (ive Son't have permiasion £0 snvoke that tachod } Catch tnvocattonrargetexception ef ) { Zan exception ocurred white invoking that echo Systen-out.printIn¢ ethod' threw an: " + ef. getrargetexception( ")°); D rvisrorettinone percent chants Why Python? Gai Python was created over twenty si years ago and has evolved to become an ideal beginner's language for learning how to program a computer.’ perfect forthe hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves ora piece of external hardware and the computer self Python i free to download, install and use and is available for Linux, Windows, macOS, MS-DOS, 05/2, BeOS, IBM iseries machines, and even RISC OS. has been woted one of the top five programming languages in the world ands continually evolving ahead of the hardware and internet develonment curve So to answer the question: why Python? Simply put it’ Free, easy to learn, exceptionally powerful universally accepted, effective anda superb learning and educational too BASIC was once the starter language that early ‘bit home computer users learned. eet ete ye eels ar sexre Python is amore madera take on BASIC, i's easy to learn {and makes for an ideal beginner's programming language. sowsoeniecieses einesSay Hello to Python | Equipment You Will Need You can learn Python with very little hardware or initial financial investment. You eee IN Mere WA ni Reece TEIN OL NCCU oly Lice WHAT WE'RE USING ‘Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. IF you have one of those systems, then you can easily start using Python. COMPUTER Obviously youre going to need a computer in orderto learn how to program in Python and to test your cade. You can use Windows (from XP onward) on either a 32 (0F 64-bit processor, an Apple Mac or Linuxinstalled PC. AN IDE An IDE (integrated Developer Environment) isused 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 different IDEs availabe, so find the one that works For you and gives the best results PYTHON SOFTWARE 1m8e0S and Linuxalready come with Python preinstalled as part ofthe operating system, as does the Raspberry, However, you need to ensure that you're running the atest version of Python. Windows users need to download and instal Python, whlch wel cover shortly TEXT EDITOR ‘Whilsta text editoris an ideal environment to enter codeinto,it'snatan absolute necessity, You can enter and execute cade directly from the IDLE but atext editor, suchas Sublime Text or Notepad++ offers more advanced features and colour coding when entering code. INTERNET ACCESS Python isan ever evolving environment and as such new versions often introduce new concepts or change existing commands and code structure to make ita 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 maylead you to believe, ou won't become a programmer in 24+hours. Learning to code in Python takes time, and patience. You may become stuckat times and other times the cade wil Flow like water. Understand you're learning something entirely new and you wil get there. BED 200s oetntie Gide Series | Vole 21Equipment You will Need THE RASPBERRY PI Why use a Raspberry Pi? The Raspberry Pisa tiny computer that's very cheap to purchase but offers the user a Fantastic earning platform. ts main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras. RASPBERRY PI ‘The Raspberry P 3 isthe latest version, incorporating amore powerful CPU, more memory, Wii and Bluetooth support. You can pick upa P for around £32 oras apart of kc for £50+, depending on the kityou'e interested in. ava el) seg ‘The FUZE isa learning environment bult on the latest model cf the Raspberry i You can purchase the workstations that ‘come with an electrons kit and even a rabot arm for you tobulld and program. You can ind more information onthe FUZE at wwrw.fuze.co.uk. We have several great Raspberry Pitities available via www. ‘bdmpublications.com., Gur Fi books cover how to buy your First Raspberry Pi setitupanduse it;there are some great step- by-step project examples and ‘guides to get the most From the Raspberry Pi too, PEST ‘The Raspberry P'S main operating system fsa Deblan-based Linux cstrbution that comes with everything you need in a simple to use package. I's streamlined for the Pi and is an {ideal platform for hardware and software projects, Python {programming and even asa desktop compute swerpubicationscom som sDetintveGudeseres \voimesi IE>) Say Hello to Python Getting to Know Python Python is the greatest computer programming language ever created. It enables oO RU ACN ome Reo Le RUNS (elegy |e Kel EON rol Teele aT WHAT IS PROGRAMMING? Ithelps 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. PROGRAMMING RECIPES "inn Programs are like recipes For computers. A A programming langvege recipe to bake a cake could go ike this: 3 isalist oF instructions that 3 2 computer follows, These Put 100 grams of selF raising lourin abowl instructions canbe as simple: Add 100 grams of butter to the bow as displaying yourname ‘Ad 100 mlilitres of ik. ‘or playing @ musicfile, or Bake for half an hour. ascomplexas building a whole virtual world. Python CODE eo isa programming language Paka (objeot) - orice ee oor Just Uke a recipe, a pragram consists of instructions that you fallow mibleches -y by Guido van Rossum at Centrum Wiskunde & lnformatica (Cwi) in the Netherlands as a successor to the ABC language. in order. A program that describes a cake ight run ike this: bowl .append¢[flour, butter, mitk]) parson cake. cook¢bont) PROGRAM COMMANDS You might not understand some of the Python commands, like bow. append and cake.cook(bow)) The first alist, the second an abject; wel look at both inthis book. The main thing to know is that it’s easy to read commands in Python. Once you learn whiat the commands do, i's easy to| Figure out how a program works. Guido van Rossum, the Father of Python. BED) 80s etic sees tresHIGH-LEVEL LANGUAGES Computer languages that are easy to read are knowns “high Level nis s because they ly high above the hardware (also referred to as te metal), Languages that “ly close to the metal,” like Assernb! are known as low-level". Lowslevel languages commands read a bit like thissmsg db ,@xa len equ $ = msg. PYTHON 3 VS PYTHON 2 Deere ee aes re seid WORLD OF PYTHON eee Lea eae there are two buttons available: one For Python 3.6.2 andthe othe hens. tas DCC Ra aaa ary PYTHON 2.x Jey ae leet TEE ae eee eter es erie song toed ZEN OF PYTHON ts you access all the power o 4, Behind all thisisan ethos called "The This is a collection of 20 soPeware principe that Pythe thac humans can -omputer in alanguage Zen of Pytho influences the design ofthe language. Principles include "Beautiful isbetter than ualy"and "Simple is beter than complex. Type import this into Python and it wil display al the principles, CEs LLCS aCe ui PYTHON 3.X Pupuaieerne eae Mise cae Ce aes GF nok ll oF these new Features a Cea es sey and enhanced Features, These Fest ieee rete X WINS a os Che ee DM's Definitive Guide Series | Volum>) Say Hello to Python ) How to Set Up Python in Windows TMM eee] Genelec RM wae T UTIs eo PPL oreo] (MN Cee eel ena VaNel Ke Ao) SECA U RAWLS platform of choice for building their code, it’s still an ideal starting point for beginners. INSTALLING PYTHON 3.X jows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. t's an easy process to follow. FEED start by opening yourweb browser towwnoython. ERIE choosing the Customise option allows you to ‘ra/downloads/. Look or the button detailing the specify certain parameters, and whilst you may download link for Python 3.x.(in our case this is Python 3.6.2 but as stay with the defaults, its 8 good habit to adopt as sometimes (not mentioned you may see later versions of 3). ‘with Python, thankFully) installers cen include unwanted additional Features. On the first screen available, ensure all boxes are ticked ‘and click the Next button J Optional Features Biyowow Bi ateoneenretnatay oi sts ebb munca ers oe winds = ‘Wes | can Cliche downloadbutton for version 3.x and “Thenent page of options nude some teresting gue save the file to your Downloads folder. when the Sue additions to Python. Ensure the Associate File with fleisdownloadea doublecik the executable andthe Python Python, Credte Shortcuts, Add Python to Envronment Varbls instalation wizard wllaunch Fomfereyouhavetwo choles: Precomple tandrdLray anna fr Al Uses optons are inet Now and Customise installation We recommend optngfot ted These mate usng Python ater much eager Cickinstall when the Customise Installation tink. you're ready to continue. J Install Python 3.6.2 (32-bit) ‘Advanced Options Sue nano Pyne tng or on nef B wind Baanpersemm ws soot ie ine ioRR 0.2 ned to conten the staat withthe Clekng onthe LE (Python 363250 ink wl the final Python wizard page wil allow you to view the latest release Is newer, aslo notes, and fallow some ontine tutorials uti 3s Python 3.x our code will work inside your terface Setup was successful im | © iste puth windows ae Before you close te instal wizard window ¥ you now cckonthe Windows Star baton asi, SUES however, it's best to click on the link next to the Bue! and this time type: CMD, you'll be presented with shield detaled Disable Path Length Limit. This wil allow Python Command Prompt Unk, Click tte get to the Windows command line to.bypas the Windows 260 character limitation, enabling you to _ environment, To enter Python within the command line, you need execute Python programs stored in deep folders arrangements. totype: python and press Enter Again, click Yes to authenticate the process; the! instalation win @ Disable path length limit cose a = command ine version of Python works in ue MELD ich ne same vay os the Shell you opened in Windows 10 users will now Me Step 8; note the three left-Facing arrows (>>>). Whilst it’s a perfectly fatcialecrcion fall a Sian fcendorent tstttoo attend oleate command Recently Added section. The first link, Python 3.6 G2-it) willlauneh the command a line version of Python when Prompt window, d (more on that ina moment) To ope type IDLE into Wir 80M Definitive Guide Series | Volume 3 GlSyHeloto pti How to Set Up Python on a Mac TaN EU aus enrn Meer rT ere SMC) Atel nNo A ano NeR- LU =LeN Ale Crea NCR ole ol MEU R OORT) baal ol 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 even later, fF Apple has updated the OS and Python installation, depending on how you've got your Mac configured, it automatically Either way, k's best to check forthe latest version, starts the installation wizard, (pen afr and head ver ovat of vt the Pthoninstalation ward pen cickon LEED sovnicods Jstesuiththewindonesetup all ‘ the Continue button to begin the installation, I's procedure on the previous pages, you can see twoyellow download worth taking a moment to read through the Important Infarmation buttons: one for Python 3.6.2, and the other For Python 2.7.13. section, i it references something that applies to your version Note, that version numbers may be different duetothe Frequent of macO. when ready, lick Conti releases of Python. Pr rune a SaeedThenexe section detalste Software iene SUBPE ‘Agreement, and whilst not particularly interesting tomost folks it's probably worth a read. When you're ready, cick on the Continue button once again. Final youre be presented with the amount of Suse ‘space Python will take up on your system and an ital button, whieh ou ned tock start the acta intaltion ‘oF Python 3. on to your Mac. You may need to enter your password toauthenticate the installation process There’ nating much els afta din he Pyenon sur installation wizard so you can click the Close button. iFyounes drop nackinto 2 Terminal session andreenterthe command: python’ ==verstion, you nse the new versonis ‘now listed, To enter the command tine version of Python, you need to enter: python, To ext, 's: exitQ) Younced to search in Finder forthe Python IDLE; Sue when you've Found it, click it to launch and it should looksimiato that ofthe Windows IDLE version shown on the previous page. The only difference being the Mac detected hardware platform i's cunning on, . en 360 She Python 9.68 (0.6. 0:41EDeET, Bec 22 2886, 1720/03) (C421 Capte in bul S666) (ot 39) on ornin ove ccorylahtss“eredttet slices for sore tforeation ermine werent Fete rs (eo my te cra The installation shouldn’ttake too long; the older "Mac Min we used in this section isa litte slower than more modern Mac machines and it only took around thirty seconds for the Installation Successful promptto be displayed. ‘Older Mac versions may have trouble with the newer versions of Python, in which case you wal STEP 10 need to revert to a previous Python 3. build as lang as you're using Python 3.x, the cade inthis book will work for you. Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33+18) {Gcc 4.0.1" (apple Ine. build 5493)] on’ darwin Type "copyright", “eredits" or "license()" for mo Fe information. DM's Definitive Guide Series Volume 31Say Hello to Python How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it's often difficult to nail down just one way of doing something. Different. distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 For this particular tutorial, Fesounestoaxerainubihveson sf Pton ERED Sore nuxdsvosiazonaty ate Suzau is currently installed in your Linux system; as we uae the installation of Python to the latest versions mentioned, we're going tobe using Linux Min. 18.1 forthe section, whenever the system s updated. To check fist doasjtem update drop into a Terminal by pressing Coat sed uporae wit As with m ST sudo apt-get update && sudo apt-get uporade Enter your password and let the system do any u Filet View Search Terminal Help fates oper eavidedavideine Feat Vw Search Tenia! Hep Nesey =veeton ia eer ERRMY on este andar cont SIE screen. You should have the output relating to Busia may need to answer “Y" to authorise any upgrades, version 2xoFPythoninthecienay. OursinthscaselFPython enter python version taseeFFyenon ax updates or even 27:12. installed. inthe case of Linux Mint. the version we have is Python 3.5.2, which sine for our purposes davidedavid-mint ~ File Edit View Search Terminal Help BOM Definitive Guide Series | Volume 21How to Set Up Python in Linux Howe Fvonvant tees erion362:s0e REESE wennctePenofer ener: SEP the Python website at the time of writing, you need Sue eee r0 build Python from source. Start by entering these commands into ae ae ast ey eniening i sudo make altinstalt Tis could atte white depending onthe speed of your compute Once finished enter python3.6.=-verston to check the istaled ates verson sudo apt-get install build-essentiol checkinstall sudo apt-get install libreadline-gplv2-dev LibncursesaS-dev libssl-dev libsqlite3-dev tk-dev Libgdbm-dev Libc6-dev libbz2-dev (Open up your Linux web browser and goto For the GUIIDLE you need toenter the following BUD ne thon dovnload page wwnesthonora/ SED esate termina downloads. Click on the Download Python 3.62 (or whichever vetsionit's cn when youlook) to download the source Python 3e2carxe file The lOLE can thenbe stated with the command: £413. Note that IDLE uns clifferent version From the one yau installed from source. @ python sudo opt=get install idle3 va 0 Peer Python=3.6.2. tar. xz. Now enter the newly unzipped Folder ee IPs then installed: check forthe latest update with: pip3 install --upgrade pip ERECT or ‘When complete, close the Terminal and Python 3. will be avalable via the Programming section in your distros menus DM's Definitive Gude Series Volume 31>) Say Hello to Python ) Installing a Text Editor eM ireleaeessACD elt kent aay a ASB eRe tel col athe] CMTC AUD (LMC Rone Reels ee MOU ROoke Koleos Le ee) unique characters, paragraph settings and much more, so it’s not a good platform For Vanes SUBLIME CODE Sublime Text is an excellent, cross-platform text editor that’s designed for entering code. It has a slick interface, many Features and performs magnificently. In short, i's an ideal starting point. PEPER 20's besin by navigating to the Sublime Text PRTISEDD Whichever version you choose, download the setup webpage, to download the latest version for files and double-
Colour Scheme. We've opted for IDLE in this screenshot. Sublime Text 3 BEET) 802s tresSublime Text offers sorne excellent Features over that ofthe standard Python IDLE. For example, enter the Flowing print (*Hietlo everyone!”) Thisis an actual Python command, which wil rine the words Hello everyone! on the screen. Notice how Sublime automaticaly recognises this as code and places the quotes and parentheses, BAPR S000, as you become more Python-sayw, youll find that the standard IDLE isnt quite up to the task ‘of keeping up with your code, alterations andinjections of code mid-way through along program. However, Sublime will keep you ‘updated and you can even utlise indents easly (Installing a Text Editor GC Sublime itu for Python ether. wth tyou can SUP build code for a number of programming languages. Clk on Tools> Bul Sytem ose whch languages yu abet build with n Sublime sublime comes witha number opefnstaled SUED plugins For Python cade, allowing you to experiment wh your codetn reat. theyre probable bewkderng st thspantn te bayou efi melas your Pon shlsnrese ‘AP Reterence werent going togetooheay nto the Suse y code right now but an indent is part of Python programming, where a statement ndcates hat the Flowing indented commands must be run una patclarevethes, appened fer niche inert sop Pressing Col indent Une oFcodein Pétion, However we recommend you use the DLEto Sue) ‘begin with, Although the Python IDLE isn’t as. advanced as Sublime, ts perfect base on which to bull your skis, Once youve mastered Python and the way wars, ou can move onto a text editor forthe better Features,Say HellotoC++ ) C++ is an amazing programming language. Most of what you see in Front of you when you power up your computer, regardless of whether you're using Windows, macOS or Linux, is created using C++. Being able to code in C++ opens up a whole new world for you in terms of desirable professional skills and the ability to code amazing apps and games. C++ is an efficient and powerful language that’s used to develop operating systems, applications, games and much more. It's used in science, engineering, banking, education, the space industry etc. We're here to help you take your First steps into the world of C++ and get your First Few lines of code up and running. 34 Why CH? 36 Equipment You will Need 38 Getting to Know C++ 40 How to Set Up C++ in Windows 42 How to Set Up C+ on a Mac 44 Howto Set Up C++ in Linux 46 Other C+ IDEs to Install BOM Definitive Guide Series | Volume 21erred ra Ce cc eMet ee Coe cReT TY ec Rene Keresse a ent Ate Kena CEM Serie a naars Orne cterce une cnert tiene seaeuoues Ceo eas CEVERYTHING D devic drivers and even entire operating systems. Dating backtto 1979, the startof the golden era of home computing, C++, or rather C with Classes, was the brainchild of Danish computer scientist jam Stroustrup while working on his PAO thesis. Stroustrup's plan was to Further the original C language, ‘hich was widely used sine the early seventies. C++ proved to be popular among the developers of the '80s, sinceit wasa much easier environment to getto grips with and more importanty, it was 89% compatible withthe original C language. This meant that It could be used beyond the mainstream Qwest ntnteien ‘to how complex the language can be, and its power and performance, C++ is often used to develop games, programs, computing labs and by regular people who didn't have access to the mainframes and large computing data centres. C+¥'simpact in the dgital worlds immense. Many ofthe programs, applications, games and even operating systems are coded using Cet. For example, all of Adobe's major applications, such as Photoshop, InDesign and so on, are developed in C++. You will find that the browser you surf the Internet with s written in C+, 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 Tp) #include
2 | using namespace std; 3 | void main() 4 |D{char ch; = cout<<"Enter a charater to check it is vowel or not"; 6 cim>ch 7 switch (ch) 8 jo ( 9 case'a': case'A': 10 cout<
) Say Hello to C++ ) Equipment You Will Need You don’t need to invest a huge amount of money in order to learn C++, and you don't need an entire computing lab at your disposal either. Providing you have a fairly modern computer, everything else is Freely available. C++ SETUPS ‘Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. IF you have one of those systems, then you can easily start using Python. COMPUTER Unless you Fancy writing out your C++ code by hand on a sheet of paper (whichis something many older coders used to do}, then a computer isan absolute must have component, PC users can have any recent Linux distro or Windows O5, Mac users the latest macos, (_] AN IDE fs wth Pthon, an DEis used to enter and execute your C+ code. Many DES come withextensionsand pluginsthat help make t wok better, or eddan ent levelof functionality. Often an IDE wil provide enhancements depencing onthe core OS TIPE ceesreeenmmneen | being used, suchas being enhanced for Windows 10 sree COMPILER = ‘Acompler isa program that will convert the C++ language into binary that the a computer can understand, while some IDEs come with a compiler builtin, others don't. Cade:Blacks is our Favourite IDE that camnes with a C++ compiler as pat ofthe package, More on this later TEXT EDITOR Some programmers much prefer to use atext editor to assemble their C++ code before running itthrough a compiler. Essentially you can any text editor to write code, just saveit with a.cpp extension. However, Notepad++ is one of the best code text editors available INTERNET ACCESS While it's entirely posible to learn how to code on a computer that’s not attached tothe internet, i's extraordinarily dificult. You will need to install the relevant software, keep it up to date, install any extras or extensions, and laok far help when coding. All of which require access to the Internet. | TIME AND PATIENCE sins ‘Yes, as with Python, you're going to need to set aside significant time to spend on learning how to code in Cr. Sadly, unless you're a genius, i's not going to happen overnight, or even a week. A good C++ coder has spent many years honing their craft, sobe patient, start small and keep learning sows tfatn ues ne(Equipment You will Need OS SPECIFIC NEEDS C++ will work in any operating system, however, getting all the necessary pieces together can be confusing to a newcomer. Here's some OS specifies for C++. WINDOWS {As we've mentioned previously, a good IDE is Microsoft's Visual Studio, However, a better IDE and compiler is Code::Blacks, which is regularly kept up to date with a new release twice a year, 50. Otherwise Windows users can enter their code in Notepad++ then compile it with MinGW — which CodeBlocks uses, LIN Linux users are luckyin that they already have a compiler and text editor built into their operating system. Any text editor willallow you type aut your C++ code, when k's saved with a cpp extension, use g++ to compile aaa The Raspberry P's operating system is Raspbian, which isLinux based, Therefore, you'r able to write your code out using text editor, then compile it with o+¢ as you would in any other Linux distro, Mac owners wil need to download and install Xcode tobe ableto comple their Crt code natively, Other options For the macOS include Netbeans, Eclipse or Code:Blocks. Note: the latest Code:lcks isnt available For Mac due toa lack oF Mac developersEP Say Hello to C++ ) Getting to Know C++ See OPC cul ecu AGRO oe Ces CST or work at the cutting edge of science or engineering technology, then being able to ore Rem eae eam ete mcetel hol cine nonce ot #INCLUDE
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. #INCLUDE [ul Dn Dn Sheweedacepp cao The structure ofa C++ program is slightly different to that of eee eee ee Python and accaly ferent LO BASIC Every Cr+ code Desinsuithadrectve, tne <>, The directive instructs the \¢|*newcode.cpp * preprocessor toincudea Seclonofthestandardces #inelude
cece, For exaple Minelude Siostreams ncudesthe Ssareambeadertosippo inntlourpt operations ford C#+- wasinvented by Danish student Bjarne Stroustrup in 1979, a8 apart of his PRO thesis. Initially C++ was called E Cwith Classes, which added Features to the already popular programming language, while making ita more User frienaly environment. Bjarne 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 isa group of code statements, ‘unde the name ‘main. All (CH code begins at the main Function, regardless of where it |!) *neweade.cpp %: _ctually les within the code, #include
int main() BRACES. . *newcode.cpp(-/Documents) = The open braces File Edit View Search Tools Documents Help something that you may rot have come across before, especialy if you're {sed to Python. The open braceincicatesthe —_|(@')newcode.cpp beginning ofthe main Function and contains a the code that belongs to , that function int main() { sows tft eset ne #include
COMMENTS Lines that begin with a double slash are comments. This means they won't be executed in the code and are ignored by the compiler. Why are they there? Comments are designed to help you, or anather programmer looking at your code, explain what's going on. There are two types of comment: * covers multiple ine comments, // a single ne, . ‘“nowcode cpp (-yDocumonts) ‘le dt view Search Took Documents Help Bae Ay (c)mewcodecop % \Ainclude
using nasespace std; int main() (109) First Coe progrant COUT In this example we're using cout, which isa partof the Standard Namespace, hence why i’ there, as you're asking C++ to useitfrom that particular namespace, Cout means Character OUTput, which clsplays, o prints, something to the screen. IFwe leave std: out we have to declare itatthe start ofthe code, as mentioned previously, . sneweode. File Edt View Search Tools Documents Help (-/Decuments) include
int main() 4 Uy first C+ progrant << The two chevrons used here are insertion operators. This means that whatever Follows the chevronsis tobe inserted into the std:cout statement. Inthis case the words are ‘Hello World, which ‘are tobe displayed on the screen when you compile and execute the code, ~ “Snewcode.cpp (-PDocuments) Fle eet View Search Tools Documents Help (ch tnemcode.cep % leinclude
Lint main() Ic 11 My first Coe program Std:teout <¢ (oHeli9 World!\n") OUTPUTS Leading on, the (Hello world”) partis what we want to appear on the screen when the code is executed. You can enter whatever you lke, as ong as ts inside the quotation matks, The brackets aren't, needed but some compilers insist on them, Then part indicates a new line isto be inserted 11 My First Css progrant cout << ("Hella World! \n")| sta ;AND} Finally you can see that lines within a Function code block (except comments) end with a semicolon. This marks the end ofthe statement and ll statementsin C++ must have one at the end or the compiler wil failto build the code. The very last ine has the closing brace to indicate the end ofthe main Function, sovsoenieceses eines Getting to Know C++ GcEP Say Hello to C++ ) How to Set Up C++ in Windows ANTM ETE RN] eRe anol eR N UN
New > Empty File, Ths creates anew, blank window for you to type in BREED the new window, enter the folowing: #include
Int main { ZN first C+ program Std: :cout << “Hello World!\n"; I Notice how CodesBlocks auto -inserts the braces and speech quotes. CekFlerSavessandsaethecode tha BEAD .cpp extension (helloworld,cpp, for example), Code: Blo changes the et color code scordng toc Sarda Teeth code chvon te Bud and Run con along the op oF hesren es greeny con ogeter wth yawn») =P Say Helloto C++ ) How to Set Up C++ ona Mac BOR te eels eRe B ME Cone Ma ec 0-919) ecole MLB] Le featured IDE that's designed to create native Apple apps. However, it can also be used to create C++ code relatively easily. XCODE Apple's Xcode is primarily designed for users to develop apps For macOS, iOS, tvOS and watchOS applications in Swift or Objective-C, but you can use it for C++ too. BIER St2"t by opening the App Store onyour Mac, Apple REE When you're ready, click on the Get button which "Menu > App Store, In the Search box enter Xcode and then tums into ‘install App’. Enter your Apple ID press Return, There will be many suggestions filing the App Store and Xcode begins to download and install. It may take some time ‘window butt’ the first option, Xcode, that you needto cickon, depending on the speedof your Internet connection. Takea moment tobrowse hough he 6 henthe instalationis complete, dckon the Open gue information, including the compatibility to ensure Sree ‘button to launch Xcode. Click Agree to the licence younavethecorectvetson a macos.neodevequres macOs tes andenter your passucrdt slew Xeade to mate changes 10.12.6 or later to instal and work tothe system. When you've done that, Xcode begins to install ‘additional components. BED) 80s 2s tresC How to Set Up C++ on a Mac Gc BERD ith everything now installed, inctuding the BRTeEEDD The next step asks where to create a Git Repository additional components, Xcode launches, displaying forall your future code. Choose a location on your the version number along with three choices and any recent projects Mac, ora network location, and lick the Create button. When that you've worked on; although fora fresh instal this shows blank you've done all that, you can startto code. Thellft-hand pane details the files used inthe C++ program you're coding, Click on the main.cpp file in the list. Welcome to Xcode i seameree STEED 2" clickingon Geate new Xcode Proictthis ESTEEM Youcan see that code has automaticaly ‘pens a template window From which to choose the completed abasic Hello Werld program For you. platform you're developing code for. Click the macOS tab, thenthe The differenceshere ae that the int main ( function now contains Command Line Tool option and finally, Next to continue. multiple Functions and the layout s slightly different, Thsisjust Xcode utilising the content that's avalable to your Mac. co: ERQGETTT errr oor PRED Flin the various elds but ensure thatthe BEELER Vihen you want torun the code, click on Product > Language option at the bottom is set to C++, Simply Run, You may be asked to enable Developer Mode choose it from the drop-down lst. When you've filedin the fields, on the Mac; thsis to authorise Xcode to perform functions without and made sure that C+ isthe chosen language, click on the Next’ _ needing your password every session, When the program executes, button to continue, the output s displayed at the bottom of the Xcode window. sebtncon sone ie Senne>) Say Hello to C++ / How to Set Up C++ in Linux Linux is a great C++ coding environment. Most Linux distros already have the FIle eed era nd RSH eo] eee RR SO UN ee Reg neh Red excellent for entering code into, including colour coding; there's also tons of extra software available to help you out. 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 of the book. BTID the rst step with ensuring Linuxis ready for your C+ codeis check the system and software are upto date, Open a Terminaland enter: sudo apt-get update 8K sudo apt-get upgrade. Press Return and enter your password. These commands updates the entire system and any installed sofoware. File Edit View Search Terminal Help FETTER ost Linux distros come preinstalled with all the necessary components to start coding in C+. However, ts always worth checking to see if everything is present, so still withinthe Terminal, enter: sudo apt-get install build-essential and press Return. IF'you have the right components, nothing is installed but if you're missing some then they are installed by the command. sows tfatn ieee ne “Amazingly, that’s it. Everythings allready for you tostart coding, Here's how to get your fst C++ program up and running, In Linux Mint the main text editors Xed can be launched by clicking on the Menu and typing Xediinto the ‘search bat. Click on the Text Editor button in the right-hand pane to open Xed. ined or any other txt dor you may be sn, Sue enter the lines of code that make up your C++ Hello World program. To remind you, its: #include
int mainc) { My first. C++ program “Hello World!\n"; std::cout << sinciude
¢ Uiny first Cos Progra Cea scout Suelo worksnvnrs »PETES when you've entered your cade, click File > Save AS and choose a older where you want tosave your program, Name the fileas heloworld.
(20M Defintive Guide Series swonacnpubicationstCoding on Linux ) Why Linux? NNR ae eee erest ech ce Cate ac an operating system base for their coding and testing, but why? Linux has many. Eco e-1e) =e) te en -UCe Rae CoM ESO eC sd Cele Belg place to learn to code. FREE AND OPEN Linux isa 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 frst thing we need to addressis that there is no such operating Linux works considerably differenti to Windows or macOS. t's system called Linux. Linuxisin Fact the eperating system kernel, the free Fora start, Free to dawnload, install on as many computers. as core component of an OS. When talking about Linux whatwe, and you ike and use for an unlimited amount of time, I's also free to others, are referring to are one ofthe many distributions, or distros, upgrade and extend using equally Free programs and applications. that use the Linux kernel, No doubt you've heard of atleast one of This free to use element is one of the biggest draws forthe the current popular distros: Ubuntu, Linux Mint, Fedora, openSUSE, developer, While @ Windows license can cost up to £100 and a Mac Debian, the list goes on. Each one ofthese distros offers something one considerably more, a developer can quickly download a distro alittle different forthe user, While each hasa the Linux kernel at and get towork cadingina matter of minutes, its core, they provide the user witha different looking desktop environment, different preloaded applications, diferent waysin Alongside the Free to use aspect comes a level of freedom to which to update the system and get more apps installed and a slightly customise and mould the system to your own use. Each ofthe dlfferent look and feel throughout the entire system, However, at available distros avalable an the Internet have a certain spi’, the centre les Linux which is why we collectively say, Linux in that some offer increased security, afancy looking desktop, 2 Linuxcs a great operating system in 4D which to stare coding, Dealnr xecas BBB On ne — a‘gaming specific spin or something directed towards students. This ‘extensibility makes Linux a more desirable platform to learn coding ‘on, as you can quickly shape the system into a development base, including many different kinds of IDEs for the likes of Python, web evelopment, C++, Java and so on, Another remarkable advantage is that Linux comes with most of the popular coding environments bult-n, Both Python and C+ are preinstalled in a high percentage of available Linux distros, which means you can start to program almost as soon as you install the system and boot it up or the First time, Cenerally speaking, Linux doesn't take up as many system resources as Windows or macOS. By system resources we mean memory, hard clive space and CPU load; the Linux code has been streamlined a isfree from third-party bloatware’ which hogs those systems resources, A more efficient system of course means more available resources forthe coding and testing environment, andthe programs you eventually create, Less use of resources also means you can use Linux on older hardware that would normaly struggle or even refuse torun thelatest versions of Windows ar macOS. Sorather than throwing away an old computer, itcan be reused witha Linux distro, ‘There are thousands of Free packages avallable for programmers under Linux. Why Linux? However i's notall about C++, Python or any ofthe other mare popular programming languages. Using the commandline of Linux, ‘also called the Terminal, youre able to create Shell scripts, which are programs that are designed to run from the command tine 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 ist, there are thousands and thousands of free programs and apps available that cover near every aspect of computing. Known as packages, there are (atthe time of writing) over & 700 specific programming applications jst for Linux Mint alone. Linux therefore, isa great resource and environment For programming in. t's perfectly suited for developers and is continually improving and evolving. Fyou're serious about getting into coding, then give Linuxa try and see how it works for you. XO Ob wane cos @ @ 2 A Each distro offers something unique to the debian user but all have Linux at the coe. ‘ALinux programming environment can be as simple or as complex as you need it to be. swonvcinpubications cm DM's Definitive Guide Series Volume 31Equipment 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 platform, with many languages built-in. Here’s what you need to get up and running ATRL a UUs 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 lows: Obviously the better the system you have, the better the experience willbe, and quicker too. cpu TOOMHe RAM 512MB, Hard Drive Space 98 (2068 recommended) Monitor 1024x768 resolution Usa eeU ey) (ou can install Linux Mint onto your computer via USB or VD. We'llook into each a ttle later on but iF you're already familar with the process oF you're thinking of USB and just jthering the hardware you need, then you're going to needa minimum 4GB USB flash chive to contain the Linux Mint ISO. rTEquipment You will Need INTERNET CONNECTION It goes without saying realy, that an Internet connection is vital For making sure that Linux Minti up to date with the latest updates and patches, as wells the installation of Further software, Although you don't need an internet nection to use Linux Mint, you're sure to miss out on & id of free software avallable for this distro, DVD INSTALLATION DvD instalation of Linux Mint simply requires a blank DVD-R disc. Ofcourse, you also need a DVD Writer drive before you cantransfer or burn the ISO image to the disc : Ser although Linux Mint can be installed onto a Mac, there's Ea schoolof thought that recommends Mac owners use 2 £ virtual environment, such as VirtualBox or Parallels; and why ‘not, macOS is already a splencid operating system. IFyou're wanting to breathe new life into an older Mac, make sure it's } amintel CPU model and not the PowerPC models. ENVIRONMI viRT installation toa virtual environments a favourite method of testing and using Linux distros. Linux Mint works exceedingly well when used ina virtual environment, More on that ater There are many different virtual environment apps available; however for thisbook we are using VirtualBox from Oracle. You can get the latest version From wwwa.virtualbox.org, DM's Definitive Guide Series | Volume 3Transfer Mint to DVD or USB You need the latest version of Linux Mint before you can transfer it to a DVD or USB. Go to wwwilinuxmint.com/download.php and download the 64-bit version of Cinnamon to start with. Other versions can be tested once you're accustomed to the system. DVD BOOTABLE MEDIA We're using a Windows 10 PC here to transfer the ISO to a DVD. If you're using a version of Windows from 7 onward the process is extremely easy. Fstlocate the 50 mage of Mint youve already Right the Mint 50 and from the menu select SueHi downloaded. You can usually Find this in the suds Burn Disc Image. Depending on the speed of the PC, Downloads flder of windows 7, 81and O.omputersulessyou may take afew seconds before anything haopens, Dont wary too spedtied ferent locaton when saving truth, ules takes more thane minute nwhchcase might be eth restartng your PC arctyng ag, with ike indore Dc mage Burer should launch ratte ht [B amnth on Dede ar 3 one #8 crown PETER Next insert a recordable DVD disc into your ESTEEM Fotieclick the mint so and from the menu select computers optical drive, After afew seconds, while Burn Disclmage. Depending on the speed of the PC, the discisread, windows will dsplaya pop-up message asking you it may take a Few seconds before anything happens, Don't worry too what to do with the newly inserted disc: ignore tis, as you're going much, unlessit takes more than a minute in which casei might be tose the built-in image burning Function ‘worth restarting your PC and trying again, With uck, the Windows Disc image Burner should launch, © Windaw: Die Image Burner * Diseimage file: finuxmint-18.1-cinnamen-6abit iso DVD RW Drive (E:) Dise bumer BD-ROM Drive (D:) Status Burning disc image to recordable disc iUSB BOOTABLE MEDIA (Transfer Mint to DVD or USB? \ USB mediais 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 imag easy but you need a third-party app first and a USB Flash drive of 4GB or more. PEPER Ficstoven up wed browser and goto www.rufus ‘akeoie, Scroll down the page alittle and you come to a Download heading, under which you can see the latest version of Rufus (2.12 in thisinstance). Let click the link to start the download, BETEE RD When youre ready, click on the start button atthe bottom ofthe Rufus app. Ths wil open up another dialogue box asking you to download and use anew version of SysLinux, SysLinux is a selection of boot loaders used to allow a modem PC to access and boot from a USB flash drive, Iisnecessary, so click on Yes to continue, Double-click the downloaded Rufus executable; you can click Yes' to the windows security question and "yes'to checking or updates, With Rufus launched it should have already identified your inserted USB flash drive; F not just remove and reinsert. F Rafe 211.995 - x ewe bank {866 USS Fla (E) [7.968] ¥ Partition scheme and target system ype [MBR partition scheme for BIOS of UEFI ¥ File system A032 (Default ~ ‘Guster size Aft lance the Rufus interface can ok ile usr) confusing, don't worry though it's really quite simple, To begin with, cckon he dc and dive kon nett the Create abootble dk sng’ section andthe FreeDOS pulldown menu. Theil surcha Windows Explore window whereyo an loate and selec the Lnox Mint 6 ‘The next step asks which image mode you want the Mint 150 to be written to the USB flash drive in. Both methods work for cferent situations but generally, the recommended ISO Image Mode isthe more popular, Make sure this mode is preselected and click OK to continue, followed by OK again, tocconfirm the action. (© Wen 0 gered Racrmerded) The Mint 150 is now being transferred to the USB flash drive, The process shouldn't take too long, again depending on the speed of the USB device and the PC. You may find Rufus will auto-open the USB drive in Windows Explorer during the process; don’t worry you can minimise or close iif you ‘want. When the process is complete, click on the Close button. Create a bootable disk using [ROMSGE (Ea Create extended label and icon files | Copying 0 fs BSH [tos startCoding on Linux Installing VirtualBox 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. FEED the fist taskis getting hold VitwlBox. Fyou withthe correct pa haven't already, head over to www.virtualbox.org a 8 kon here oun fownloaded, and before we install anything, you need to make sure that the an VirtualBox 5.1’ box. This will take computer you're using sable to host a VM, To da this, reboot the you to the main download page. Locate the correct host for you system, Windows or Mi the hosts the current installed o computer and enter the BIOS. As the system, and click to begin the ¢ Del, F2 or whichever key is necessary ting omputer stats up, press the Enter Setup, wnload, oe yg VirtualBox elcome fo VituelBoxora! Viruatbox Dod SB devices, aswellasnumerous other However extras that can help make the VM environment amore accurate emulation of areal computer 1 each BIOS i laid out differently i's very difficult toassess where to lookin each per nal example. 35 general rule of thumb, you're looking for intel Virtualisation Technology or simply Virtualisation it's usually within thea n ofthe BIOS. When you've located it, Enableit settings, exitthe BIOS and reboot the computer. BG VirtualBox Download VirtualBox BOM Definitive Guide Series | Vole 2With the computer back up and running locate the downloaded main VirtualBox application and double-click to begin the instalation process. Click Next to continue, when you're ready, (frac Valor 51.10 Setup * Welcome to the Oracle VM VirtualBox 5.1.10 Setup Wizard ‘he Seno herd eva te tte S.3060 {ou corp athe orenue Caco eat Setomeos The default installation location of VirtualBox should satis'y most users but if you have any spectal location requirements click on the Browse button and change the instal Folder. Then, make sure that all the icons inthe VirtualBox Feature tree are selected and none of them have a red X next to them, Click Next to move on, (Oater necaren ne neebeon harge ea fete wl beta, oon ep aeer Batre seed he Son. This ection can be left alone to the defaults, should you wish. It simply makes life alittle easier when dating with VMs; especially when dealing with downloaded VMs, as, you may encounter inthe future. Again, clicking Next will move you onto the next stage. esestrtnenenres oeseesertaten te etn oewes rrr ne qua anerear Dept Se noctre io C Installing VirtualBox GC When instaling VirtualBox your network connection, will be disabled for a very brief period. This is due to VirtualBox creatinga linked, virtual network connection so that ‘any VM installed wil be able to access the Internet, and your home network resources, via the computer's already established network connection. Click Yes then install to begin the installation. Sia Warniny Network Interfaces ety race enon. ating Kouta nett crechn ao ereray Seorract yo tos eo < Poca whitlten rom? BREE You may well be asked by Windows to accept a secutty ntifcation; dick Yes For this and you may encounter a dialogue box asking you to trust the installation from Oracle Again, click yes and accept the installation ofthe VirtualBox application. wihen k's complete, click inh to start VirtualBox With VirtualBox up and running you can now STEP 10 install the VirtualBox Extension Pack, Locate the downleaded add-on and double-click. There may be a short pause ‘hile VirtualBox analyses the pack but eventually you receive a ‘message to install it; obviously clckinstalto begin the process, scroll down the next screen to accept the agreement and click Agree! og oo Oracle VM VirtualBox 5.1.10 istallation is complete. seer we son 50a tat 20M Definitive Gude Series |voiumes! JCoding 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, replaces the traditional BIOS but can cause issues when installing Linux Mint. FEED ser your DVD or USB Fash drive into your PCand, EM wit us iFyou haven't already, shutdown Windows, Inthis ow two ways oF booting into the Mint Live instance we're using the USB boot media but the processisvirtually Environment, The fits is va the BIOS you're already in. Locate the tical, Startthe PC and when prompted press the appropriate Boot Sequence and change the ist boot device From its original ysto enter the B105 or SETUP: these could be, For example, F2, setting, usually Internsl HOD or similar, to USB Storage Device Fo Delor even 12 the USB media option; or BVO Drive, For the DVO media option tuned to Legacy mode, there are FETED there are different versions of a UEFIBIOS, so FSTP DD \teratively use the Boot Option Menu. with this covering them all would be impossible, Ww jon you can press F12 (or something similar) looking for isa section that detailsthe Boot Sequence or Boot todisplaya lst of act media options; From there, yo "Made. Here you have the option to turn off UEFI and choose L the appropriate boot media. Either way, you can or disable Secure Booting. Mint does work with UEFI but itean bea the BIOS by navigating to the Save & Exit option ane tricky process to enable't to boot Changes and Exi hoose w save and exit id choosing Save BOM Definitive Guide Series | VoleTESTING MINT With the UEFI BIOS side of things behind us, it’s tim Live Environment. BETTER “loro the bottom ofthe desktop isthe Mint Panel and the Mint Menu. Clickthe Menu and t displays the core applications along with a search bar and various icons lined up down the left-hand side. These are quick launch icons that wil change tothe more recently used apps as you use Mint BETTER the three icons tothe bottom of the quick launch strip indicate the session options: Lock Screen, Logout and Quit (shutdown Linux Mint) Just above the Lock Seren iswillaunch Nemo, the Linux Mint Cinnamon icon is Files, licking th file manage see what the Linux Mint desktop ha: Testing Linux Mint’s Live Environment @¢peg offer, albeit in the test, Te the Far right of the Panel, you can see several icons; these indicate the current logged in use account which Live Session User at present, active network connections (where you can adjust or setup your Wii or wired internet connection), volume controls, time and date, and all ‘Windows, which when clicked displays all opened apps PREM there are also some quick aunch icons on the Panel next to the Mint Menu: Show Desktop, which vill return you toa blank desktop while minimising all open ap Firefox web browser, the Terminal command line; and Nemo file manager. You can use any ofthese ina live session but anything stored won't be saved on quitting, Jou install Mint, you need to make sure you ve Internet connection. IF you have 8 wired, Ethernet connection, andit'snot already plugged into the computer, do so now. Fyou're using WF, click an the network connection con in the bottom right ofthe Panel, ind your router id and enter the detail. DM's Definitive Guide Series | Volume 3Installing Linux Mint onaPC You've picked your Linux Mint desktop version and you've played around in the Live arene OVS ARK la Cen oh ot meee Eales cele Windows. Thankfully the process is extremely easy. GOING MINT We're assuming at this point that you're still in the Live Environment and that you've set up and activated your Wi-Fi connection, or plugged your computer into your router via a wired connection, FETED ovidine youre connected tothe ntemet (trot REM Arter clickino Continue you're asked ityou want then do so now) and you're in the Live Environment, to Install Third-Party Software, Providing youre start the installation process by double-clicking on the InstallLinux connected to the internet, as from Step 1, then tik the box. This Mint icon on the desktop, vill make sure that hardware drivers, Adobe Flash and codecs For, MP3 and video files are installed withthe main Mint system, Click Continue for the next stage. PED 2unching the install Linux Mint app will open up FETTER) This next stage asks you how you want to manage the Welcome screen. Make sure your language is the installation of Linux Mint onto your PC. In ou selected from thelist on the left and if you wantto clickthe Release example, we're going ta Erase Disk and install Linux Mint, which wil ‘Notes lnk taread what the latest changes and additionsareto Linux wipe the current OS and ALL DATA replacing it with Mint: make sure Mint 18.1 Cinnamon, When you're ready, click the Continue button. you have a goad backup, justin case. Clik Install Nowe to continue.PRFID fore the installation pracess can begin, you're asked if the choice you made regarding the erasure ofthe hard drive is correct. This s your last chance to back out. IF you're certain you don’t mind wiping everything and starting again with Linux Mint, lick Continue BSED This next stage determines your location. You can enter the nearest major city, ar even try your local town and see ifit’s inthe lst of available choices, When you're ready, click Continue, Berea Next up. use the options to pick which keyboard you're using. In most cases it wil be the option with the Extended Winkeys. Use the Type Here. your keyboard setup is correct. Click Continue when you're ready to oxto tes ications BOTS this stage you need to set up your Mint username and password. Enter your Name to begin with, then Computer Name, which isthe name it's identified on the network as Next choose a Username, followed by a good Password, You can tick the Login Automatically option but leave the Encrypt Home Folder ‘option for now. BEER The installation process will now begin and you can 22 whats being installed along the bottom of the install window. Yo% nalso.use the arrows on the sereen to browse through some of the Features available in Linux Mint PEEND When the installation iscomplete you are presented with a completion box, asking you you want to continue with the Live Environment or restart the PC DM's Definitive Guide Series=P Coding on Linux Installing Linux Mint in VirtualBox With Oracle's VirtualBox now up and running, and continuing from the previous section, the next task is to create the Virtual Machine (VM) environment into which Von Ta rie=] (Mia alia CREATING THE VM ‘There are plenty of options to choose from when creating a VM. For now though, you can set up a VM adequate to run Mint. Cinnamon and perform well, ith vituaBon open cok onthe Newicanin “Thenent section deine the amour stem the top right of the app. This will open the new memory (RAM) the VM has allocated, Remember. rome Uisamountwibe ac rom te tobe meray instant ae your conputer se dorset Veo much For eon we have 8CB of memory installed and we're giving 2GBtto the VM. ‘When you're ready, click Next to continu eee pees. ie oes @ ay : aan In the box next to Name, type Linux Mint and “This section is where you start to create the virtual VirtualBox should automaticaly choose Linux hard disk that the VM will use to install Mint onto. asthe Type and Ubuntu (64-bit) asthe Version. Ifnot thenuse The default option, Create a virtual harddisk now’, isthe one we're the drop-down boxesto select the correct settings; remember using, Click Create to move on, Mint mainstream is based on Ubuntu. Click Next when youre ready to proceed. 1 | “a i i li i i i IPEPER the pop-up window that appears after clicking Create is asking you what typeof virtual hard disk you want to create. Use the default VOI (VirtualBox Disk mage) in this case, as the others are often used to move VMs from one VM application to the next, Make sure VDI is selected and click Next Te aueston of whether oop for Dynamically SUES or Fixed sized virtual hard disks may come across asbelngsomevhatconfsing ta the newcome basal, Dynamical Allocated wituathard dks 8 more Hebe rage ranagemenc option. Ik wort tke up muchspace within your blysalhard daktobesn vith ether Ensure Dyamkaly located selected and ick PEED The virtual hard disk wl be a single Folder, upto the size you state inthis section, Ensure the location ofthe virtual hard disk, on your computer, has enough Free space available. For example, we've used a bigger storage option on our DA drive, named it Linux Mint and allocated 25.50G8 of space to the virtual hard disk Installing Linux Mint in VirtualBox ERTISESRD ter clicking Create the initial setup of the vat is complete; you should now be looking atthe newly created VM within the Virtualliox application. Before you begin though, click the Settings button and within the General section lick the Advanced tab, Using the pulldown menus, choose ’directiona’ for both Shared Clipboard and Drag'n'Orop. SPEED Follow thatby clicking on the System section, then the Processor tab. Depending on your CPU allocate 35 many cores asyou can without detriment to your host system; we've opted for two CPUs, Now click on the Display section, slide the Video Memory up to the maximum and tick Enable 3D Acceleration. Click OK to commit the new settings PETD ick on the Start button anduse the explorer button in the ‘Select Start-up Disk’ window to locate the downloaded ISO of Mint; the explorer button isa Folder with a green arrow. Click Start to boot the VM with the Linux Mint Live Environment. You can now install Linux Mint as detailed in the previous installing Linux Mint ona PC section. =o DMs Definitive Gude Series Volume 3BY 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 e Terminal. programs designed to be run i nere you begin your journey suzFil with Linux, through the command line and thus. any scripting rom. In Linux Mint, it can be accessed by licking on the Menu Followed by the Terminal icon inthe panel, or entering "Terminal into the search bar. FSTSERD het you currently see inthe Terminal is your login name Followed by the name ofthe computer, 35 you named it when you Fits installed the OS on to the computer. The line then ends with the current Folder name; at First thisis ust a tilde (Oy whieh mesns your Home Folde FEED the Terminal will give you access to the Linux Mint Shel called BASH; this gives yo the underlying operating system, which s why scripting powerful language to learn and use. Everything in Mint, and Linux asa whole, including the desktop and GUI, isa module running From the command line ‘leet View Search Terminal Help ROMs Definitive Guide Series | Volo 2 FSP D the ashing cursor atthe very endof the tine is where your textbased commands will be entered. ‘You can begin ta experiment with a simple command, Print Working Directory (pw), which will output to the screen the current Folder you're in. Type: pad and press Enter adedavi File_Edt View Search Termin! Help( Getting Ready to Code in Linux BETIS lithe commands you enterwilworkin the same RIP the lst of available Linux commands is vas, ‘manner. Youenter the command, include any with some simply returning the current working parameters to extend the use of the cammand and pressEnterto directory, while others are capable of deleting the entre system in execute the command tine you've entered. Now type: uname” =a _aniinstant. Getting to know the commands is part and press Enter. Ths wil display information regarding Linux Mint. of learning howto sat. By using the wrong command, you could In scripting, you can use all the Linux commancitine commands tend up wiping your computer. Type comgen =C to view the thin your own script. available commands, eviderdavidmint = Fie Edit View Search Terminal Help a ae ee 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. Having access to the Terminal means you Therefore it’s aways @ good idea to workin the bypassing the GUI desktop method of working Terminal using a two-pronged approach. Fist, use with the system, The Terminalis afar more powerfulenvironment the desktop to make regular backups of the Folders you're working than the desktop, which has several safeguardsin place incase you _inwhen inthe Terminal. This way, should ansthing go wrong, there's accidentally delete all your work, such as Rubbish Bin to recover a quick and handy backup waiting for you deleted files ESTED ovever,the Terminal doesnt offer that lusury.if RIMM second, research before blindly entering a you were to access Folder with files within via the command you've seen on the Internet. IFyouseethe erminal and then enter the cornmand: Fm*.*, allthefilesinthat_ command: Sudo ‘dd if'=/dev/random of=/dev/sda and use folder would be instantly deleted, They won't appear'in the Rubbish it ina script, youll soon came to regret the action as the command Bin either, they're gone For good vill wipe the entire hard drive and iit with random data, Take a moment to Google the command and see what it does, david@david-mint IM Go ocle gesnmonecnam Terminal Help “ 20M Definitive Guide Series Volume 31Coding on Linux Creating Bash Scripts —Part 1 GET SCRIPTING A Bash scripts simply a series of commands that Mint will run through to complete a cert remarkably complex, it all depends on the situation. $k. They can be simple or ESTESERD You'llbe working within the Terminal and witha FEED To bein with, and before you start to write any text ector throughout the coming pages. There scripts, you need to create a folder where you can are alternativesto the text editor, which welllook atina moment put allourscriptsinto, Start with mkdiim Scripts, and enter the but forthe sake of ease, well be doing our examples in Xed. Before folder ed 'Seripts/. This will be cur working Folder and from here you begin, however, run through the customary updat you can create sub-folders if you want of each script you create. apt-get update && sudo apt-get upgrade Suere ‘a Bash script: Xed, Vi, Nano, Vim, GNU Emacs and Sus batch file to work, asin be executed and Follow the soon Inthe end kal comes dou to prsonl preference Our programming within eneedsto havea aa feextension nik use of Xed fs purely dueto making iteasierto read the script inthe isan extensiar-less operating system but the corwention isto give screenshots you see below scripts a sh extension Fle E6t View Search Terminal Help OMS Definitive Guide Series | VoliPSTD 22'sstart with asimple script to output something tothe Terminal. Enter xed helLoworLd.sh. Xed and create a file called helloworld sh, Xe6, is wil aun: enter the folowing: #1/bin/bash, then on a newline: echo Hello World! lett View Search Terminal Help Fle EM View Search Teo Oscuments Help Boaln~|/xoaojag + esnyoaeh acne netto morlat The #1Zbin/bash line tells the system what Shel youre going to be using, in this case Bash, The hash nent ine, one that is ignored by the system, the exclamation mark ( means that the commenti bypassed and will Force the script to execute the line asa command. This i also known asa Hash Bang, () denotesa con Fle Edt View Search Tools Documents Help poale~ xoo,aa sheloneiish bin/bash acho netto world You can save thisfile, clicking File > Save, and exit SMD 20.10 the terminal entering Ls, wil eveaithe scriptin the Folder. To make any script executable, and able to ‘un, you need to modify its permissions. Do this with chmod +X heLLoworldssh, You need to do this with every scriotyou create. File ESR View Search Terminal Help Creating Bash Scripts —Part 1 When you enter US again, you can see that the hhelloworld.sh script has now turned from being to green, meaning that it's now an executable fle. Torun the scrip, in other words make it do the things you've typed int it -/heLLoword.sh. Fle Edt View Search Terminal Help SPD tnouah it’s not terribly exciting, the words Hello ‘World should now be displayed in the Terminal The echo commandis responsible for outputting the words after it inthe Terminal, as we move on you can make the echa command pea fie ESE. Vow Search Took Docume Help aoa xonlag Pm etowerash e1oin/bash BSTSET DD) Thick of echo as the old BASIC Print command. t splays either text, numbers or any variables that are storedin the system, such asthe currentsystem date. Try this example: echo Hello World! Today is SCdate 4KA). The {date +%A) is calling the system variable that stores the current day of the week. DM's Deiitive Guide Series[P-» 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 oruser crested. Lets startby creating a new scrip called hells SueF il xed heLLo.sh. in it enter: #1/bin/Bash, then, echoHelLO7S1 Sovethe ie and ent Med. Backinthe Terminal trae the senpeeveciable wth chtod 4% hel1O,sh poo xeojaa FEED the output now will be Hello David. Thisis because Bash automatically assigns variables for the user, ‘hich are then held and passed to the script, So the variable '51" now holds ‘David’. You can change the variable by entering something different: s/hel1o. sh’ Mint. Fle Edi view Search Terminal Hey Pere Ce st Patracare) eee tea races pete) Asthe script isnow executable, run itwith 9 helo. sh. Now, as you probably expected a simple Hell is displayed in the Terminal. However, ifyou then issue the command with a variable, it begins to get interesting. For example, try a/hello.sh David OMS Oefnitive Guide Series You can even rerame vale. Mody the hel Su sh script with the following: firstname=$2) surnane=$2, echo Hello Sfirstname $surname. Putting each statement on anew line. Save the script and ext back nto the Terminal le Eat View Search Took Docens Hep xo0 ag ao%en youun the sep nw yu cn Ee to Gus custom variables: «/heL lo. sh David Hayward. Natural change the two varabes wth your oun ame; ness youre ako caled Dav Hayward. atthe moment we're st printing contents set’ expand Ue twowarabe we able FETED create anew scriptcalled addition:sh, using the same formatas the hello sh script, But changing the variable names. Here we've added finstaunber and secondnunber, and used the echo command to output some simple arithmetic by placing an integer expression, echo. The ‘Sui is $(CSfirstnumber+Ssecondnunber)). Save the script, and make itexecutable (chmod +x addition. sh). Fle Edt View Search Toole Documerts Help aoa yoo ag $€(stirstmunbersssecondounber)) When: enter two numbers usa /addition.sh 1 2. the result hopefuly be uth the Terminal slaying Thesum 53, Ty Rwth afew diferent numbers andsee whathappens See also you con alter the egtandrenome tco mulepston, andsubtaction File Edie View Search Terminal Help Creating Bash Scripts —Part 2 inthe Let's expand things Further. Create a new script called greetings sh. Enter the scripting a reenshot, save it and make it executable with the chmod command, You can see that there area few new additions tothe Fle E8t View Search Tools Documents Hep poale» xoo ag im oeetnassh etybinvbash STD) Weve added a nto the echo command here which willleave the cursor on the same line asthe ‘question, instead of a newline. The mead command stores the Users’ input as the variables Firstname and suename, to then read bback later in the last echo line, And the Clear command clears the screen, SPELT RD’: final action, let's include the date variable we used in the last section, Amend the last line ofthe scristtoread: echo Hello Sfirstname Ssurnane, how ‘are you on this fine $(date #A)?. The outputshould display the current day ofthe week, calling it fram a system variable. Fle £60 view Search Tove Docurens Help poo xoaojag Du reengssh x ‘1/binybash eee ieee terete and Firstname feed surname fecho Hello Sfirstnane ssurnane, how are you on this fine §(dat DM's Definitive Guide Series | Volume 3Creating Bash Scripts —Part 3 In the previous pages we looked at some very basic Bash scripting, which involved outputting text to the screen, getting a user's input, storing it and outputting that to fen race Ree aes eR] CR Nena a P-leReo uae mh Vad combine what you've achieved so far and introduce Loops. 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. ‘The next line ELSE, is what happens ifthe variable instructions and simply work out that IF something is present, THEN cdo something, ELSE do something diferent. Create a new script called greeting2sh and enter the text in the screenshot below into. “erecting Fle Edt View Seurch Tools Documents Hep pom xooHl|ag ects eyesnvach echo
/dev/nutt ) JU
32 cycle Let Lives=3 Repeat This prints the message whist waiting For the specific key to be pressed on the keyboard: the Spacebar. ‘Now you can nttaduce the game anette player Now we cn start theory part ofthe adventure SUES know how many lives they currently have. You can SERS as 110 Ui Bi sine the following tothe ds Print “You anake to find yourself in an airlock Printat (41,0); *You have "; Lives; “ lives left.” onboard a space station.” Printat (0,@); “Welcome to Cosmic Adventure!” Input “There are tno buttons in front of you: : sdepioy 6T2EN and Red. Which do you press?”, button$ Tepintacommanduilpecyalocenonthesccenocinly Tr ueeongamned™ then fusing Let Lives=Lives-1 Print “You just opened the airlock into space. You ‘are dead!” Print “You now have “;tives; “ lives left.”Coding with FUZE BASIC — Part 2 SET con now continue the game from tine 28, adding another press the Spacebar routine followed by a clear screen ready for the next part of the adventure. PEED Now add If Lives then goto 25 Print “Press the Spacebar to try again.” While inkey <> 32 cycle Print “Press the Spacebar to continue.” Repeat While inkey © 32 cycle Goto 8 Repeat Else as Print “The door to the interior of the space station opens, lucky for you,” 1 Goto command goes toa line number and continues with code, Here you can use ito start an end of game routine. Bee You con now Save the code, calit Adventure (or thing), and Run it From the menu, Whilst i's not iebringsin many different one with FUZE BASIC. the most elegant code you will ever elements and shows you what can be ese Endif Endif Goto 29 Print “Sorry, you are dead. End of game. Press Spacebar to start again.” While inkey <> 32 cycle Repeat Goto 1 This closes the Ifstatements, then goes to line 29 (f you pre Green button) to continue the ga ing the end oF game routine. ~ : ods a Before you continue with the adventure, and map_ BRD orvezswesatheendofaamerouiness — EMME rece ourveuctanespace er, were going ated line is only works the to improve our code with some graphics. FUZE BASIC has some BOM Definitve Guide Series |voiwmesProgramming with the FUZE Coding with FUZE BASIC — Part 3 The last tutorial had you creating the Foundations for a text-based adventure game. While it works perfectly Fine, it would be nice to include some graphics and maybe a Few other elements to have it stand out from the usual BASIC programs. ADDING GRAPHICS FUZE BASIC employs a variety of different commands to display graphics, either drawn on the screen or by displaying an image file You're going to stat by making the game fll Now ceatea new ine 13, by geting the crsorto SuzP il screen, then adding an appropriate image that sets sungP the end of line 12 and pressing Enter, For the new thetene thease rome Zoereneroceaiearow he ope ine ond pene elon aaa EUuscretiS This command will remove the image from the screen, allowing you Sort tstecenesorteC1) Doreinearewmogeterteesepntesane Earth$="planetEarth.png” Loadsprite (earth$, spriteindex, 0) need ta source your awn images for your game. In our example, we found an image of red and areen buttons and copied to the /Desktop/fuze basilextras/ images Folder, Now we need to add it te our code From line 15: buttons$="buttons. png” see eeeeee seseeeeee ssseesee LOadspritte Cbuttonss, ‘spriteindexy/0) FERED the code from step twillimport and displayan _-—-~PROESPIrLReCspniteindexs"300;°400,°0) image ofthe Earth; the image keels already Make sue the image called before the Input command! available inthe /Desktop/Fuze-basicextras/images olde.’ now classed as a sprite and can be manipulated through the vaious graphical commands of FUZE BASIC. Any uniqueimages yo include shoul be copied to this folder to add to your gam PEM continuing, cof the interior ofthe ISsiFthe Green| sed. Download the image, put tin the images folder, name ti$S.png and cat Fram the code whist hidesprite hides the previous image. Hidesprite (spriteindex) Usdate Print “The door to space station opens.” ISSS="ISS.png” Loadsprite CISSS, spriteindex, 0) Plotsprite (spriteindex, 200, 200, 0)Coding with FUZE BASIC - Part 3 eis getting quite hefty. Don't FETED Natural you can continue with Cosmic Adventure ew line you're entering, the ourself, adding choices, graphics and keeping tabs es original Goto values willbe different.’ best to return tothe cade on the number oflives and whatever else you can think of. As we and update the lines where Goto is referenced said, isnot the most elegant cade and it’s asfar From atriple-A game as you can imagine; but at least it's given you ahead sta wih FUZE Basic an add animage forthe End of ert the code te (spriteinderd cas ee beste ; Pra Pas Here's a recap of the images we've used for the bey emma) SDS iicci cur adve e. The FUZE BASIC repeat manual comes with countless mare commands to idesprite use of the system, so.read through it and expand on what you've goto 1 BED ‘ance more, the code has now expanded and 3s such you need to ensure that any reference to another line is updated to reflect the new numbering; especialy inest24 and BB, which call either End of Game routine or continue the game ifthe Green Button has been pressed ae GAHE OVERProgramming with the FUZE Using a Breadboard Agreat way to learn circuits is to use a breadboard, You can use a breadboard with FUZE BASIC, or Scratch and Python, to control LEDs and other simple circuits. Here we'll show you how a breadboard works. GPIO ‘The Raspberty Pi enables you to access electronic pins, known as GPIO (General Purpose Input and Output). These are used to interact with external electronics like LED lights and switches. Below you'l learn to build circuits using a Breadboard. 1 ral: red is For Follow along with this tutorial by getting a breadboard, 1xblue and provide any power themselves; instead they just connect to each 1 xred breadboard wires, aSmmLED, a220hms 5% resistor, 9V_other.So i you plug an item into-one hole, and ancther item into battery, and a SV snap battery clip. Your loca electranies shop will a connected hole (along the line), then the two are connected asf help you out you'd physically joined the two things together PPR Cet cctne veadoard hold kup veal and Thetwo cumnsof ols onthe ouside are columns. The two pairs on the le and right, oth have ared and to the bottom. Take a9V battery and attach a snap battery clip. blue line eunning vertically alongside them. inthe middle are vertical Connect the positive wire (red tothe topmost red hole onthe left columns with letters and numbers. There are typically twomain _itwill provide positive power to any wire or component connected columns, lettered AE and FJ in any red hole al the w (negative) wire to the BED 22%" 02 crise series votre 3 y down to the bottom. Ad the blue ost blue hole on the right.BED RECREATING THIS IN A BREADBOARD Using a Breadboard Get the LED and look tit closely. Notice how one legis onger than the other. That's the positive wire the shorter one is negative. Take a resistor and wrap one end of ‘around the shorter wire on the LEO. Take the positive wire from the PP3 battery clip and touch the LE; touch the negative wire to the resistor and see the LEO light up. We've numbered these 1, 2 and 3 so you can match them in the next steps, Wrapping wires and circuits around each other isn’t going to be much Fun, especially when you're trying to Figure out how something works. That's what a breadboard is for: the holes enable you to connect one item to another. Let’s now recreate this simple LED circuit ona breadboard, with the positive and negative cables from the battery connected to the top ofthe power rails, take @red connector and slot one end into @ hole on the red line, and the other ED ths the part ‘where most people mess Up, Take the other leg endinto hole At of the LED and connect iktohole D2, Thsis the next row down. Fyou connected itto anath hole online 1, such 351, itwould be the equivalent of touching both LED legs together. Now take your resistor and place tnext to the LED leq in slot £2 (also on the second line). IFyou look at the photo from Step 6, this sthe equivalent of 2 (the part where the LED and resistor are connected. Insert the other end of the resstorin ahole on the negative power rail and your LEO wl ight up. sTep2 BQ take the LED, find the long end and slot this into hole Thisis the equivalent of umber 1 in our physical connection. The red cable isconnected vertically along the powerline, and then to raw 1a” the pe. breadboard where itis connected horizontally to the LED on row 1 80M Deintve Gude Series \Voisme 31 ETProgramming wth the FUZE Using the FUZE lO Board So far our breadboard hasn't been connected to the FUZE or Raspberry Pi in any way, Peericriacarne mica eiencmatiald rec ehick alts DNS T< eke od eae GPIO PINS ‘Te Raspberry P's GPO pins act as physical interface between the Raspberry Pand electronic items. On the FUZE these are {ately connected to the 10 board and can then be connected to your breedboard. FR eve ater and batey dp itis Suconected toe beocburd sd sie te JO bow d Lethe dose okat what te 10boardhas ofr The pins rmatked 0" and numbered 1-7 are more interesting, These can be turned on or off from inside programs, orat the command line, when turned on they provide 3.3V, and when off they provide nothing. These On/OFF switches can beused to activate and deactivate components youattach tothe Raspberry Pi Bee GND inthe Supply section on the top right of the IOboard, Connect the other end to the leftmost hoe inthe blue ra now running along the top ofthe breadboard. Connect ared ableto the socket marked 33V onthe supoly section in Iryou ook closely athe 0 boarayoul see section SIE of pins marked “RPI Header”. These match the pins that are onyourRspbery PL Ontherigtsie ofthe board are 2 number of output sockets The PL 3nd (23Vor SOV ae marked the bottom right of the 10 board. Connect the other end of the cable to Frsthole inthe red rail running along the bottom of the breadboard, The LED will come on,ue different to what we had befor, so let's spice things up, Remove the Fed cable fram che 3.3 10 socket and connect ittothe socket marked Dunderneath GPIO. The LED will turn off, This is because this socket wor provide any power until wetell itt, GETTING INPUT Using the FUZE IO Board PRTESTMD tor: FU2€ BASIC and enter: PinMode (@, 1) Digitalurite (@, 1) The LED tus on. The first part, PiaMode, tells the Raspberry Pi that PIO Vis going tobe used, and the 1 part saysit wil be output, The Digitalvrite command sets GPIO 0 on. Enter Digitalvrite (0,0) to turn the LED off We're now really steaming along. Our Raspberry Pi-powered FUZE is turning on LED lights in the outside world. Next we need to look at input; how we can get information from our breadboard to our Raspberry Pi PEED emove the LED and resistor From the breadboa and remove the GPIO 0 and GND cables. Place the Push button switch in the same place as the LED (B1 and D2) and place the blue cable in the hole next to it (E2). Take a look at the phota iFyou need help placing the itemsinthe right holes, ake the blue cable in E2 and connect the sTeP2 JM ue cab ‘other end to GPIO 0. Finally, connect the red cable from the irsthole inthe power railto 33V. Our circuits cr Current will go from the 3.3V co the power rali,and From the por rail to our switch. nnected ta our blue cable, whi connects to GPIO. PRED 105552 to open the Program Editor. Enter the following program: PinMode (0, 0) Until DigitalRead(o) Cycle Repeat Print “Button Pushed” Press FB to run the program, Here's what happens, Power is Flowing fi 3.3V socket to the switch where it is waiting until nput comes through on O (via DgitalRead), we push the button a connection is made, power flaws to GPIO G and it alerts the program. Itthen prints the message “Button Pushed DM's Deine Guide Series | Volume 3Programming with the FUZE Using a Robot Arm with FUZE BASIC As part of the educational kit, the FUZE Workstation can be purchased with an accompanying robot arm. This is a 149 piece kit-form robotic arm, that requires assembly and is powered by four D-type batteries. It’s connected to the RPi or FUZE via a USB cable and is also Windows compatible. |, ROBOT We won't go into the construction of the robot arm here, the instructions which come with the arm are easy to follow and it can be completed and ready For use within a couple of hours or so. Let's look at how to get it working, ERD) tiesctotemisoreottheristetenathacnae ERED robesn remands make th let's look ata Few ‘ArmBody (1) This starts the arm rotating clockwise (looking down oni) ts this quickly enter start by pl the spare USB ports on the ArmBody (0) tthe arm This willstop the arm from moving. in the Immediate MoFETED Now enter: Amniody (=1) This will start moving the arm anti-clockwise ‘ArmBody (0) ain, when it starts to Tostop it rom moving. to make the arm move are: FPP M the ochercomma ArmShoulder (x) = where x can be 1, -1 or @ ‘ArmELbow (x) - where x can be 1, -1 or Arnitrist Gx) ~ where x can be 1, -1 or @ ‘ArmGripper (x) = where x can bel =1, or @ ArmLight Cx = where x can be 1 or @ Note: you can press the up arrow key to re-enter the previously typed commands, so you can quickly stop when iteachesits it arm's movernent Let's create a program allowing you to around freely. There are some PROC and DEF PROC, that enables BASIC to jump to a PROCedure, another part ofthe program, then back with ENDPROC. FONTSCALE determines the size ofthe on-screen print display and HVTAB isan X and coordinate system to print onscreen. Using a Robot Arm with FUZE BASIC Bee 10552, anc type inthe Following PROC ResetArm PROC Disployinstructions End DEF PROC ResetArm AemBody C8) ‘AemShoulder (8) AemEUbow C0) Aenwirist (0) ArmGripper (0) Armbight (@) ENDPROC DEF PROC Displayinstructions cus FONTSCALE (2,2) Ink = Red Print “I, Robot” Ink = White HVTAB (0,2) This is the start of the program, resetting the arm and preparing the onscreen display, Print Print “1 or Print “3 or Print “5 or expand the program to control the arm: Print “Press:” 2 for Body Left & Right” 4 for Shoulder Up & Down” 6 for Elbow Up & Down” Print “7 or 8 for Wrist Up & Down” Print “9 or 0 for Gripper Open & Close” Print “Enter to turn the Light On on OFF” Ink = Red Print “Spacebar to stop all movement and turn off the Light.” ENDPROC Now we need to process the user input. There's alot here but type the content as shown in the Save the code and Ru; you can now control the atm using the number keys 1 to., the Enter key for the light and Spacebar toreset everything. DM's Definitive Guide Series | volumeProgramming with the FUZE FUZE BASIC Examples — Part 1 FUZE BASIC has an impressive following of coding experts and enthusiasts who have selflessly provided their code for others to learn from and use. These stalwarts of FUZE BASIC have forged some amazingly detailed examples, which we'll take a look at over the coming pages. CODE REPOSITORY From fractal generators to encryption programs and animation, here are ten excellent examples of what others have done with a little patience and a lot of code. inca cionencwne, SSRIS ce onan ‘and make it atta prsingly right to let, Put your image et o.uk/code-repository ust enter the inthe /ex oF simply in the same Folder asthe code itself. Save and Run and enjoy the image moving across the sereen, See if you can modifyitto Fullscreen, or more BSS TeD '2the Program Editor click the Load button and owse through the rz ~ * until you ind Shooterfuze. With the isting loa PITTS Sivon Plouffeisa mathematician who, back downto ine 247 and changetthe“player2.png" entry to "Player ding a capital PT cling shooter and image: st fied an error inthe co on mathematica ng acirle aced px enter this and be amazed:(_ FUZE BASIC Examples — Part 1 TIS METER u22Fiahter, also found in the Games Folder, anoth ‘of what be done with FUZE BASIC sound effects, animations, colsion detection, scoring and a lement that can be worked into your own routines. RR 0087 2%: 2 func con RSM Rov ere nah detection, scoring pcogram that you entered its benefit le Future pro s and make ita more flexible [excuse the pu) program. Score 228 L Enersy 534 nally, snake fi ‘ombi MSANED rr sstcames openthe of programming elements. raph, ze and have alook through the 784|ines of code before scoring, collision detection and button. Its quite complex but wh ng routines to help urn it you e Found within this code all program car ending 3 publcatonscom eeProgramming with the FUZE FUZE BASIC Examples — Part 2 Cees TUR icon Malka ere. Ete eel eC em can be done with FUZE BASIC. Take what you want from the code, alter it and insert it into your own routines to Fine-tune your program. CODE STRIPPING Many of the legendary programmers from the golden era of home computing stripped the code from snippets posted in the magazines of the time. They bent the code to their will and created something as close to magic as possible. Amiga owness wha fond memories LARA Fic fturstic computer bckin the late '80s and early '90s. The Amiga was a pretty impressive home computer, even by today's standards and its iconic Bouncing Ball routine will forever be remembered by those who grew up with tone. Load up aball fuze from Demos and see what you can use. PRY elcltakele ae ist an anclogue clock on the screen, complete with second hand, may not sound too interesting, there's a surprising amount of useful code within this particular routine. Clock fuze isin the Demos folder and once laaded up you can strip ali manner of handy code snippets From it BLED 20s vetintve Gude Series | votre 21 PEN CUR UTED. Scenkerboardfuze isan extremely handy bit of code to load up, I's a simple program that will display the key pressed on the keyboard ‘which is @ great resource when it comes to creating keyboard interactions withthe user and the program, such as a game, Just take the key codes you need and insert them in your own programs. PRT er eRe ED TS code snippet wil look For and detect any attached BBC microsbit or ‘Arduino compatible devices that you ve attached to the FUZE 10 or Raspberry Pi GPIO pins. I's incredibly handy for helping you create the code behind your hardware projectPRD thislctesnippet of cade, although simple, wil display some of the avallable Font sizes of FUZE BASIC ne maximum size is 20,50 alter as, you wish as FOR size = 1 10 7 LOOP INK = RNDC3@) FONTSIZEC size ) PRINT “Hello” REPEAT END Pee (®:0u'e working with a Raspberry SenseHaT, then the following code wil return the current value ofthe HAT's accelerometer: cus Loop PRINT “Sense Accelerometer X=”; SENSEACCELX PRINT “Sense Accelerometer Y="; SENSEACCELY PRINT “Sense Accelerometer Z="; SENSEACCELZ REPEAT END PTS CGR) 72 this code will return the value oF the SenseHAT's compass: aus Loop PRINT “Sense Compass X="; SENSECOMPASSX PRINT “Sense Compass Y=”; SENSECOMPASSY PRINT “Sense Compass Z="; SENSECOMPASSZ REPEAT END (_ FUZE BASIC Examples ~Part 2 ISSA (vou waneto incorporate mouse pointer and button use in your code, then this will certainly help you out. e's afirly simple bt of code but remarkably effective andit can easllybe inserced into your ‘own programs, BE Sermouse Cewrorn 2, cncxorr / 2) 32 tocrnouse rat se) teal TROLLED cluding the use of a gamepad ‘or jaystick in your games or code sa great addition to also being able to redefine the keyboard, This code will detect and display the states ofeach ofthe axis ‘and buttons, PCG eGR ial i 0u'e aftersomethinga ltele competitive wth your Family, then load up reaction fuze from the Dems folder. When run, thiscade val test your reaction time by hitting the Spacebar when indicated, See how fast you can gett, and see iFyou can hack the code 20M Definitive Gude Series Volume 3Coding with Windows 10 Batch Files Did you know that Windows has its ‘own built-in scripting language? Batch files have been around since the early days of Windows and while they are overshadowed by the might of the modern Windows graphical user interface, they are still there and still just as capable as they were thirty years ago. Batch file programming is a skill that system administrators still use, so it's worth spending a bit of time learning how they work and what you can do with them. This section introduces batch files and covers user interactions, variables, loops and even a batch file quiz game to inject an element of fun. 106 Whatisa® ch File? 108 Getting Started with Batch Files 110 Getting an Output 112 Playing with Variables 114 Batch File Programming 116 Loops and Repetition 118 Creating a Batch File GameCoding with Wind 10 Batch FilesCoding with Windows 10 Batch Files) What is a Batch File? The Windows batch file has been around since the early days of DOS, and was once a critical element of actually being able to boot into a working system. There’s a lot you can do with a batch file but let’s just take a moment to see what one is. .BAT MAN ‘AWindows batch file is simply a script file that runs a series of commands, one line at a time, much in the same Fashion as a Linux script. The series of commands are executed by the command line interpreter and stored in a plain text file with the BAT extension; this signifies to Windows that it's an executable file, in this case, a script. Batch Files have been around since the earliest versions of Microsoft DOS. Although not exclusively a Microsoft scripting fil, batch Files are mainly associated with Microsoft’ operating systems. In the early days, when a PC booted into a version af 00S (whieh produced a simple command prompt when powered up), the batch ile was, Used in the Form of a system file called Autoexecbat, Autoexec bat was a script that automatically executed thence Autoexed) commands once the operating system had finished dealing with the Config.sys le When a user powered up their DOS-based computer, and once the BIOS had Finished checking the system memory andso.on, DOS would look to the Config sys file to load any specific display requirements and hardware drivers, allocate them a lotin the avaliable memory, assign any memory managers and tellthe system where the Command.com file, which isthe command tine interpreter for DOS, was. Once it had done that, then the Autoexec. bat file took over and ran through each lin in turn loading programs that would activate the mouse or optical drive into the memory areas assigned by the Config.sys le The DOS user ofthe day could opt to create diferent Autoexec bat files depending on what they wanted to do, For example, iF they wanted to play a game and have as much memory avalable as possible, they'd create a Config sys and Autoexec bat set of files that loaded the bare minimum of drivers and so on. I they needed _elp | ‘The Autoexec.bat file was a PC user's First experience with a batch ile, tose ie Sers oeBatch ilesare plain text and often created using Notepad tae | = fe i Batch files were often used as utility programs, to help users with complex tasks. access to the network, an Autoexec bat fle could be created to load the netwark card driver and automatically gain access to the network. Each ofthese unique setups would be loaded on to a Floppy diskand booted as and when required by the use The Autoexec.bat was their PC-based computing lives; since many had come from a 16-i cr even é-bie background; remember, this was the late eighties and early nineties. The batch file was the user's primary tool Fer automating tasks, reating shortcuts and adventure games and J frst such file many users came across in translating complex pracesses into something Far simpler Nowadays however, a batch file isnt just for loading in divers and such when the PC baots. You can use a batch file in the same w asany other serioting language file in that you can program it to ask or user input and dsplay the results on the screen; or save to afile and even sendit ta a locally or network attached printer, You te scripts to back up your files to variou mpare date stamps and only back up the most recently chan nbas well as program the script to do allthis automatically. Batch files are remarkably powerful and despite them not being as commonly used asthey were curing the older days of DOS, they are still there and can be utilised even in the latest version of windows 10; and can be a5 complex or simple as you want them tobe. So what do you need to start batch file programming in Windows? ell long as youhave dows For that matter, you can start batch file programming immediately allyou need isto be able to open Notepad and get to Nindows 10, or any older version oF the command prompt of windows. We show you how i all works, read or reieoublications.com What is a Batch File? BATCH FILE POWER Just tke any other programming interface that can directly interrogate and manipulate the system, batch filesrequire a certain amount of care when programming. It’s hardto ‘damage your system wit a batch file, the mare important elements of the modern Windows system are protected by the User Account Control (UAQ security, UAC works by only allowing elevated privileges access to important system fi Therefore iFyou create a batch Fle that somehow deletes 2 system file, the UAC activates and stop the process. However, iFyou're warking in the command promt with elevated privileges to bein with, as the Administrator, then the UAC won't question the batch file and continue regardless of what files are being deleted That said, you're not likely to create a batch file that Intentionally wipes out your operating system. There are system controls in place to help prevent that; butts worth ‘mentioning as there are batch files available onthe Internet that contain malicious code designed to create problems. ‘Much ikea virus, arogue batch file (when executed wth Administrator privileges) can cause much mayhem and system damage. in short, don't randomly execute any batch fle downloaded from the Internet as an Administrator, without First reviewing whet it does. You can learn more about batch file in the coming pages, so don't worry too much about destroying your system with one. Allthisjust demonstrates how powerful the humble batch file canbe. ‘You can create complex batch files or simple ones that display ‘ASCIIimages on screen. DM's Definitive Guide Series | volumeGetting Started with Batch Files Before you begin to program with batch files, there are a few things you need to Lo PMY] nN il e=IRoNLRoo el eo ec Ae merece kel ea eon with Notepad isn’t always straightforward. ANEW BATCH Throughout this section on batch fil called ‘Batch Files’. To begin with, le going to be working with Notepad, the command prompt and within a folder 1e how you get to the Windows command prompt. ne Windows while atthe command prompt window, ete LED > 8 | RED corr sts at eres ana decors on promot may ook ait = atthe marentin the stem nths cae, that's your but it's simply another = interface (or Shell used to “ by using the ¢ accessthe fil cd. Documents can go anywhere you tke in Then press Return. the command prompt, as ith the gr Tobeain, click ows Start button and the Konthesechektontedcermandrone EEEEM the rove shod hang an diay sktop App) and a 20pS UP. The seks DoCURERESS§ this means you're in the Documents ry call Batch Files, Enter: The prompt details the er with y me, cd Batch Files fou won't need the quotes to change di(. Getting Started with Batch Files Bee Now that you have the directory set up, where you Back atthe command prompt window, entes store your batch files, heres how youcan create ‘n/n again to list the newly created Test bat ile. ‘one. Leave the command prompt window apen and click onthe ay, the Aw part oF drfw means the files are ited ‘Windows Start button again, This time enter Notepad and lickon the screen as opposed to straight down. Enter dif if you the search result to open the Notegad program. Notepadisasimple (although you need more Files to view) but it's considered text editor but ideal for creating batch scripts with, read with the fw flag, o execute the| To create your fs bath fle, enter the Flowing ch fle youve ist eated, simply SUES into Notepad: 1g enter its name, Test, in the command prompt. that command co itself. FETED hen saving anything in Notepad the defaul .. soe soe avecsesie> extension ist, to denote a text file. However, you t mmand displays whatever is after want-the extension to be .bat. Click on File » Save As and navigate MED 1°60 command cistlays whatever's after it tothe nent crested Each ies GretorynGocumentsClekthe amine, "OUTER, Right he Test fl rom drop-down menu Save as Type, and select All Files from the menu. in niin aaa ammaeiaiaaaaaaaaiinaa File Name, call the file Test.b youlixe Try this @echo of echo Hello World! = echo This is my first batch fle echo. echo With @ blank Line between! Remember to save each new change tothe batch file.Coding with Windows 10 Batch Files ) Getting an Output Mer ee eae Gr Oren aU oa IS VATA CONa Tt Cen Te after the echo command in the batch File, it’s not very useful at the moment, or er mC acm ete circle a INPUT OUTPUT Batch files are capable of taking a normal Windows command and executing them, while also adding extra options and Flags in tothe equation. diorencer\euooamensaecnriestss PA aes GNSERIRUME cre c:\users\YOURNAME\dirview. txt: - Sane click the @ilpviveWs#3t file, you can see the batch file's output Substitute YOURNAME with your Windows usemame. directory, dumping the output to atext file called GURVIGMEERE nine tothe batch file: sae ee NS eatepas ee cers OURUNE Se sonst it iOUTPUT WITH VARIABLES Variables offer a more interesting way of outputting something to the screen and create a higher level of interaction between the user and the batch file. Try this example below. Create anew bath fe and clit namebat. star SHEP) with the @GHONOFFl|command, then add the Following lines set /p nane= What is your nane? echo Hello, name Note: there's @ space after the question mark. This is to make it look neater on the screen, Save itand run the batch lle The set fp name creates a variable called name, with ESD the /p part indicating that an ‘=prompt string’ isto Follow. The Set command displays, sets or emoves system and environmental variables. For example, while in the command prompt win enter: set To view the current system variables. Note the name: just created. FETISED Verisbles stored with Set can be called with the 6VARIABLENAME% syntax. Inthe batch Fe, we used the newiy created Séname% syntax to call upon the contents of the variable called name. Your username, For example, is stored as a variable. Try thisina batch fle: echo Hello, NUSERNAMEX. What are you doing? This is extremely useFulif you want to create a Unique, personal batch File that automatically runs ‘when auser logs into windows, Using the default systems variables that Windows itselF creates, you can make a batch File that greets each user eecho off echo Hello, USERNAMEN: echo. echo Thanks for logging in. Currently the network is operating at 100%% efficiency. echo. echo Your Hone directory is located at: SHOMEPATHS: echo The computer nome you’re Logged in to is: ‘SCOMPUTERNAMES echo. usr ‘overwrite and still use name.bat if you want. The batch letakesthe curent system arabes and reporsthem according, depending onthe ise’ on name and the name of the computer. Note: the double percent symbol means the percent sign will be displayed, and isnot a variable. SEER) *:ematively, you can un the batch file and display ion the user's desktop as text file: @echo off echo Hello, USERNAMES, > c:HOMEPATHR\USer. txt echo. >> c:NHOMEPATHW\user.txt echo Thanks for logging in. Currently the network is operating at 100% efficiency. >> ¢:XHOMEPATHR\ uservtxt echo. >> c:XHOMEPATH\User.txt echo Your Home directory is located at: SHOMEPATHX >>. C:RHOMEPATHE®\user. txt echo The computer nane youre logged in to is: [XCOMPUTERNAMER >> c:5HOMEPATH®\user txt echo. >> ¢:XHOMEPATI\User.txt notepad c:KHOMEPATHR\user txt The>outputsto a new File called user.txt, while the >> addsthe lines within the File ADM Defntve Guide Series |vouwmes’ QECoding wth Windows 10 Bath les Playing with Variables Pees ten ren a lie Ce CR renune Aen Fou Stemi teuncueT cutieh oicrsurateait Pecan en Meuron ech Tree m cue Mae acea tte Une s USING MORE VARIABLES Here's a good example of mixing system and environmental variables with some of your own creation, along with a number of external Windows commands. FETTER reate anew batch ile called st bat and start itoff REDD "ou, create a batch ile that displays the contents, with the @eCholOF command, Begin by clearing of any directory and post it. as atext file to the user's the command prompt screen and deplaying a Ist ofthe current screen. Add the following to thelist. bat batch file: directories on the computer: ermemeremecnnees as echo From the List, which folder would you like to din “c:\" > List.txt view? type List.txt set /p vien= Center as c:\folder) echo. dir “views” > view. txt notepad.exe view.txt Save and execute the batch file Within the What's happening here isthe batch file asks the user SMD cornnand vont sou can se the contents Fal ED 3 ier aro the dicectovesdeplyedinthe st the files and directories from the root of the C:\drive; and asany —__generated, in the form of '‘e\directory. Providing the user enters a User under Windows has permission to see ths there's no UAC valid directory, ts contents are dsplayed asa text fle, We created elevated privileges required, the view variable here along with %SHOMEPATH%, ta store the input and the text file BRED 20% vetintive Gude Series | vole 21Playing with Variables BSED {always a good idea, when creating text files PPI ios:2a4 of lefeclicking on the Command Promat For the user to temporarily view, to clean up after result, as you dd the fist time you opened it yourself. There's nothing worse than having countless, random Fight-clickitand from the menu choose Run as Administrator. There text Fes cluttering up the file system, That being the case, lt’s Isa rsk that you could damage system files asthe Administrator dear up with butas long as you're careful and don't do anything beyond viewing airectaries, you wil be okay. as del /Q view.txt del /Q List. txt echo ALL files deleted. System clean. ao @ Filters est match fH Command Prompt © Ran as administrator se DI Open file location A and delete both the view txt and lst. files that were created by the batch File, The /Q flag in the del command meansit deletes the les without anyuse input orntifctin, The Final message ; Inftormsthe ve tat the les are removed TEED ise 80n Vignes the UAC warning message asking you if yout sure youwant to run the ‘Windows commend prompt withthe elevated Administrator privleges, Most ofthe time we would recommend th course of scion: the UAC is there to protect your system. Inthis ase however, clk Yes eens oe your systemis configured, © sre ete you may not get any pare directory information ee Crete atallora message ee stating Access Denied, serene . This is because the UAC 2 ont PTTSET BD withthe UAC active, the command prompt looks locking access to alittle different. For starters, t's now defaulting protected areas of the tothe CAWINDOWS\system32 folder and the top of the windows is system, like cAWindows, labelled Administrator. Tarun the batch fle, you need to navigate ta or C:\Program Files. the Batch Files directory with: ed \Users\USERNAME\Documents\, Bateh Files. To help, pr he Tab key to auto-complete the run the bateh fle as an directory nares. ‘Administrator, Click the Windows Start button and enter CMD again ADM Definitive Gude Series |vclume 31 EEFCoding with Windows 10 Batch Files Batch File Programming Teac Me rene eee ican seas tt eh luricy PUAN Oe Ie ute mcuceee ener tcmmentl Teese umn aetna SEARCHING FOR FILES Here's an interesting little batch file that you can easily extend for your own use. It asks the user For a file type to search For and displays the results. BEER 2 2°e introducing a couple of new commands PETE DD ow lot's extend the seek bat batch fle: into the mix here but we think they/re really useful Create a new batch fle called seek bat andin itput eecho off Gecho of F _ = als color 2 echo Please enter the type of file you want to echo Please enter the type of file you want to | reel search for (MP3, DOC, JPG for exomple) echo * text > found.txt a notepad.exe found.txt ee fone Se as no color Ee del /Q found: txt ESTEE the new command inthis instance is color PATER 2rother new command, where, looks fora specific (Americanised speling). Color, as you already file or directory based on the user's requirements. assume, changes the colour of the command promptdisplay. The__Inthis case, we have created a blank variable called ext thatthe user color attributes are specified by two hex dis, the frst corresponds can enter the file type in, which then searches using Where and tothe background colour of the Command console and the second dumasthe results in atext file called found.txt, Save and run the tothe Foreground, and can be any ofthe following values: batch file O=Black 8=Grey 1=Blue 9=Light Blue 2=Green A=Light Green 3=Aqua B= Light Aqua 4=Red = Light Red S=Purple D = Light Purple 6=Yellow E-= Light Yellow 7=White F= Bright White ERED 20s vetintve Guide Series | votre 21CHOICE MENUS (- Batch File Programming Creating a menu of choices isa classic batch file use and a good example to help expand your batch file programming skills. Here's some code to help you understand how it all works. Rather than using a variable to process a user's response, batch files can instead use the Choice command in conjunction with an Errortevel parameter to make 3 menu, Create a new File called menubat and enter the following: @echo off as choice 7M “Do you want to continue?” Y/N” if errorlevel 2 goto N if errorlevel 1 goto ¥ goto End: Runing the code produces an ero a, Ba % “i a Goto command without any reference toi in the the batch File. Finish the File wth the following and unit again: vecalled file, Goto does exactly that, goes to a specclinein echo You chose No. Goodbye. goto End Y echo. fecha You chose Yes. Hello sEnd BEER 1 cutput from your choiceisuifferent depending on whether you pick oF N, The:nd part simply signifies the end ofthe Fle (also known as EOF) Without tthe batch file runs through each line and csplaythe ¥ response even you enter N;so it's important to remember to fallow your Cato command ErrorLevels are essentially variables and the /Mt switch of Choice allows a descriptive message string tend this menu with something new tobe displayed. echo off als echo. echo. echo. echo Please choose a directory. echo. echo Press 1 for c:\Music echo. echo Press 2 for c:\Documents echo. echo Press 3 for c:\Pictures echo. echo Press 4 for c:\videos echo. echo) choice / 1234 if errorlevel 4 goto Videos if errorlevel 3 goto Pictures if errorlevel 2 goto Documents if errorlevel 1 goto Music PETTIM) (Now add the Goto sections: Videos cls CD SHOMEPATIVideos echo You are now in the Videos directory. ‘goto End Pictures cls (D sHOMEPATHE\Pictures echo You are now in the Pictures directory. goto End Documents as (CD %HOMEPATHEADocUnents echo You are now in the Documents directory. goto End iMusic cls (CD SHOMEPATHRAMUsic echo you are now in the Music directory. goto End End ESSER When exccuted the batch fle dsplaysa menu andwith each choice the code changesdlrectaryto the one the User entered, The %2HOMEPATHYS system variable will enter the currently logged in wsers Music Pictures andso directories and notanyoneeles (DM's Definitive Gude Series Volume 3Loops and Repetition Re Ease orae serach ea Ng ele} PMc cic Keren R sk utecce ec etn Orman aan een sect an osc COUNTERS Creating code that counts in increasing or decreasing number sets is great For demonstrating loops. With that in mind, let's look at the if statement alittle more, alongside more variables, and introduce the Else, Timeout and eof (End of File) commands. BALE ein folowing set and Ra echo ore Trytnsevampleinsead as @echo off set /a counter= for /L 380 in (1,1,99) do echo %in shunbers set /a counter=Rcounters+1 if ¥counters ==100 (goto :eof) else Cecho counters) timeout /T 1 /nobreak > nul goto inunbers he count bat isarough way of demonstrating a loop; a better approach would be to use aFor loop. ised pes os For, then the /L switch, handles a range of numbers, the parameter labelled as 23in to denote a number. Then the in (1.1.99) part, which tells the statement how toca asin 1 Gtart number), (steps totake), 99 (the end number) he next part is do, meaning DO mand is after sorts st numb nd ‘ling down the between numbers and the Else statement continues Uuntilthe counter variable equals 100 before going to the eof (End OF File), thus losing the loo} ERED 20s oetintive Guide eres | Volume 2You can include the pause between the numbers BED « easily enough within the adding multiple cormar Js after the Do For loop. The brack ampersand (8) separate the different commands, Try ths @echo off for /L 3% in (11,99) do Cecho skin & timeout /T 1 Ynobreak > nul) (One ofthe greatttime saving uses of batch files is to Say nttwenty five text files within director 25./AFor loop much ike the previous example does the trick @echo off For /L 36i9 in (141,25) do copy nul XKin.txt create multiple, numbered files. Assume that you mt all numbered fi re vou open wind atch Files direc text files all neatly numbered. OF course, you thing lke user1.txt and soon by Fy where youre working From can append the file name wit altering the code @echo off for /L 9% in (141,25) do copy nul Userdskn. txt Sus this example, the code creates 26 directories, one For each letter of the alphabet, within the directory c\test which the h file makes using the MO command: here are diferent ways of using the For loop. In @echo off FOR XRF IN (a,b,c,d,e,f. SsE,U,YAM,XGY,2) DO (md C24 19sh,i,j.ks1.m,0,0,0,4,r, -eSt\RXF) Loops can be powerful and extremely useful elements ina batch Fle. While creating 26 directories may not sound too helpful imagine having to create 1,000 users on ¢ network and assign each one their own set oF Unique directories. This is where a batch file saves an immense amount oF time. BED errors aitina ch esse For example, foro? You get an onscreen hel le swt detailing the com For /? > forhelp.txt ta BOM's Deine Guide Series | Volume 3Coding with Windows 10 Batch Files Creating a Batch File Game Based on what we've looked at so Farwith batch files, you dan: Pe lt) Reel aR Ce Tel. 21) Evel Chs bcm dee Relea ella) freee Me eee ella created) thatiyou'Te Free tb Fiddle with and make your own, ‘Make up your own questions but how about also including an introductory or loading screen? Make your loading screen in a separate batch file and save it as screens bat (for example). Then, fromthemain game batch file, you can load itatthe beginning ofthe file with the call command followed by color to reset the ‘game's colours: CC oceoen: te ea DIGCLOCK.PY ‘This isa surprisingly handy little script and one that we've Used in the past instead of relying on a watch or even the clock in the system tray of the operating system, echo off cis start set /a scoren0 set /a question=0 cle set /p nane= What is your nane? cle echo. (echo. #A1E+OErewrsuciasonrensanesvasaventraneevntTneaves? ‘echo, ‘echo Welcome inane to the super-cool trivia game. echo, fecho Press 1 to get started echo. ‘echo Press 2 for instructions echo. fecho Press @ to quit echo, echo Wttttettiesnentenenttenstntensentnnstintnesentnsets cehoice /C 120 if errorlevel 3 goto :eof if errorlevel 2 goto Instructions Af errorlevel 1 goto Game uinatructions cls echo. ho stttaeesteseeisseneeanesstaseesenees ‘echo. fecho The instructions are simple, Anewer the questions correctly, echo, cho HAtinteneanenineeneennenntannaneannn pause cle goto mena Cane set /a quostion-iquestiont+] cle Af tquestiont ==5 (goto end) else (echo you are on question Squeaticnt) echo. fecho get ready for the question... echo. timeout /r 5 /nobreak > nul AE tquestiont ==5 (goto end) ele (goto tquestiont)a cle echo. acho, #eteenennensnestesnenesnennete echo. echo Your current score is #scoret che, Scho steeseneenanusuussenannennane echo. echo. echo Question tquastion®. sche. fecho Which of the following version of Windows is the best? echo. echo A. Windows 10 echo. echo B. Windows ME echo. echo C. Windows Vista echo. choice /e abe Af errorlevel 3 goto wrong Af errorlevel 2 goto wrong Af errorlevel 1 goto correct 2 cls echo. cho tetecetenananeetessnenneennate echo. echo Your current score is tscores echo. tcchg. wevecernsaraneetesenesnesnrets echo. echo. echo Question questions. echo. fecho Which of the following version of Windows is the most stable? echo. fecho A. Windows 10 echo. echo B. Windows 95 cho. fecho C. Windows ME echo. choice /¢ abe Af errorlevel 3 goto wrong Af errorlevel 2 goto wrong Af errorlevel 1 goto correct 3 els echo. Saha: weveesunsnrenn echo. echo Your current score is tacore? echo. echo. fecho Question tquestions, echo. fecho Which of the following Windows version is the latest? echo. echo A. Windows 10 echo. echo B. Windows 98 echo. swervoublicationscom Creating a Batch File Game echo C. Windows 7 echo. choice /c abe 4A€ errorlevel 3 gote wrong if errorlevel 2 goto wrong if errorlevel 1 goto correct Your current score is tscoret Question iqusstiont, fecho Which of the following Windows uses Directx 127 fecho A. Windows 10 echo. ‘echo 8. Windows 3.11 echo. fecho C. Windows xP echo. choice /¢ abo Af errorlevel 3 goto wrong Af errorlevel 2 goto wrong Af errorlevel 1 gote cormect song els echo tetesesneneensese echo. ‘echo WRONG!" echo. echo sstenteaesaetnte set /a scorentscoret-1 pause goto :gane correct, cls echo echo. ‘echo CORRECT. YIPEE! echo. Sea ENE sot /a score=tecoretti pause goto :game send cls echo #eteeeneesseueetssansenesnners echo, echo Well done, tnanet, you have answered all the questions ‘echo. fecho And your final score is... ‘echo tecoret echo. eahg eevareereneravererserserserevees! choice /M “play again? ¥/s" Af errorlevel 2 goto :eof Af errorlevel 1 goto start DM's Definitive Guide Series | Volume 3>) Programming with Scratch and Python ) Scratch is a Free programmi language and online community that’s targeted primarily at young people but also useful for older users too. It’s a visual language created by MIT (Massachusetts Institute of Technology) and designed to help teach the building blocks of programming. It's extremely versatile and as such can be used in conjunction with Python code to create interesting and useful programs. With the ing of Scratch and Python you can make games, system utilities and even control external sensors, robots and motors. 122. Getting Started with Scratch 124 Creating Scripts in Scratch 126 Interaction in Scratch 128 _Using Sprites in Scratch 130 _ Sensing and Broadcast 132 Objects and Local Variables 134 Global Variables and a Dice Game 136 Classes and Objects,>) Programming with Scratch and Python. ) Getting Started with Scratch INSTALLING SCRATCH Scratch can be run inside your web browser at scratch.mit.edu, You need to have Flash installed in your browser; if isn't already, it can be installed from get.adobe.com/flashplayer. Sign up for an account with Scratch so you can save your programs. Scratch runs from inside the web browser, Click Lets take a look at Scratch Cat. Use lckand drag Create to open anew document. The Scratch with the mouse to position him on the Stage. At interface opensin the web browser, clickthe maximise buttonon the top, just above Scripts, you'l see two icons for Growand Shrink. your browser so you have plenty oF space to view the window and Click one and click the catto resize hi, Sife-click on Scratch Cat allitscontents ‘and choose nfo to access rotation controls Click the blue back button to get back to the Sprites pane, anda Stage. On the Stage will be an orange cartoon cat, known tothe lef ofthe Sprites Pane. The Script Area switches to Backdrop as Scratch Cat". Thisis the default sprite that comes withallnew Library elsplaying the available backgrounds. Click Music and Dance Projects; you will also see smaller versions ofthe sprite above the and choose spotight-stage. Ck OK Script Area and in the Sprites Panel. scarp Lorry - Bom aes BED 22sec sees tresBRTeREERD The backaround appears on the Stage and ratch Catlooks alot happier. Let's create ascript that ‘moves him to the stage. Click Sprite in the Sprites Pane to select the cat and click the Scripts tab to return tothe Script Area, Now lick the blue Motion tab atthe top ofthe Block Palette. SAVING SCRATCH FILES. Getting Started with Scratch BEE 029 he turn [35] degrees block (with an anti
Save Now to save your project Enter STERI ‘name in the New Filename box; we called ours Sere /CS_On sage” As we mentioned inbath Fehon and Unites, simportantto ved any pedal characters and {oases nyout filenames Use underscores” sien, STEP 3. _ Lotsof example Scratch files can be found on the MIT website by clicking Explore. Here you can see _ahuge range of projects Bult by other users and youl also be: ‘able to share your own projects, Choose a project from Explore to ‘openit, STEP 2 Choose ile Go to My Stuffto exit the stage and View the saved file, Click the Scratch Cat. On_ Stage link to view your file, You can add Instructions, Notes and Credits here, and Tags. lick See inside to head back to viewing ‘your code again, ‘oucanron the project det inde the man STEP window by clicking the Green Flag icon. Click the Stir son Favourite or bookmske raed he es on {othe More mportanty, ck the Set nside ose the code Used create he poet Tis good wy fern ho Sean code beng ised DMs Defintive Gude Series |voiume ss GBCreating Scripts in Scratch VISUAL CODING ‘The scripts in Scratch are created by snapping together blocks. These blocks are similar to the code you Find in more complex. programming languages, such as Python, but much easier to understand. ick Create to start a new Scratch project and Click the Motion tab and drag the move’ [10] name it Dancing Cat. You're going te put your cat ssteps_ block and connect it beneath the when and some other characters on a dancefloor and get them to bust. flag clicked block. A quick word about that [10]. when you write some moves. lick Stage, then Music and Dance and choose party- a number or word inside those square brackets, that's the way oF room, Drag the Scratch Cat graphic around the Stage tofind a good saying you can choose a valve. I'sthe equivalent of avariable", starting positon, because it varies. Well tell you which number or selection we're using but you can use any you want. Play around, BSTISED Cickon Spritet inthe Sprites Panes and dick the ESTEEM isnot much ofa cisco, solet’s add some sound, Scripts tab above the Scripts area. Now click Events Click the sound tab and drag play drum [8] for in the Blocks Pane and crag the when flag clicked blockintothe [8.2] beats and connect itto the bottom ofthe stack of blocks. Scripts area, This block represents the start of your program. tells Click on the blocks and Scratch Cat will move and a sound will come Scratch to run through the blacks belawit when we click the Green from your speaker. Flag icon above the Stage window. BED 2s 2 sees tresDancing sa back and forth affair so let's get Scratch Cat moving back Drag ancther move [10] steps block tothe bottam ofthe stack: Now cick the 1 and change itt =10 (minus 10). Entering minus figures moves the cat backwards. Drag another play drum block tothe bottom of the script Pick 2 ciffecent drum sound, We chose 13, = = = EDITING SCRIPTS. a 4 * | (Creating Scripts in Scratch Scratch Cat only moves back and Forth once, which isn’t much ofa party. Click Control and drag the Forever blockto the Script Area. Carefully position beneath the when [flag] clicked block but above themove [1@] steps block. The script should nest within the two prongs of the forever block Click the Green Flag icon ta start the disco Click the red Stop icon toend the program. ke often nessa Nothing is set in stone, and you can move your blocks in and out of scripts and even have several scripts or parts of scripts in the Script Area. Scratch is far more forgiving than other programming languages for experimentation. STEP 1 ee pretnibad forme usekne forever block (01 # Forever loop in prosrammise. Programs are ‘Sipp6sed to run from star ta.a Finish. Even programs like Scratch have an end point when you quik the program, You want to replace Bhs orever block wikia repeat one, Cliche forever Blockin ‘your Script and drag it down to separate it From the other blocks. Mourns and oy drs Blockgavesti nested SIEp2 within the foreye- block though and you want {Skee the, Chek the topmost-ove Block and dag ot oF the ‘reves Ble snow gos waekig othe ore. blodks0 tragic tothe left ang backto the Blois st ogc ido Dol Nowraga repeat [10] block fromthe block ist STEP 3 emmRiren [oa click in the SEE Area, Now drag the top olay den blockoFthe stack inside the repeat [10] Block IF you'drag/the top block all the blocks undemeath move withit and the whole lt willbe nested ipsidethe repeat [10] stacks ‘tu can poslonthe tack myers onthe Siok STEP Area and even keep the unused blocks around, attouah wetninuies good pracieetoKeeponiy wise youare ising nthe Sab ren and remove ty unsed blocks Cite Green fag eon shove the Stage window fstes Sate 3 ng 2 short dance DMs Defintive Guide Series |voiume ss GEInteraction in Scratch INTERACTIVE CONTROL, ‘The only Control option we've really looked at so Faris the when [flag] clicked block, which starts the program. Once the program is running it does its thing, right up until it Finishes. You're going to use the other Control blocks to do something more interesting. FETED 220 the Dancing Cat program from previous BREED We're going tommake Scratch Cat jump up and down tutorials. Select Sprite’ and click on Events so you ‘when we press the space bar. lick Mation and drag cansee thewhen [fag] clicked script. Now cick Controlinthe change y by. [10] andclipittothewhen [space] key Block Palette and draq the when [space] key pressedblockto pressed block. What's wth the ‘y"?Thisis what's known as an empty part of the Script Are, 2 "coordinate + Bm You can drag and rearrange the block crits to any The postion of each sprite on the stage is shown part ofthe Script Area, We lke to have our when using two variables, xand y. These are referred [ag] Licked scriptsin the top left but it realy doesn't matter tos the "coordinates". The xs the sprites horizontal postion ‘here they re, I's also worth spotting that we now have more than on the stage whilst the y coordinate isthe vertical postion. Click tone script For Sprite; you can have multiple scripts for each spritein and drag the sprite around the Stage and you'll see the x and your program. numbers change. BED 802s tres‘The centre ofthe Stage is x0 andy: 0.As you move the sprite up and to the right the numbers increase and as you move it left and down they decrease (going intonegative rnumbers).Sa when we use the change y by [10] block t says, take the current value of y (the vertical position) and increase it by 10. That makes our catjump up, FIXING YOUR SCRIPT (interaction in Scratch tothe bottom ofthe when Espace] key pressed script. Now change [10] to [-10]. Cikthe Green Fiag and run the program. Now press the space bar and... oh no, nothing happens. We've just encountered ourfist “bug What goes up must come back down. So drag another change y by [10] block and attach it ‘We know that there's something wrong with our script and we want to see Scratch Cat jump when the space bar Is pressed. So let’ quickly squash this bug and see it working. STEP 1 _ Theproblem s that programs are superfast and highly visual prograrns ke Scratch can move in thé blink an eye and chat's what is happening here, F you tap the space bar repeatedly while the program fs running you'll see Seratch Cat flickering asitjumas up ang down, The chlenge that our motion controls move the SHER. ‘cat instantly from one place to another, so fast that sient Sometimes is sf, he orbs and forth dance, ‘but obviously we need to slow down the jump. Help is at hand. Glick the Motion ab to ve te Motan Bloc Dragaiwait [71 secs /block mom the Blocks Palette sndiseieleGideresth thechance [y] bby. 1O black, Now press the space bar on the keyboard to see ‘Scratch cat jump up, and then back down. Notice that you don't need to press the Green Flag icon to un the programy the Green Flag starts our other script, B.* STEP 3 We tink Scrteh Casta inthe 9X oolong STEPS ‘We want a jump, not a levitation effect. Change Hhewait (1) secsWanablete [0.25 | Fihisisa quarter of a second and will give us a more Fun hop. Press the Green Flag to. ‘Saree sip anata the spacebar whenever you wane Seraeh Cattojump, DMs Defintive Guide Series |voiumes GiUsing Sprites in Scratch LOOK SPRITE Sprites are 2D (flat) graphics drawn on top of a background. They are commonly used to display information in games such as health bars, scores or lives. Older games are composed entirely of sprites, just like our Scratch project. BSTEERID {re going to addanothersprite to our project and BREESE All the blocks on the Script Area have vanished. The ‘a second characterto the scene. Clik the Choose scripts we built for Scratch Cat relate to that objec, Sprite From Library button, just above the Sprites pane. This opens not to our new sprite. Click on Sprite inthe Sprites pane ta view the Sprite Liorary that lsplaysall the eiferent characters available. the Scratch Cat scripts again. Then click Gigato return to your Giga character, FETTER
) Programming with Scratch and Python ) Objects and Local Variables ARE YOU LOCAL OR GLOBAL? Objects, like your Scratch Cat sprite, can have their own variables. This could be the player score or the amount of ammunition left. These are stored inside the object and are known as “local”. Variables used by all objects are known as ‘global’. You're going to leave the disco behind, Chaose File > Click Make a variable and enter ditcet into the? New. You start with a blank stage containing a single ‘window making sure that your variable starts with & Scratch Cat sprite, Click Controland drag awhen flag clicked lowercase letter. There are two options here: For aL sprites block to the Script Area, ‘and For this sprite only. For all. sprites allows every sprite to use the dice; thisisknown asa global variable rovreaangioceecsinicomewicescauh EEREEMY For this sprite ony srt hs gure Cat rolls two dice and wins iF they're both the same Sue sprite can use the two dice variables, this is known number cick Data Unie therseceonsthereare ne blocks ere; asaloeavarableThsisuefl you wae ta crete another iatead ve hve tocreate te varibles enced Weneedt one charair itn ther oun seo ce anda aginst each the Terese sce. Were cong thatn the next sxora so choose ar hsp ony and lek OF BED 2s 2 sees tres( Objects and Local Variables BEPTID) whole bunch of blacks appears inthe Block PRPIIRD both the dicet and cice? variables are currently Palette. We can now use our dcet variable but ‘empty. They could be anything we wanted, but we want two dice, soclickMake a variable again and thistime we want them to be a random number between 1 and 6. Drag the center dice2, Remember ochoose For this sprite only and set [dicel] to [0] block and click underneath the when click OK. flag clicked biock Drag another set [dicet] to [0] block underneath and change the (dice1] setting to (dice?) SMOOTH OPERATORS Operators are used to change the values of variables, Some of these will be familia; you've used the addition operator ‘+’ to, ‘add two numbers together. Programs can also checki numbers are equal, bigger or smaller than each other or even not equal, Click the Operatortab and drag. pick random ‘The — operator checks iFtwo things are the same STEP | eco 10 aan tea Oise STEP 2 [ii ie Reed te Nel so check or NASBIEL Cle dicet to [O]/GRBEGEENe |10)koa|C]soitrenda'set dice: | BelNBRNG
. This sits between ‘two numbers, i.e. 3> 2 and lets you know IF the number on the left is bigger than the one on the right. Both sprites are going to announce their score and STEP | ee GRMBOEnd dre say Thetto} for 2 secs) Nawsdiek Date fnddrag. v'c_totaT|EGPEpIses [1 0] NEsepart oF the game's ready, were going to use an if Block with an ~ operator forthe next part of the game. STEP 2. Glick Control and drag anf block tothe script, Now click Operators and draa the » operator tothe Slob in the ‘block. Click Variables and drag vc toto’ tothe left Of the » block end vob_Lotal to the right, Finally cick Looks and Gisgasay [hel lo! ]BIBeRinsidetne F blockand change the Feet win’ Bob needs inthe seme srt only wih bob STEPS. total in place of cat_total. We could write Bob with the same code but the point of objects is that you can stamp out {Copies Shiftecik Bob and choose Delete Now Sfeclkvicand choose Duplicate. Click the Info icon and rename Vic2 as Bob. ne ‘ou need to change Bos ables Change STEP iset_vic_total|igset bob_total/andsay STE TotaT say bob total SBS c_ otallibob toto MU lok Now sek Gre Flag icon to play the game. Vic and Bob role their dice, and the ‘noe is aoncunce. DM's Definitive Gude Series Volume 31 135>) Programming with Scratch and Python. ) Classes and Objects SCRATCH THAT OP can be hard to explain, but makes sense when you start using . IF you've used Scratch then you already have an idea of ‘what an object Looks like, it looks like a sprite. This is why we detoured into Scratch. It's great for learning OOP. In this tutorial we're going to open the dice_game rogram that we created earlier in Scratch. Resize Sc oa the window and place Scratch on the left-hand side ofthe screen. Next we're going to recreate this qame in Python using objects, so you can see how objects are similar ta Scratch sprites, mI PRED open Python 2 and choose File» New Window, Resize the Editor window to the right-hand size of the screen. Choose File» Save As and name it dice_game. Now let's have alook a the objects in Scratch, we have twor Vic and Bob. Each has three variables (two dice and a total; both pick random numbers between 1 and 6 and check to see iFtheir totais ager than the other. ———E eee oT In OOP we don't design objects. Instead we design a blueprint For our object, called a "Class". Think oF ietke a blueprint or stamp. Vicand Bob are both dice-roling cats, 50 ‘we create a blueprint For a dice-aling animal. We then stamp out two identical objects from that blueprint. One called “Vi” the other called "Bob’, We're going to need the random number module, so enter thisline: from random import randint I [eee Oia Class DiceAninalO: dicel = 0 dice? = 0 total = 0 Notice the funny capitalisation of DiceAnimal, Thisis known as CamelCase and class definitions shauld be named in this Fashion, Now let's define our class, which we're going to call Diceanimal. Enter BED 22 cece tresBRTEEEERD Now we're going to define a function thatralls both dice, and adds the two together to create the total Inside the lass indented four lines a lineup with diet, dice? and total, enter this def rolldiceCselt): self.dicet self.dice2 self. total random. randint(1, 6) random. randint(1, 6) self.dicel + self.dicez i? CREATING OBJECTS. Classes and Objects Lookat Scratch, and you'lse this isthe same as the set dicet to pick random 1 to 6 block. But what ‘are those self bits about? Remember that Vic and Bob have their ‘own dice. c's dice are going to be accessed use vic. dicet and vk. ice? and Bob's using bob.cice' and bob.dice2. But the class doesn't know what we're going to call each object; instead it uses "self" asa placeholder. This works no matter what name each object as. STEP 6 = Now that our class is ready, we need to create two characters from it, One vie’ and one ‘bob’, These are known as objects, and. also sometimes as instances (or ‘object instance’), Because each one is an instance of the DiceAnimal class. STEP 1 Kfeatingan object in OOP has big Fancy names “instantiation” Don't be impressed by the (3h 0868, ilk means is creating an instance oF your class. And this is exacly the same as cresting a variable, onlyinstead of passing in number, or string, you make it equal to your class, Enter this Wvic = Diceanimal() bob = DiceAninal() There, that wasn’thard a all Now we're going to use dot natation to access the valves inside both the cat and lobster Enter STEP 3 this code: print “Vic rotted a™ vic.dicel, “and a” Wvic. diced) print “Gob rolled a”, bob.dicel, “and a” bob. diced] Finally, we've going to use if elf and else statements to create the game. You now have two abjects, 2 vic and a bob. You SHER. ‘access the variables and functions inside the object. aig the objects name followed by 3 dot To acess Vics de you Useviedice and vedee2. We're going to get both objects oral thet die and sore the total in ther own self total Enter Ivic.roltance() bob. rolldice() Enter this code: if vic. total > bob. total: print “Vic wins!™ (ETWF bob. total > vic. totals print "Bob wins elser print “It's a draw™ Press to sun the game. DMs Defintive Gude Series |voiumes GGWorking with Code At this point, you can see that there’s more to coding than simply entering a few lines into an IDE and expecting a result. Working with code means conforming to proper layout, adhering to strict operations and making the code as easy to understand and efficient as possible. In this section we take a look at the common coding mistakes with Python, C++ and Linux scripting and how to avoid them. You can learn how to check your code with checklists, Find sources of help when you're stuck and test your code online in a safe and secure environment. Learning to code is an on-going occupation, where you discover new techniques and ways of managing code from other developers. Being able to recognise mistakes, fix them and then help others is all part of becoming a better coder. 140 Common Coding Mistakes 142 Beginner Python Mistakes 144 Beginner C++ Mistakes 146 Beginner Linux Scripting Mistakes 148 Code Checklist 150 Where to Find Help with Code 152 Test Your Cade Online 154 Python OS Module Error Codes 156 Python Errors 158 Where Next? 160 Glossary of Terms BOM Definitive Guide Series | Vole 2Working with Code7 Mv Common Coding Mistakes MM ICUN TRUS onan MTU en MME aes Co Ty Cece Mesuec rer etc eiteuss mnt even experts make the occasional mishap. Thing is, to learn from them as best you can. =MISTAKE, PRINT Y There ore may pals forthe progranmer tbe are of fr oo arya be sted her, Belg able / torecognise a mistake and fix itis when you start to move into more advanced territory. It would be wonderful to be able to Work like Neo From The Matrix movies, ‘Simply ask, your operator loadsit into your memory and you instantly know everything about the subject. Sadly though, we cant do that. The First ‘major pitfalls someone trying to learn too much, too quicky. So take coding in small pieces and take your time. Use comments. tsa simple concept but commenting on. your cade saves so many problems when you next come to look overt. Inserting comment lines helps you quickly sift through the sections of code chat are causing problems; ‘also usefulif you need to review an older piece of code, EASY VARIABLES ‘meaningful naming For variables is a must to eliminate common coding mistakes. Having letters of the alphabet Isfine but what happens when the code states there's ‘ problem with x variable, I’ not too difficult to name variables lives, money, playert and so on az points = 1023; r lives = 3; totalzine = 457 Heotaltines" secs"); ‘totalscore ~ weite("Your total Score is: "stotalscore) PLAN AHEAD \whileit's great to wake up one morning and decide to code 2 classic text adventure, it's not always practical without a {00d plan, Small snippets of cade can be written without too much thought and planning but longer and more in- depth code requires a good working plan to stick toand help iron out the bugs,Common Coding Mistakes USER ERROR BACKUPS SWS Cea SR}Working wth Code Beginner Python Mistakes OEM c aac aer ascnce mane cask CMU nCa icine emeck irene Programming language, it can be easy to make common mistakes that'll stop your code from running. DEF BEGINNER(MISTAKES=10) Here are ten common Python programming mistakes most beginners find themselves making. Being able to identify these mistakes will save you headaches in the Future. NECTED 10.20d tothe confusion that mostbeainners INE GRCGRU eee oochon uses precise already face when coming into programming, indentations when Python has twollive versions ofits language avalable to download displaying its code, The indents mean thatthe code in that section and use. There is Python version 2.7.xand Python 3.6.x.The3.6x isa parof the previous statement, and not something linked with versionis the most recent, and the one we'd recommend starting, another part ofthe code. Use Four spaces tocreate an indent, not But, version2.7.x code doesn't always work with 3.62 code and the Tab key, Be aa &°e1y programmerhas anddoesatsome PREVIM EMER). g2in we mention commenting point goon the Internet and copy some. I’sahugely important Factor in code to insert into thelr own routines. There'snothing wrong with programming, even IFyou're the only one who is ever going to view using others code, butyou need toknow how the code works and the cade, you need to add comments as to what's going on. Isthis what it does before you go blindly running it on your own computer. Function where you lose alife? Write @ comment and help you, or anyone else, see what's going on, Create at fle ina python progam BZD ors vetintve Gude Series | vole 21Remember thatn Python a loop COUNTING LOOPS doesn't count the last number you specifyina range. So f you wanted the loop to count From 1 to 70, then you will need to use: n= ListCrangeCt, 119) Which will return to 10. Dranaaa Tg cp wt ip SSNS need to check any variables you assign For example, LAVESEIO isa lfferent variable to lves=10, caling the wrong variable in your code Python is a case sensitive programming language, so you will can have unexpected results. To riten 36201 File_Edt_Shel_Oebug_Optins Window Help Pychon 3.6.2 (v3.€.r84a00b8, dol 8 2057, OFT: on wind? aype tespyrians", bop tavesl0 Bop lives 333. peincitives, woreaite” ox "License ()" for mor aives) BRACKETS, Everyone forgets to include that extra bracket they should have added to the end ofthe statement. Python relies on the routine having an equal amount of closed brackets to open brackets, so any errs in your cade could be due to you Forgetting to count your brackets; including square brackets. def print_game_stacus(self): Print (board|len(self-missed_letcers)]) print (‘Word ' + self-hide vord()) Prine ("Leccera Missed: ',) for later in aelf.missed Lette: print (ietter,) print () print (‘Letters Guessed: ',) for letter in aelf.guessed letter: print (letcer,) prine () L \ Beginner Python Mistakes. Cl loss Hangman: def quess(self, letter): ‘And so on. The colon is what separates the code, and creates the indents to which the following code belongs to. Itscomman for beginners to forget to adda colon tothe end of a structural staternent, such as OPERATORS Using the wrong operators also a common mistake to make. When you're performing _a.comparison between two values, for example, you need to use the equality operatar (a double equals, ==). Using a single equal (=) is an assignment operator that places a value to a variable (such a, lives=10), bes o=10 a=10 b =e #ralse because 5 is not equel to 10 4 ferue because 10 is equal to 10 elt EAC writing code For multiple platformsis difficult, especially when you star to utlse the extemal commands of the ‘operating system. For example, iF your code cals For the screen tobe cleared, then For Windows you would use EUS. Whereas, for Linux youneed to use €Lear. You need to solve ths by capturing the error and issuing it with an alternative command. Glave: depmccexeoe Fi wail « item 6) os-syater(‘cless") 2.systen(*cl9") peine(*m>>o>>5>>9BytRon 3 File Managerceecce
int main() { std::cout << x; + SEMICOLONS program must end with a semicolon. IFit doesn't then the compiler treats the line with the missing semicolon as the same line with the next semicolon on, This creates allmanner of problems when trying to compile, so dont forget those semicolons. Remember that each line of a C++ \#include
int main() it int a, b,c. d; std::cout << a, b, ee ee Referencing the Standard Library is Aa ‘common for beginners throughout their code, but If you mis the std: element of a statement, Your code errors out when compiling, You can combat this by adding using namespace std; Under the tinclude part and simply using cout, cin and soon from then on. #include
using namespace std; int main() { int x; string mystring cout << cin >> x; cout << x; t cout << "\n\n"; cout << mystring; ‘This is a string!\n" What's the value of x? In C++ variables arent initialised to 2er0 by default PUTS RASTA} This means if you create avariable called x then, potentially, tis siven a random number from Oto 18,446,744,073,709,551,616, ‘which can be difficult to include in an equation. When creating @ variable sive it the value of zero to begin with: X=. #inelude
) Working with Code Python Errors It goes without saying that you'll eventually come across an error in your code, where Merk cceacue sete r uci simu tit aici Ren en ronan cia eee cast ease cae icles DEBUGGING Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important thing is to keep looking, experimenting and testing. Eventually your code will be bug Free. Code en 2 fu athe writen word no matter “Thankfully Pythons helpful when comesto sue? | how good the programming language is. Python is eure) displaying error messages. When you receive an certahly easier than mostlanguagesbuteven iis ronetasome err incedtexe from the IDLE hel, kwildefne the ear sel anoying bugs The mest commnonaetypos byte ser and whist slong withthe ine number vers the evra ha cere, Wh stn tasytofind nimple dazemline code, magine having to debug —_thelDLE Edtorths sate daunting for los oF code text edors ialtthousand tne code help by nclding line numbering. FPR the most common of errorsisthe typo, as we've FRID sytaxersors are probably the second most mentioned. The typas are often at the command level: mistyping the print command for example. However, they also Even ithe spelling is correct. the actual command itself is wrons, Doccur when you have numerous variables, alof which have lengthy In Python 3 ths often occurs when Python 2 syntaxes are applied names, The best advice sto simply go through the code and check The mast annoying of these isthe print Function. In Python 3 we use your spelling, print(‘words"), whereas Python2 uses print “words” common errors you'll come across as programmer, ie bs oat Geng geen sue te He Eee Sel nog Stns Yrs He sows tfatn ues nePesky brackets are aso a nuisance in programming BD orcs especialy whenyouhave something Ike printcbalanced_check(input())) Remember that forevery there mustbe an equal numberof tneort 98 sercrece = oe bh » 1+ charactor in reference. toys) ach ape enracter) ‘At character in roferncesaes() and lentstach) > 0: ‘onhow best to achieve something, Whilst 99 per cent of it is good code, don't always be lured into copying and pasting random code Into your editor. More often than not, it won't work and the worst parts that you haven't learnt anything, There are thousands of online Python resources, code snippets and lengthy discussions across Forums C Python Errors Gc Aan excellent vay te check your code step-by-step SUPE is to use Python Tutor's Visualise web page, Found at waww.pythontutor.com/visualize.htm|s#mode=edit. Simply paste your codeinta the editor and ck te visvalee Execution Daktonto runthe code tne byte. Tishepsto clear bugs and ary misunderstanding. Planning makes for good code, Whilst alte old school, t's good habit to plan what your code ull do before sitting down to type it out. Listthe variables that wll be sed and the modules too; then write outa script for any user interaction or outputs. Indents area nasty part of Python programming that alot of beginners all foul of Recall the f loop, from the Conditions and Loops section, where the colon means everything indented Following the statement tobe executed as long ass true? Missing the indent, or having too much of indent, vill come back with an error. Purely out oF interest, the word debugging in computing terms comes from Admiral Grace Hopper, who back inthe 40s was working on a monolithic Harvard Markl electromechenical computer. According to legend Hopper found a moth stuck ina relay, thus stopping the system from ‘working, Removal ofthe moth was hence called debuaging,Working with Code Where Next? Coding, like most subjects, is a continual learning experience. You may not class yourself as a beginner any more but you still need to test your code, learn new Pee UM cLeoM ao ieee Cy o-oo (ToL programming language. #INCLUDE
What can you do to Further your skills, learn new coding practises, experiment and present your code and even begin to help others using what you've experienced so far? BSED) Titerssntall trolls and antagonists, among the well [EREESENM Look for open source projects that you lke the sound publicised vitriol are some genuine people who are of and offer to cantrbuteto the code tokeepit more than willing to spread the'r coding knewledge. We recommend alive and up to date, There are milions of projects to choose From, so you find afew who you can relate toand Follow them. Oftenthey contact a few and see where they need help t may only be a mina! post great tips, hacks and Fies For common coding problems. code update butit's a noble occupation For codersto get int, Om ne ee iyovie mere tory nel en cunseur BREE exc ore ve en codg ar elmer UEP attention to C++ or even C#. Still keep your Python SLES knowledge sites, such as StackExchange. If you have skills going but learning a new coding language keeps the old brain the skills to start and help others out, not only will you Fee! really ticking over nicely and give you a view into another community, and good For doing so but you can also learn a lot yourself by interacting how they do things differently ‘with other members. StackExchange™ = = e : sonst ues ne( Where Next? PETER the mobile market sa great place totest your BSTISISRD youve learned how to code with an eye For 2 coding skill and present any games or apps you've developer job in the Future, then is worth starting created. f your app is ood, then who knows, could be the to bulld up an online portfolio of code. Look at ob postings and see next great thing to appear on the app stores It’s a good learning _ what skllsthey require, then learn and cade something with those experience nevertheless, and something worth considering skils and add it to the portfolio. when comes to applying include alinktothe portfolio. 4 = eS ccnoniciedors BSED Online courses are good examples of where to PETER can you teach? your coding skilsare spot on, take your coding kills next, even i youstart consider approaching a college or university to see from the beginner level again, Often, an online course follows —_iFtheyhave need For a programming language teacher, perhaps 3 Strict coding convention, so iF you're selPtaughtthen it might be __ parttime or evening course. IFnot teaching, then consider creating worth seeing how other developers ay out thelr code, and what’s your own YouTube howto code channel considered acceptable. FETED Cet sharing, even ifyou think yourcode isn't very ESTESIETRIR) Contributing toharchware projects is a great ‘good, The criticism, advice and comments you resource For proving your code with others and receive back help you iron out any sues with your cade, and you _learing from other contributors. Many ofthe developer boards have add them allto your checklist. Altematively your code might be postings For coders to apply to For hardware projects using unique utterly amazing but you wont know unless you share it. code to get the most rom the hardware that's being designed. somsdetintve Gude series vines EN=P Working with Code Glossary of Terms DO Tetae Cet iu us omen neem ue Meat nt CEI, Date ric inital acetates ole ED oR CMe am eR ole Re Leelee R elt Reels eB ol NAAR oe gain experience and try new things, your coding vocabulary will naturally expand. A ALGORITHM process orset of rules tobe followed incalcuations or other problem solving operations, especialy bya computer. ANGULAR.JS ‘Angularjsisan open source web application framework maintained by Google. APACHE ‘Apache is an open source Unicbased Web server. Ie was created by the Apache Software Foundation AJAX ‘AJAX stands for: asynchronous JavaScript and XML. isa set of web development techniques Using many web technclogies on the client side in orderto create asynchronous web applications APL ‘An APlisan application programming interface. ttisa set of routines, protocols and tools forbulling software applications, APIs express Software components in terms oftheir erations, input, outputs and underlying types B BACKBONE.JS Backbone sis JavaScript framework with a RESTFULSON interface andisbased on the modeliew-presenter (MVP) application design paradigm, BOOLEAN SEARCHING Boolean searches allow you to combine words and phrases using the words and, or, not (Boolean operators to limit, broaden or define your search BUG Ammistakein the program. A point oF error that causes the program to stop, or behave differently than expected. BRACKETS CCharacters often used to surround text. The different types of brackets are: Parenthesi Curly Brackets, Angle Brackets and Square Brackets. C CALL Torun the code na function; also referred to.as “running” “executing” oF “invoking” a function. CLASS InPython, atemplate for creating user-defined objects lass definitions normally contain method definitions ‘which operate on instances of the class, CODING Codingisthe actof computer programmingin a given coding language, COFFEESCRIPT Coffeescrptisa programming language that trans compiles to Javascript COMPILER Thisisa program that takes the code you have written and translates t into the binary ones and zeros of actual machine code. CONCATENATION Combining two things together, suchas two stsor strings oftext: sos tft ue es net CONSTANT ‘Avariable that never changes its value. Example: the Pi constant. has the value 3.14 D DATA STRUCTURES ‘A data structure isa method of organisation of data in computer so thatitcan be used efficiently, DEPLOYMENT Software deployment sal ofthe ‘activities that make asoftware system avaliable for use. DJANGO ‘free open source web ‘application Framework written inPython that Follows the model-viewscontroller (MV0 framework. DUMP Allstof data thats saved if program crashes, often as a textfile.Itisvery useful for iagnosing problems, E EXECUTABLE A program, usually single file, readytoberun, EXPRESSION Apiece ofsyntax which can be evaluated to some value; An ‘accumulation of expression elements tke literals, names, attribute access, operators or Function calls EXPRESS.JS Expressisisa Nodeysweb application server framework, {esigned for building single page, mult-page and hybrid ‘web applications F FLASK Armicroweb application Framewark written in Python and based onthe Werkzeug toolkit and Jinja template engine. FRAMEWORK A frameworks often a layered structure indicating what kind of programs can or should be built and how they would interrelate FULL STACK Afullstack, aso known as software stack or bundle, is setof software components needed to create a complete web application. FUNCTION Asotof instructions that are ‘written once to obeaina particular result and can then be used whenever necessary by’caling it G GIT/GITHUB ‘Amico web application framework vittenin Python and based on the Werkzeug toolkit and Jinja template engine, cu General User Interface refersto the Frontend’ ofa plece of software thatthe end user actualy sees andinteracts with H HAML HTML Abstraction Markup Languageisa lightweight markup language that's usedto describe the HTML of aweb document,HASHABLE ‘An oblectishashable fithasa hash value which never changes dlring is lifetime (needs a _hash_) method), and can be Tomparedto other objects, HTML Hypertext Markup Language, commonly referred toas HTML, isthestandard markup language used to create web pages, This is often the ver irs technology that beginners to web evelopment wil learn. HTTP REQUEST Hypertext Transfer Protocol isan application protocol for suibuted, colaborative, hypermedia information systems. HPs the Foundation ‘of data communication forthe World wide web, INTEGRATED DEVELOPER ENVIRONMENT (IDE) ‘An Integrated Development Environment is abasic editor and code interpreter which allows you to work with a specific coding language. The Python IDE isknown as IDLE INTERPRETED Python is aninterpreted language, as opposed toa compiied one, though the distinction can be blurrybecause ofthe presence of the bytecode: compier. INTERPRETER Some languages do not need a complier butinstead use an ‘interpreter’ that translates to machine code as the program istun, IOS SWIFT OS Swift isa mutéparadigm complied programming language created by Apple inc Fori0s, macOS and watchoSand 10S development. ITERATION sequence of instructions that are repeated. For example, to perform an action for every item inalistyou would iterate over thatlist: Each time itis repeated isone iteration J JQUERY Queryisa crossplatform JavaScript Ubrary designed to ‘imply the client-side scripting oF HTML jQuery is the most popular JavaScript Ubrary in use today. JSON ‘format for transmitting information between locations that is based on JavaScriot. Many ‘APIs use JSON, L LAMP STACK LAMPis an archetypal model oF web service solution stacks: Lux operating system, the Apache HTTP Server, MySQL relational database management systemand the PHP programming language LBYL Look before you leap. This coding style explitly tests For preconditions before making calls or lookups. LINUX Unuxis a Unictke computer ‘operating system assembled Under the madel of free and ‘open source software development and distribution. LOGICAL OPERATION ‘The use of simple Boolean lagical suchasand, or and no. Loop piece of code that keeps running until certain condition isfulflled;or isnt fulfilledin the case ofan ‘infinite loop’ that will, crash the system running i M MONGODB. MongoDB isa cross-platform document oriented database, Classified 2s @ NoSQL database. mvc Modelview-controller (MVC)is 2 software architectural pattern for implementing user interfaces. cividesa given software application Into three interconnected parts. MYSQL ‘MySQL san open source relational database management system (RDBMS) ( Glossary of Terms Ec N NESTED. ‘When one thing is contained within anather ies saidto be ‘nested NODE.JS Nodejsisan open source, ‘cross-platform runtime ‘enviranment For developing serversside web applications. Nodejs applications ae written in Javascript and can be run ‘thin the Node js runtime on multiple systems. O OBJECT ORIENTED. PROGRAMING (OOP) (00P isa programming paradigm based on the concepts of objects! that are data structures containing data, inthe form of elds, often known asatsibutes; and code, in the form of procedures often krownas methods OBJECT RELATIONAL MAPPER (ORM) ORM isa programming technique for converting data between incompatible type sstemsin objectoriented programming languages P PHP PHP isaserverside scripting language designed For web development butalso used ‘asageneral purpose programming language. PYTHON Pythonisa widely used general purpose, highlevel rograrnming language lis design philosophy emphasises code readebiity and itssyntaxallows programmers to express concepts infewer lines of code than would be possible inlanguages suchas C+ or avo. R RECURSION When something eferstotsef Forexample variable may add something to itself For each iteration of code loop, RUN TIME The time during which a program isactively running, S SANDBOX ‘place to run a program for testing and experimenting SASS Sessisa scripting language that isinterpretedinto Cascading Sbyle Sheets (C55).SassScriptis the scripting language itself and consists of two syntaxes. SLICE An object usually containing = pttion of asequence.A slices Created using the subscript ‘notation, [] with colons between rhumbers when several are given, SOFTWARE DEVELOPMENT KITS. Asoftware development kit'or SDK'is@ bundle of software tools Forthe creation of new, applications fora specific platform or framework SUBROUTINE {function or other portion oF code that can be run anywhere within a program. SYNTAX Programming languages arejust like human languages, they have their own'syntax’or rules to describe how statements should be wtten T TYPE The type ofa Python abject determines what kind of object t isjevery object has type. V VALUE Apiece of data that can be contained inside a variable. Every value has a type. VARIABLE ‘Away, used by many programming languages, to store apiece of datathat can then be modified at ay time, W. WRITE ‘Tosend output data values to an external destination, usualy toa file, canalso reFerto sending data aver a network. ous de Sie oe 3BDM Publications Innovate, Educate, Inspire... Stay up to date about all of Your Apple devices! Subscribe now// a ~ Vs Normally £3.99 per digital issue Coding Ticks, Hacks 8 Fes * Top features « Interviews se Ha + Reviews « Latest news * Competitions + iTunes Subscribe Now at: www.bdmpublications.com Many BDM titles are also available as digital editions: Search Poss ZINIOThe Complete een le aey-2.4@) bal WhatsApp Manual Manual ch aes ee a i eon a The Complete Photography pre 4 eT "Fm iC Lightroom Manual he Complete GoPro Manual The Complete Instagram Manual are The Complete Outdoor Photography Peed Y Gitenne The Complete Ere ea y Ml Photosho} protoaraphy Manual Manual | The Complete MacBook Manual
You might also like
The Complete Coding Manual (21th Ed., 2024)
PDF
100% (2)
The Complete Coding Manual (21th Ed., 2024)
164 pages
HubSpot - Learn To Code With ChatGPT Ft. Sundas Khalid
PDF
No ratings yet
HubSpot - Learn To Code With ChatGPT Ft. Sundas Khalid
36 pages
Jones, Martin - Python For Complete Beginners - A Friendly Guide To Coding, No Experience Required (2015) - Libgen - Li
PDF
No ratings yet
Jones, Martin - Python For Complete Beginners - A Friendly Guide To Coding, No Experience Required (2015) - Libgen - Li
225 pages
The Complete Python Coding Manual - 21th Edition, 2024
PDF
No ratings yet
The Complete Python Coding Manual - 21th Edition, 2024
164 pages
The Complete Coding Manual - 19th Edition, 2023
PDF
No ratings yet
The Complete Coding Manual - 19th Edition, 2023
196 pages
Phython and C++ Learning
PDF
No ratings yet
Phython and C++ Learning
164 pages
The Complete C++ & Python Manual - 18th Edition 2024
PDF
100% (1)
The Complete C++ & Python Manual - 18th Edition 2024
148 pages
The Complete Coding Manual - Issue 4 - February 2024
PDF
No ratings yet
The Complete Coding Manual - Issue 4 - February 2024
161 pages
Mini Python - Beginner
PDF
No ratings yet
Mini Python - Beginner
82 pages
Python For Beginners
PDF
No ratings yet
Python For Beginners
111 pages
BDM's Coding Tips, Tricks & Fixes V27 - 2019 UK PDF
PDF
No ratings yet
BDM's Coding Tips, Tricks & Fixes V27 - 2019 UK PDF
148 pages
Python 1
PDF
No ratings yet
Python 1
289 pages
2020-05-01 The Essential Coding Manual
PDF
100% (3)
2020-05-01 The Essential Coding Manual
194 pages
Python Coding and Programming
PDF
No ratings yet
Python Coding and Programming
162 pages
Python & C++ For Beginners, 2nd Edition (2020)
PDF
No ratings yet
Python & C++ For Beginners, 2nd Edition (2020)
82 pages
Coding For Beginners - 12th Edition 2022 - Coding For Beginners
PDF
100% (1)
Coding For Beginners - 12th Edition 2022 - Coding For Beginners
97 pages
Essential Programming Concepts Guide
PDF
No ratings yet
Essential Programming Concepts Guide
64 pages
The Ultimate Python Coding
PDF
30% (10)
The Ultimate Python Coding
194 pages
My Python Notes
PDF
No ratings yet
My Python Notes
120 pages
Python Complete Manual (Coding & Programming)
PDF
No ratings yet
Python Complete Manual (Coding & Programming)
165 pages
PCL. The Complete C++ & Python Manual 15ed 2023
PDF
No ratings yet
PCL. The Complete C++ & Python Manual 15ed 2023
148 pages
Bdms Series The Complete Coding Manual Volume 31 PDF
PDF
No ratings yet
Bdms Series The Complete Coding Manual Volume 31 PDF
163 pages
Python Beginners
PDF
0% (1)
Python Beginners
23 pages
Linux Tricks and Tips Ed19 2024
PDF
No ratings yet
Linux Tricks and Tips Ed19 2024
66 pages
Programming Tips
PDF
No ratings yet
Programming Tips
21 pages
What Is Programming? A Handbook For Beginners
PDF
No ratings yet
What Is Programming? A Handbook For Beginners
133 pages
The Complete Python Manual (5th Edition) - April 2020
PDF
100% (1)
The Complete Python Manual (5th Edition) - April 2020
197 pages
Coding User - Issue 08 December 2023
PDF
No ratings yet
Coding User - Issue 08 December 2023
242 pages
Coding For Python - 2020-06
PDF
100% (2)
Coding For Python - 2020-06
164 pages
The Ultimate Python Coding Manual, 5th Edition 2021
PDF
100% (1)
The Ultimate Python Coding Manual, 5th Edition 2021
194 pages
Lec 1
PDF
No ratings yet
Lec 1
19 pages
The Complete Coding Manual (5th Edition) - April 2020
PDF
No ratings yet
The Complete Coding Manual (5th Edition) - April 2020
197 pages
Coding Basics
PDF
No ratings yet
Coding Basics
14 pages
BDM's Coding For Beginners - 2018 UK
PDF
100% (1)
BDM's Coding For Beginners - 2018 UK
164 pages
Python Coding Book Ch2
PDF
No ratings yet
Python Coding Book Ch2
75 pages
Introduction To Python
PDF
No ratings yet
Introduction To Python
8 pages
English
PDF
No ratings yet
English
5 pages
Programming With Python - An Easy To Understand Beginners Guide To Coding With Python
PDF
No ratings yet
Programming With Python - An Easy To Understand Beginners Guide To Coding With Python
31 pages
The Complete Python Coding Manual - 3rd Edition, 2023
PDF
No ratings yet
The Complete Python Coding Manual - 3rd Edition, 2023
196 pages
What Can Programming Do For You
PDF
No ratings yet
What Can Programming Do For You
3 pages
Python & C++ For Beginners - Vol. 33, 2019
PDF
No ratings yet
Python & C++ For Beginners - Vol. 33, 2019
164 pages
The Complete Coding Manual 5th Edition - April 2020
PDF
No ratings yet
The Complete Coding Manual 5th Edition - April 2020
197 pages
The Essential Coding Manual November 2019
PDF
No ratings yet
The Essential Coding Manual November 2019
198 pages
Coding For Beginners 2nd Edition-May 2020 PDF
PDF
No ratings yet
Coding For Beginners 2nd Edition-May 2020 PDF
84 pages
Python C For Beginners Apr 2022.sanet - ST
PDF
No ratings yet
Python C For Beginners Apr 2022.sanet - ST
80 pages
The Complete Coding Manual August 2019
PDF
No ratings yet
The Complete Coding Manual August 2019
197 pages
2022-07-23 Python For Beginners
PDF
No ratings yet
2022-07-23 Python For Beginners
94 pages
The Complete Coding Manual December 2019
PDF
No ratings yet
The Complete Coding Manual December 2019
165 pages
C-Python For Beginners
PDF
No ratings yet
C-Python For Beginners
78 pages
Coding For Python 37 2019
PDF
No ratings yet
Coding For Python 37 2019
164 pages
Python & C++ Guides - August 2019
PDF
No ratings yet
Python & C++ Guides - August 2019
166 pages
How To Start Coding - The Ultimate Guide For Beginner Programmers
PDF
No ratings yet
How To Start Coding - The Ultimate Guide For Beginner Programmers
22 pages
Plete Python Manual 5th Edition 2020 PDF
PDF
No ratings yet
Plete Python Manual 5th Edition 2020 PDF
195 pages
Black Dog Media - The Complete Coding Manual - 3 Ed.
PDF
No ratings yet
Black Dog Media - The Complete Coding Manual - 3 Ed.
23 pages
The Complete Python Manual by The Complete Python Manual
PDF
No ratings yet
The Complete Python Manual by The Complete Python Manual
197 pages
The Complete Python Manual (5th Edition) - April 2020-NoGrp
PDF
No ratings yet
The Complete Python Manual (5th Edition) - April 2020-NoGrp
197 pages