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

Python & C++ Guides - August 2019

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

Python & C++ Guides - August 2019

python guide
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 166
14g Python 3 | C++|Working with Code (| Pythons. for Beginners Learning to code for students, for work, for fun, for everyone p | £999 fl | 33 ll 77 204%"990036 Discover more of our complete manuals on Readly today... eS ican The Complete The Complete coo (Ubuntu | Linux Mint Manual Manual Manual Sy See WhatsApp The Complete Building Your Own PC Manual Manual ‘Android | The Complete AG ia lordPress marot Google Manual Mantal Pe compite on ees Outdoor Black & White Landscape ait hy Photograph Photography sa Wey Y Manual ‘| BD's Definitive Guide Series Python:.C: for Beginners “Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is Fun to program.” ~Linus Torvalds (developer of the Linux kernel) Having a basic knowledge of programming can open many different doors for the newcomer to explore. You can understand how hardware and software work together better, how your computer or device Functions and how incredible open-world gaming environments are converted from ones and zeros to what's on your monitor or TV. Technology is everywhere andit’sall connected through programming. Your TV, microwave, in-car entertainment and the Internet itself are all reliant on good programming to make them work the way you want them to. ‘Within these pages are the building blocks to help you take your first steps into the world of programming. We've taken two of the most powerful and versatile programming languages available, Python and C++, and broken them down into bite-sized tutorials and guides to help you learn how they work, and how to make them work for you. Learn how to install them, print simple messages to the screen, ask for user input and manipulate the data to produce amazing results. By the end of this book you will understand how Python and C+ work, and what potential lies beyond. Ready? Let's get programming! iy] @bdmpubs Gi BDM Publications ‘www.bdmpublications.com \ Contents ‘ontents_) 6 ) Say Hello to Python 60 Writing to Files 62 Exceptions 8 _WhyPython? 64 Python Graphics 10 Equipment You will Need 12 Getting to Know Python 14 Howto Set Up Python in windows. 16 How toSet Up Python on a Mac 18 How toSet Up Python in Linux 68 Calendar Module 70 OSModule 72 Random Module CRG euch 74 _Tkinter Module 76 Pygame Module 22 _ Starting Python for the First Time 80 Create Your Own Modules 24 Your First Code 26 Saving and Executing Your Code 82) Say Hello to C++ 28 _ Executing Code from the Command Line 30 Numbers and Expressions 32 Using Comments 34 Working with Variables 36 User input 38 Creating Functions 40 Conditions and Loops 42 Python Modules 84 WhyC+? 86 Equipment Needed 88 How to Set Up C+ in Windows 90 How to Set Up C++ on a Mac 92 How to Set Up C++ in Linux 94 Other C+ IDEs to Install Cea CU 44) Working with Data 98 Your First C++ Program 46 Lists 100 Structure of a C++ Program 48 Tuples 102 Compile and Execute 50 Dictionaries 104 Using Comments 52 _ Splitting and Joining Strings 106 Variables 54 _ Formatting Strings 108 Data Types 56 Date and Time 110. Strings 58 Opening Files 112 C++ Maths BE) 20sec sete veine3d QS c ons GURU kere 116 User interaction 138 Common Coding Mistakes 118 Character Literals 140 Python Beginner's Mistakes 120 Defining Constants 142 C++ Beginner's Mistakes 122. File Input/Output 144 Where Next? > EEE 126 while Loop 148 Python File Manager 128 For Loop 150 Number Guessing Game 130 Do... While Loop 152 Polygon Circles 132 Statement 153 _ Random Number Generator 134 If... Else Statement 154 Random Password Generator 155 Keyboard Drawing Script ‘It’s OK to Figure out murder mysteries, 156 Pygame Text Examples but you shouldn’t need to Figure out code. 157 Google Search Script You should be able to read it.” 158 Text Adventure Script ~ Steve McConnell (Software Engineer and Author) 160 Hangman Game Script index) Say Hello to Python “How did you know so much about computers?” “| didn’t, it was the first one.” ~ Admiral Grace Hopper (pioneer programmer) when interviewed by David Letterman ora bmpublcations com Say Hello to Python ‘There are many different programming languages available to learn and use. Some are extremely complex and incredibly powerful, while some are extremely basicand used as minor utilities For the ‘operating system. Python sits somewhere in the middle, combining ease of use with generous helping of power, which allows the user to not only create small projects butalso excellent games and performance heavy computational tasks. However, there’s more to Python than, simply being another programming language. It has a vibrant and lively community behind it that shares knowledge, code and project ideas, as well as bug Fixes for Future releases. It’s thanks to this community that the language has grown and thrived; now, it’s your turn to take the plunge and learn how to program in Python. The first half of this book helps you get started with Python, and from there guides you on how to use some of the ‘most common and interesting functions and features of the language. Before long, you will be able to code your own helpful. system tools, text adventures and even control a character as they move around the screen. 8 Why Python? 10 Equipment You will Need 12 Getting to Know Python 14 How to Set Up Python in Windows 16 How to Set Up Python on aMac 18 How to Set Up Python in Linux ED) sriiioron Why Python? REET icns ae cuneate ee Cees eu kcout sin Pee eee eh aisedticeicmscue ato lentes are designed For scientific work, others for mobile platforms and such. So why choose Python out of all the rest? PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. ‘These pioneers of programming carved their way into anew Regardless of whether you use an Android device, 10S device, PC, Frontier, Forging small 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 terribly exiting to ageneration to aca, settop box ora thousand other connected and ‘sma ‘that's used to ultra high-definition graphics and open world, multi appliances, behind them alis programming, player online gaming, However, forty-something years ago it was. inaly brillant. All those aforementioned digital devices need instructions to tell, ‘hem what to do, and allow them tobe interacted with, These "Naturally hese bedraom coders helped form the foundations for instructions Form the programming care of the device and that care ‘every piece of digital technology we use today. Some went onto can be built using a variety of programming languages. ‘become chief developers for top software companies, whereas ‘others pushed the available hardware to its imits and founded the _The languages in use today differ depending on the situation, the billion pound gaming empire that continually amazes us. platform, the device's use and how the device wil interact with ts certssontsenttonst oid Arrayctrl::childLostrocus() seraycerl::Paint(Orave ») ( urtaamet Paine): 1) =o) ) Galor fe » Blend(scoloroieabled, ScolorPaper): Stata) siete earcamey frbottom © Fekop + oateanecy(a): Torddne 5 < colum.catcount(); 344) ¢ int by Roeder GatracisdehO) nt em = cotumni3] mara Feces a for Tay) ctrrain(s ree ieee environment or users. Operating systems, such as Windows, macOS {and such are usually @ combination of C++, C#, assembly and some form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and soon, ‘More general-purpose programming is used to create programs, apps, software or whatever else you want to call them. They're widely used across all hardware platforms and sult virtually every conceivable application. Some operate Faster than others and some {are easier to learn and use than others. Python is one such general purpose language. Python is what's nown 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, Whilst t'snatas streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefitis that it's universally accessible and easy to learn. import java. lang.reflect.*; ‘lass. Tavoke Public static void main( string [] args ) try Gass ¢ Method’ Ut 3s Object het = msinyokeC mul1, nuT1 95 Sybten-out princinc STavoked seats method: " + args(1] yofenass: * *args(o) +" wich no-args\onesules: + ree >; catch ¢ Classnotroundexception ¢ ) { {7° Classcforname(.)- can't finds the-class Caren C fosuchmethodexception 2) { [fat method doesnt exioe Gaceh ( TMlegataccesstxception 3 Fre don't Rave peraission eo favoke that ‘sss. fornane( args(0) “Cigeiethodt atg2{), adn class inethod ¥ catch ( tnvocationtargetexception e4 ) { 77-an exception ocurred while invoking that inethod’ Syst out _printin¢ ‘Method thren an: " + e4. getTargetexception( ")")} Javaisa powerful language that’s used in ‘web pages, settop boxes, TWsand even cars. ora publications com Why Python? Cll Python was created over twenty sik years 290 and has evolved to become an ideal beginner's language for learning how to program a ‘computer. It’s perfect for the 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 tse Python is Free to download, install and use andis available For Linux, ‘Windows, macOS, MS-DOS, 05/2, BeOS, IBM iseries machines, nd ‘even RISC OS. thas been voted one of the top five programming languages in the world ands continually evolving ahead ofthe hardware and internet development curve. So to answer the question: why python? Simply put, it's Free, easy to team, exceptionally powerful, universally accepted, effective and a superb learning and educational tool BASIC was once the starter language that early ‘bit home computer users learned. ae B poperaete senate Python isa more modern take on BASIC, i's easy to learn ‘and makes for an ideal beginner's programming language, z=» Say Hello to Python) J Equipment You Will Need You can learn Python with very little hardware or initial Financial investment. You don't need an incredibly powerful computer and any software that’s required is freely available. 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 needa computerin order to lear howto programin Python and to test your code. You can use Widows (rom XP onward) on ethera 32 or 62 processor an Apple Mac or Lind insaled PC. [_] AN IDE AnIDE (Integrated Developer Environment) is used to enter and execute Python code, Itenables you to inspect your program cade and the values within the code, as ‘wellas offering advanced Features. There are many different IDEs available, so Find the one that works For you and gives the best results, |_| PYTHON SOFTWARE ‘macOS and Linux already come with Python preinstalled as part of the operating system, as does the Raspberry Pi However, ou need to ensure that you're running the latest version of Python. Windows users need to download and install Python, which well cover shortly |_| TEXT EDITOR \Whilst a text editor is an ideal environment to enter code into, i's not an absolute necessity. Yu can enter and execute code directy From the IDLE buta text editor, such as Sublime Text or Notepad, offers more advanced features and colour coding when entering code, |_] INTERNET ACCESS Python is an ever evolving environment and as such new versions often introduce new concepts or change existing commands and code structure to make it a more efficient language. Having access to the Internet will keep you up-to-date, help you lout when you get stuck and alve access to Python's immense number of modules. |_| TIME AND PATIENCE Despite what other books may lead you to believe, you won't become a programmer in 24-hours. Learning to code in Python takes time, and patience. You may become stuckattimes and other times the cade wil Flow ike water. Understand you're learning something entirely new, and you will get there. soso sen ( Equipment You Will Need Cl 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 learning platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras. Sal agd The Raspberry P 3s the latest version, incorporating a more powerful CPU, more memory, Wii and Bluetooth support You can pick up a Pi for around £32 or asa part of kit for £50+, E depending on the kit youre interested in FUZE PROJECT The FUZE isa learning environment built onthe latest model of the Raspberry P. You can purchase the workstations that come with an electronics kitand even a robot arm for you to bulld and program. You can find mare information on the FUZE at wwwwfuze.c0.uk BOOKS iieciencoseal ERE Raspberry titles available via www. bdmpublications. ‘com, Our Pi books cover howto buy your frst Raspberry Pi, setitup and use itthere are some greatstep-by-step project examples guides toget the most From the Raspberry Pitoo. RASPBIAN The Raspberry P's main operating system isa Debianrbased Linux distribution that comes with everything you need in a simple to use package. It's streamiined for the Piandis an ideal platform for hardware and software projects, Python programming and even asa desktop computer. z=» Say Hello to Python) Getting to Know Python MERI eeom ccm tere STEM ele kN merece od Poa e ee Reo ME Mel tel Raa eete CIMT OMe eal 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 3 Programs are lke recipes For computers. coer } Aprogramming language recipe to bake a cake could go lke this: 2 ‘Red 100 grane of butter to the bon. isallistof instructions that a computer follows. These instructions can be as simple as displaying your name or playing a music file, or as complex s building 2 whole virtual world, Python Put 100 grams of selfraisng flour in a bowl ‘Add 100 grams of butterto the bowl. ‘Add 100 miliitres of milk. Bake for half an hour. CODE eee concent ate 50 ae Sess Jtties reps apogmeanissothanciow taryutoion | msi at Centrum Wiskunde & in order. A program that describes a cake might run like this: iss joking caNe ses irra Out te “ Le-ae Mecdeuccs: | ~RSEITE a i ascunuse {iraseos ig i butter «5 BEE aeons Guido van Rossum, the father of Python. ‘bowl append four butter milk] 9 cake. cook(bonl) PROGRAM COMMANDS You might not understand some of the Python commands, lke bowl. append and cake. cook(bow), The firsts alist, the second an object; we'll look at bath inthis book. The main thing to know is that it’s easy to read commands in Python, Once you learn what the commands do, it's easy to Figure out how a program works, EBD corr erintive cue series Volume ( Getting to Know Python Cl ZEN OF PYTHON dare known as"hightevel’. Python lets you access all the power of a computer ina language ‘hiss because they fly high above the hardware (also referred to as that humans can understand. Behind all thisis an ethos called "The “the metal’). Languages that “ly close to the metal ike Assembly, Zen of Python." This a collection of 20 software principles that {are known as “low-level. Low-level languages commands read abit _influencesthe design of the language. Principles include "Beautiful tke this msg db ,0xa Len equ $ = msg isbetter than ugly’ and "simpleis better than complex.” Type import: this into Python and it wil csplay al the principles. HIGH-LEVEL LANGUAGES. Computer languages that are easy to PYTHON 3 VS PYTHON 2 Ina typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language: Pe! PTT ar futher s.7isthenewestrelease PMNSUERYM tn 2008 Python 3 arrived with several eet nets if you diga ite deepe’ Ged ee ae ait Gos epee an run Python 3 and Python 2alongside each other it's not compatible Tee iad Sue rege ee mete Su eau Dytenar so f Python 3s growing popular has mean that Gates) Pe ae ES ue as Cue cd 0) erences eer titi eee s Cie 3 companies, such as SpaceX and N 40 to programming languages for beginners and experts to: Re edu ete ees z=» Say Hello to Python) How to Set Up Python in Windows Meets eten oan eee rns ara Tua aren} PLO tet Ma Re eon Tel nea ool TITRA ELA platform of choice for building their code, it’s still an ideal starting point For beginners. INSTALLING PYTHON 3.X Microsoft Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. Thankfully, it’s an easy process to follow. FETED S2tby opening your web browser to www.python. ‘0rg/downloads/. Look for the button detailing the download lnk for Python 3.x. The latest version atthe time of ‘writing is 3.7.0 but as Python s Frequently updated this may bea different version for you. Tees eet for Pyt BRPIEPDD lckthe download button for version 3x, and save the file to your Downloads folder. When the file's downloaded, double-click the executable and the Python installation wizard wil launch. Fram here you have twa choices: Install Now and Customise installation, We recommend opting For the Customise Installation link. Install Python 3.7.0 (32-bit) pyth wind toot ae Ses ed (haan ee FETTER) Choosing the customise option allows you to specify certain parameters, and whist you may stay withthe defaults, i's a good habit to adopt as sometimes (not with Python, thankfully) installers can include unwanted additional Features, On the first screen available, ensure all boxes are ticked and click the Next button, Bren tase er rns ersten) puthé ~~ wind tak Net Cone BRTERE DD The next pave of options include some interesting additions to Python. Ensure the Associate file with Python, Create Shortcuts, Add Python to Environment Variables, Precompile Standard Library and install for All Users options are ticked, These make using Python later much easier, Click Install when you'r ready to continue. = @ Optional Features canes 20 ranean e ‘Advanced Options (emer pe arenes omemornt ree [Shope ra casos ct puthi wind wa Oras | coe How to Set Up Python in Windows Cl onfirm the installation with the ESRB Clicking on the IDLE (Python 3.7 32-bit) ink wil \Windows authentication notification Simply click launch the Python Shell, where you can begin Yes and Python will bein to instal, Once the installation is complete your Python programming jaurney, Don't worry if your version Final Python wizard page wil allow you to view the latest asit'sPython 3.x our code works inside your ome online Python 3 interface, Setup was successful ad ue FRIYD ereyou dove tensa vz window FEI 1000 econ the windows start ton aan, however it's bestto click on the link next to the and this time type: (MD, you'll be presented with the shield detaled Disable Path Lenath Limit. Thiswillaliow Python Command Prompt link, Click to get to the Windows command line o bypass 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 ype: python and press Enter ‘Again, click Yes to authenticate the process; then you can Close the installation window. © visable path enat ii Close = rand ln version of Pthon worksin 2 Inuchthe sare way asthe Shelyoucpenedin ys 10 users can now i Step 8; note the three left-facing arrows (>>>). Whilst it’s a perfectly Sawithinthestaeouton fia ine or now Enter: eXLEC) to leave and ae the Command Recently Added section pyran Prompt wi The first link, Python 3.7. “ G20) wil neh the oa Python when clicked (more mn that in a moment). To pen the IDLE, type IDLE inta Windows start ‘worabdmpublications com z=» Say Hello to Python _ ) How to Set Up Python on a Mac IF you're running an Apple Mac, then setting up Python is incredibly easy. In fact a Neem a ee eC CeN A ecl lea OOO ACER Colt aro COM RUE OL AUT] Laem Tee 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. SpenarewTeriniwindonyccingcos ERE ice one teersiont thon 0 sue? Utilities, then double-click the Terminal icon. Now Ue) case this is the download button For Python 3.6.2. center: pythonli==version. Youshouldsee"Python 25.1" and This will automatically download the latest version of Python and ‘even later, iF Apple has updated the OS and Python instalation, depending on how you've got your Mac configured, it automatically Either way, it's best to check forthe latest version. starts the installation wizard pessfcancteszowrtownnnarthonsr) — EERE wen theron maton vsrsnen kon sh downloads. Just as with the Windows setup nas) the Continue button to begin the installation. It's procedure onthe previouspages youcansee two yelow download worthtakng a momento read trough the portant information buttons oneforython 3.62, andtheotherforPthon 27.13 section incase refrencessomething that apbes your version Note, that version numbers may be different dueto the Frequent of macOS. When ready, click Continue again releases of Python, wane Se PC ROC Coa Ea Ta od The next section details the Software License Agreement, and whlst not particularly interesting tomost folks, it's probably worth a read. When you're ready, click on the Continue button once again. Finally you'te be presented with the amount of space Python will take up on your system and an Install button, which you need to click to start the actual installation ‘of Python 3.xon to your Mac. You may need to enter your password toauthentiate the installation process. The instalation shouldnt take to ong the older suai ‘Mac Mini we used in this section is a little slower than more modern Mac machines anditony tok round iy seconds forte sation Successful prompt tobe delay, ora bmpublcations com There's nothing mich le eto doin the Pyehon Sar installation wizard so you can click the Close button. Fyou now crop bckintos Terminal sesonandreente the command: python. =-verston you can see the new versions now sted, To enter the commanine version oFPyon, you need tDenterpython3. Toes. = exitO) Youneed to search nFnder for the Python IDLE Sui) when you've Found it, click it to launch and it shoud look similar to that of the Windows DLE version shown on the previous page. The only difference beng the Mac detected hardware platform sunning on Pen 60 Set PeeC2.23 Capte in bla S06) (it 39) on doris yee eapyraht,“erotta™ er slteamseC> fr save taforatin, nih" wren FUT (89) too yt eea (Older Mac versions mayhave trouble withthe ery ‘newer versions of Python, in which case you will need torevertto a previous Python 3 bul along ar youre wing Python 34 te code mihi book wil work or you Python 3.1.2 (r312:79360K, Mar 24 2010, 01:33:18) (cc 4.0:1" (apple Inc. build 5493)) on’ darwin ‘Type “copyright”, EEincormation. "credits" oF "license()" for mo How to Set Up Python on a Mac E ma Say Hello to Python How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it’s often difficult to nail down just one way of doing something. Different distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial, PEPER Fistyounced to ascertain which version of Python RINBM some Linux distros will automaticaly update is currently installed in your Linux system as we the installation of Python tothe latest versions mentioned, we're going tobe using Linux Mint 18.1 forthissection. whenever the systemis updated. To check, frst do a system update ‘As with macOS, drop into a Terminal by pressing CtrlrAtiT, and upgrade with sudo apt-get update && sudo apt-get upgrade Fle Edit View Search Terminal Help Enter your password and let the system do any updates PEPER Next enter: python!==version into the Terminal JESEMBy Once the update and upgrade is complete, you en. You should have the output relating to may need ta answer 'Y to authorise any upgrades, version 2.x of Python inthe display. Our version as you can see center: python. =-version to see if Python 3.xis undated or even below, is Python 2.7.12 installed, In the case of Linux Mint, the version we have is Python 3.5.2, whichis Fine For our purposes david@david-mint~ 1 or ew soon eee ep Fle dit View Search Terminal Help rrr) aT DMs Definitive Guide Series -Volome 33 “ How to Set Up Python in Linux Nowe Fyounantteitetaievesen cu ETA, wennee thon eer ona? will need to build Python from source. Start by. S123 tering these commands into the Terminal a ee a sudo make altinstall sudo apt-get install build-essential checkinstall sudo apt-get install Libreadline-gplv2-dev Libncursesn5-dev libssl-dev libsqlite3-dev tk-dev Libgdbm-dev Libc6-dev Libbz2-dev This coulda litle white depending on the speed of your computer ‘Once finished, enter: python3.6 ==version to check the installed latest version sudo apt-get install idte3 Pte Gradeanat mint rwnienisPynanae se six vw Sench Yeni Hee Inthe Terminal go the Downloads older by FERED oi cterces 2 9 nsats recog tin ss suai entering: ed DownLoads/. Then unzip the er dd tool to help you install more modules and extras. ‘contents of the downloaded Python source code with: tar =xvf_ Enter: sudo apt-get install python3-pip ython-3:6:2;tanerz Now erterthenewlyureppedtoler pp, hen stale check fr the test updte wth vip3 install ~-upgrade pip ‘When complete, close the Terminal and Python 3x willbe available via the Programming ection in your dstro's menu. ora bmpublcations com Python & C++ For Geginers Index. ) ora bmpublcations com ( Getting Started with Python Getting started with Python may seema little daunting at First but the language has been designed with simplicity in mind. Like most things, you need to start slowly and learn how to get a result and how to get what you want from the code. In this section, we cover the core concepts: saving and executing your code, 22 Starting Python for the First Time 24 Your First Code 28 Executing Code from the Command Line 30 Numbers and Expressions ‘ variables, numbers and expressions, user input, conditions and loops. ‘ 26 Saving and Executing Your Code 32. Using Comments 34 Working with Variables 36 User Input 38 Creating Functions 40 Conditions and Loops Python Modules —Pamela Zave (Developer, scientist and telecommunications expert) Python & C++ For Geginers z= Getting Started with Python Starting Python For the First Time Pete u an Seo uae a en Cte CI platform. The latest version of Raspbian comes preinstalled with Python 3 (version ere rea te Nenur rie el cicero STARTING PYTHON ‘We won't go into the details of getting the Raspberry Pi up and running, there's plenty of material already available on that subject. However once you're ready, fire up your Pi and get ready or coding, FETTER With the Raspbian desktop loaded, click on the FETTER for cxample, inthe Shell enter: 242 ‘Menu button followed by Programming > Python 3 After pressing Enter, the next line wil display the (IOLE). This will open the Pyehon 3 Shell, Windows and Mac users can_answer: 4 Basically, Python has taken the ‘code’ and produced the Find the Python 3 IDLE Shell from within the Windows Start button relevant output. menu and via Finder. (ie Es Sh Dg Gi nn Ue et reas or asc or are itr, PEPTIPD) The shellis where you can enter code andsee the EAB the python shell acts very much ke a calculator, responses and output of code you've programmed since code is basically a series of mathematical into Python. This is 3kind of sandbox, where you're able to try out interactions with the system. Integers, which are the infinite some simple code and processes sequence of whole numbers can easily be added, subtracted, multiplied and soon. Starting Python for the First Time E Hm EAR While that's very interesting it's not particularly exciting, Instead, try this print¢*Hello everyone!” Just enter itinto the IDLE as you did in the previous steps. ESTED Thisise little more tke it, since you've just produced your First bit oF code. The Print commands Fairly self-explanatory t prints things. Python 3 requires the brackets as well as quote marks in order to output content to the screen, inthis case the Hello everyone! bit >>> print("Hello everyone ay everyone! >>> BeTeeEAD You may have noticed the colour coding within the Python IDLE. The colours represent different ‘elements of Python code, They are: Black —Data and Variables Green-Strings Purple Functions ‘Orange~ Commands Blue— User Functions Dark Red —Comments Light Red - Error Messages IDLE Colour Coding [-eateur [use tor] examples | atte | Erar meson ora bmpublcations com BEPAETR The Pithon IDLEisa power interface, and one that's actually been written in Python using one of the avaliable GUI toolkits. Fyou want to know the many ins and ‘outs forthe Shell, we recommend you take afew moments to view www.docs.python.org/3/library/idle.html, which detaits many oF the IDLE’ Features clicking on the Highlighting tab, However, we dor't recommend that ‘as you won't be seeing the same as our screenshots. ESTED st ke most programs available, regardless ofthe ‘operating system, there are numerous shortcut keys avallable. We dont have room for them all here but within the ‘Options > Configure IDLE and under the Keys tab, you can see alist (of the current bindings. Python a cesforsesinness QE] ED) cans saneh tion Your First Code Essentially, you've already written your first piece of code with the ‘print("Hello everyone!”)’ Function from the previous tutorial. However, let’s expand that and look at SOR ter UCR ium e neces PLAYING WITH PYTHON With most languages, computer or human, it's all about remembering and applying the right words to the right situation, You're not born kno\ 1g these words, so you need to learn them. FATED you've closed Python 3 IDLE, reopen itin whichever operating system version you prefer. In the Shell, enter the Familiar following: printC*Hetlo”) BTTERED st 2s predicted, the word Helio appears in the Shellas blue tex, incicating output from a string It's Fairly straightforward and doesn't require too much explanation. Now try: primt(*22") PEPER Youcan see that instead ofthe number 4, the outputs the 2+2 you asked to be printed tothe screen. The quotation marks are defining what's being outputted to the IDLE Shel: to print the total of 242 you need to remove the quotes: print(2+2) BRPEPM You can continue as such, printing 2+2, 46442343 and soon to the Shell. An easier way sto use a variable, which s something we will cover in more depth later. For ‘now, enter: a \hatyouhave done here isassign the ters Eu?S and b two values: 2 and 2. These are now variables, ‘which can be called upon by Python to output, add, subtract, divide ‘and so.on Fors long as their numbers stay the same, Try this: printca) print(b), Ee ESB Spine nse Courrecode (CH C Your First Code PEPER Nowlet'sadda surname: surname="Hayward” print(surname) ‘You now have two variables containing a frst name and a surname €and you can print them independently be kao) og one rn te FETTER) The output ofthe last step displays the current values of both a and b individually, as you've asked them to be printed separately Ifyou want to add them up, you can usethe following: print (arb) This code simply takes the values of a and b, adds them together and outputs the result oe Ges Dean mat a FETS You can play around with different kinds of variables and the Print Function. For example, you could {assign variables for someone's name: ame="David” primtCname) wera publications com IF we were to apply the same routine as before, Using the + symbol the name wouldn't appear STEP 9 correctly in the output inthe Shell. Try it: print (name+surnane) You need a space between the two, defining them astwo separate values and not something you mathematically play around with iz ane i Hat i 3 In Python 3 you can separate the two variables iocmecntom print(name, surname) Alternatively, you can add the space ourselves: print(name+” “+surname) ‘The use ofthe comma is much neater, as you can see. Congratulations, you've just taken your First steps into the wide world of Python, Python & C++ For Geginers z= Getting Started with Python Saving and Executing Your Code While working in the IDLE Shell is perfectly fine for small code snippets, it's not designed for entering longer program listings. In this section you're going to be introduced to the IDLE Editor, where you will be working from now on. EDITING CODE You will eventually reach a point where you have to move on From inputting single lines of code into the Shell. Instead, the IDLE Editor will allow you to save and execute your Python code. ESTeERED Fist open the Python IDLE Shell and when's up, JESESJEMM You can see thatthe same colour coding isin place dlckon File > New File. This will open a new window In the IDLE Editor as tis in the Shel, enabling you ‘with Untitled as its name. Thisis the Python IDLE Editor and within it to better understand what's going on with your code. However, to you can enter the code needed to create your Future programs. ‘execute the code youneed to first save it Press FS and you get a Save...check box open, ieee cep es Treois esters forivensmnanspenss TREMP cic onthe btn te Sve boxandseets eure simple text editor with Python features, colour cued) destination where you'll save all your Python code. coding and so on; much inthe same vein as Sublime. You enter ‘The destination can be a dedicated folder called Python or you code as you would within the Shell so taking an example from the _canjust dump it wherever you lke, Remember to keep atidy drive previous tutorial, enter though, to help you out inthe Future print(*Hello everyone!") senate ET) 2 cece vee Enter a name for your code, ‘print hello’ for ‘example, and clickon the Save button. Once the Python code is saved it's executed and the output will be detailed in the IDLE Shell. n this case, the words ‘Hello everyone! BTID Thisishow the vast majority of your Python code will be conducted. Enter it into the Editor, hit F5, save the code and look atthe output in the Shell. Sometimes things will differ, depending on whether you've requested a separate window, but essentially that’s the process. I’ the process we will se throughout this book, unless otherwise stated eed teeg re yds eH ee Soya rei Tubueratitainnne ayes seared Python resource sites will be .py. Just ensure that the code is written for Python 3, wera publications com Saving and Executing Your Code Cl nz be2 ane="David” ‘surname="Hayward” printCname, surname) print Carb) IF you press FS now youll be asked to save the file, again, asit'sbeen modified from before. Let's extend the code and enter afew examples From the previous tutorial IFyou click the OK button, the file willbe ‘overwritten with the new code entries, and STEP 9 ‘executed, with the output inthe Shell's not a problem with ust, ‘hese Few lines but iFyou were to edita larger fil, overwriting can become an issue. Instead, use File > Save As from within the Editor to create a backup. [ie £6 fort Bin tote Yann He PePET BD Now create a new file. close the Editor, and open, anew instance (File > New File From the Shel) Enter the following and save itashellopy: ‘a="Python” beris” ce"cool!” print(a, b, ¢) ‘You will use this code in the next tutorial, Telapy: anapioaasrena/Pyan areas BA) (ie G8 Fama Bn Eins Hinson ep Python & C++ For Geginers Getting Started with Python Executing Code from the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made inthe GUI at the command line level. ys0 E=p Now you're atthe command line we can thon. For Python 3 you need to enter mand python3 and press Enter. Ths wil put you into th smmand line Familiar three right executing on 2, whilst the other uses the Pytho pinto the command line or Terminal on You can see that it works exactly the same, Command Line returned search - ‘and macOS users can get access their command line by clicking Utilities > Terminal DMs Definitive Guide Series -Volome 33 Executing Code from the Command Line Cl FETTER) ow enter: exit()to eave the commandline Python JEM The result of running Python 3 code From the session and return you back ta the command Python 2 command ine is quite obvious. Whilst mp. Enter the | reyou saved the sn tin any way, due s between the previous tutorial and list the available files within; hopefully you Python 3 handles the Print thon 2, the result should see the hello.py file isn’t as we expected. Using Sublime for the moment, open the hellopy file E=D From within the same Folder asthe code youre E=D Since Sublime Text isn't available forthe Raspberry ‘going to run, enter the Following into the ;, you're going to temporarily leave the Pi for the need to use the Python IDLE. With the hello.py file open, alterit to FEAETEELIENED inclu the Following — This wil execute the code we created, which to remind yous: eT ‘e"Python” print(‘Hello,”, nane) bets? c="cool!” a print(a, bs <) PEPER aturally, since this Python 3 code, using the syntax and layout that’s unique to Python 3, t only rks when you use the python3 command. iFyou like, try the same fh Python 2 by entering: python hello.py ave the hello.py file and di ktothe ‘command line, Now execute the newly saved python3 hello.py ‘The result wil be the original Python is cool statement, together ith the added input command asking you For your name, and splaying itn the command window zk Getting Started with Python Numbers and Expressions MeN aeons Selec srl i ae ave Cet el EU Tar like. Let's expand on that now and see just how powerful Python is as a calculator. You Ce R LAT ea aN eat-8 PM Bn Colm Mea eel Col N Nm Olen Lo IT'S ALL MATHS, MAN You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, maths is the driving Force behind the code. ESTER Ocen upthe culversion of Python 3, as mentioned PRIMM vou can use all the usual mathematical operations: you can use either the Shell or the Editor For the divide, multiply, brackets and so on, Practise with a time being, you'e going to use the Shelljust to warm our maths Few, For example: ‘muscle, which we beleve sa small land located atthe backoFthe 42 brain (or no = 24283 a2") BEPEED 0 the shall enterthe following: EEPEPR Youve no doubt noticed, division produces a = decimal number. In Python these are called Floats, orton pon rete Hone younedan ger ae Stasor4s5n265 —— Sppead ts deci aoe heyoucin ie Gade sa Yovcansethtrencanindesomecutelasenimben, — MB {And soon, ies rede” ae “Leaneey” far mre tara, ET) 22sec seve Youcanalso ue an operation tose the reminder Sua?5 left over From division. For example: wa Will display 3333333333, whichis of course 3.3-ecurting, Ifyou now enter: 10%3 ‘This will display 1, whichis the remainder left over From dividing 10 into 3 ( Numbers and Expressions Cl FFD wie inne tr concn format(3, ‘b’) BETETD ext uo we have the power operator, or exponentiation iFyou want tobe technical To work cut the power of something you can use a double multiplication symbol or double-staron the keyboad 203 10"10 Essential its 2x2x2 but we're sure you already know the basis, behind maths operators. Thisis how you would work tout Python, Numbers and expressions don't stop there. Python has numerous builtin Functions to work out sets (of numbers, absolute values, complex numbers and a host of mathematical expressions and Pythagorean tongue-twisters. For ‘example, to corwert a number to binary, use: ings) wera publications com ESTEE G00lean Expression isa logical statement that will, either be true or false. We can use these to compare data and test to see if i's equal to, less than or greater than. Try this in aNew File a=6 od print(1, a == 6) print(2, a == 7) print(3, a == 6 and b == 7) print(4, a == 7 and b = 7) print(S, not a == 7 and b == 7) print(6, a == 7 or b == 7) print(7, a == 7 or b == 6) print(B, not Ca = 7 and b = 6)) print(9, not a == 7 and ) Execute the code from Step 9, and you can see a series of True or False statements, depending on the result ofthe two defining values: 6 and 7. I's an extension oF ‘what you've looked at, and an important part of programming. Python & C++ For Geginers zk Getting Started with Python Using Comments MANU Retin Mi MNS N CU sce com Ita Miler neue tae hte eum nice cha citar or MM eon mec Ul cas ae dsl n #COMMENTS! Programmers use a method of keeping their code readable by commenting on certain sections. Ifa variable is used, the ‘programmer comments on what it’s supposed to do, For example. It's just good practise. STEER Sir by creating anew instance ofthe DLE Editor (Fle > New Fie and create a simple variable and print command 0-10 printC*The value of A is,”, a) Save the file and execute the code. Sas att mo tens rts te BEER fnning the code will return the line: The value of A is, 1Dinto the IDLE Shell window, which is what we ‘expected. Now, add some ofthe types of comments you'd normally see within code: # Set the start value of A to 10 o=10 # Print the current value of A print(*The value of A is,”, a) Ee cesees vee BRPIRED Resave the code and execute it. You can see thatthe ‘utputin the IDLE Shel stil the same as before, despite the extra lines being added, imply put, the hash symbol (#) denotes line of text the programmer can insert to inform them, ‘and others, of what's going on without the user being aware, Pymona42She Let's assume thatthe variable A that we've created isthe number of tvesin a game. Everytime the player dies, the value is decreased by 1. The programmer could Insert.a routine along the lines of ona=1 print (“You've just lost a life!”) printC*You now have”, a, “Lives teft!”) PEP whilst we know thatthe variable Ais lives, and that the player has just lost one, 3 casual viewer or ‘someone checking the code may not know. Imagine for a mioment that the code istwenty thousand nes long instead of just our seven, You can see how handy comments ae. (Using Comments Cl Inline comments are comments that flow asection S28 of code. Take our examples from above, instead of inserting the code on a separate line, we could use: 010 # Set the start value of Ato 10 print(*The value of A is,”, a) # Print the current value of A o=a-1 # Player lost a life! printC*You've just lost a life!”) rintC*You now have”, a, “Lives left!”) # Inform player, and display current value of A (lives) Essentially, the new cade together with comments Riad could look tke: # Set the start value of A to 10 0-10 # Print the current value of A print(“The value of A is,”, a) # Player lost a life! na-1 # Inform player, and display current value of A ives) printC*You’ve just lost a life!”) printC*You now have”, a, “Lives left! Youcan use comments incferent was. For Su ‘example, Block Comments are a large section of textthat details what's going on inthe code suchas teling the code reader what varibles youre panning on wing 4H This is the best game ever, and has been developed by a crack squad of Python experts 4 who haven’t slept or washed in weeks. Despite being very smelly, the code at Least # works really well. FERED The comment, the hash symbol, can also be used to comment out sections of code you don't want to be ‘executed in your program. For instance, if you wanted to remove the First print statement, you would use: # print(“The value of A is,”, a) [Ele ot Farmat Bun Options windows Help i Set the start value of A to 10 S10 Frnt caren wun of fe prinec'the value of A tas", a fe Blayer lose'a Iatat 4 form player. and display current value of & (lives) pranc(“vou've Just lost a.1ifel") Prane(-You now have", a, “Lives left!) You also use three single quotes to comment ‘out a Black Comment or multiline section of ‘comments. Place ther before and after the areas you want to ‘comment for them to work: This is the best gane ever, ond has been developed by a crack squad of Python experts who haven’ t slept or washed in weeks. Despite being very ‘smelly, the code at Least works really well. wera publications com zk Getting Started with Python Working with Variables We've seen some examples of variables in our Python code already but it’s always Cee nec eu Mar kee rue entry Nel oR] e VARIOUS VARIABLES. You'll be working with the Python 3 IDLE Shell in this tutorial. If you haven't already, open Python 3 or close down the previ IDLE Shell to clear up any old code. In some programming languages you're required tose dollar sign to denote astrng, whichis a variable made up of multiple characters, such asa name ofa person. in Python this ft necessary. For example, inthe Shell enter: ‘name="David Hayward?” (or use your own name, unless youre also called David Hayward). oie one ers You've seen previously that variables canbe ous?) concatenated using the plus symbol between the variable names. In our example we can use: print Cname +: *# title), The middle part between the quotations allows us to. adda colon anda spac, svasibes te connected tout spaces, so we needto ad them manual, "ie GSB Ene ee Be aie ohana" for mice ito. BPP You can check the type of variable in use by issuing the type () command, placing the name of the variable inside the brackets. n our example, this would be: ‘type Chane). Add a new string variable: ti'tLen"Descended from Vikings”. IE) 200 ce sees vee ster 4 al combine vrbles within another variable For trample, to combine bath name and ttle variables into anew variable we use: charactersname + title Then output the content of the new variable as print (character) Numbers are stored as different variables: age=44 Type (age) Which are integers, as we know, ESTER oweves you can't combine both strings and integer type variables inthe same command, 5 you would a set of similar variables. Youneed to either turn one into the ‘other or vice versa. When you do try to combine both, you get an error message! print Cname + age) C Working with Variables Cl Thispresent io problem whenyu wane to S28 work with a number that's been inputted by the user, as age + 10 won't work due to being a string variable and an integer. Instead, you need to enter: ‘intCage) + 10 ‘This will TypeCast the age string into an integer that can be worked with, yet cer it nc a py Thisisa process known as TypeCasting. The Python codes: Riad print (character +“ is “+ strCage) +“ years old.") oryoucan use print (character, “is, age, “years old.”) Notice again that inthe last example, you don't need the spaces between the wordsin quotes as the commas treat each argument to print separately >>> print (mane + age) Traceback (most recent call Last): File s", Line 1, in print’ (name sage) ‘Typetrror: can't convert “int* object to str implicitly S3BSprine (eharacter +! is"" 4 str(age) += years 91d") Davia Hayward: Desesnded from Vikings is “4 years old. D3> prane (character, "is", age, “Years old.) David Hayward: Deseended fron Vikings is 44 years old. 2B age= input (“How old are you? “) ‘le Eat shel Debuy aptont wndows lp Another example of TypeCasting s when you ask For input from the user, such as a name. for example, wera publications com pe FETED) The use of Typecasting is also important when dealing with loating point arithmetic; remember: ‘numbers that have a decimal pointin them. For example, enter: shirt=19.99 Now enter typeCshiint) and youl see that Python has allocated the number a let, because the value contain a decimal pont. When combining integers and floats Python usually converts the integer to afloat, but should the reverse ever be applied it’s worth remembering that Python doesn't return the exact value. When converting a float to an integer, Python will always round down to the nearestinteger, called truncating; in our case instead of 19.99 it becomes 19. see = ‘le Eat Shab Debug Grtens wndows Heb een 32am OF 1 04, TTY “License()* for wore information, CJ Getting Started with Python User Input ARSC ol a Mey Len ecir- Lae ORY Keele MONE eM RC od Pn er relacletc cant Chan euue on) Teese ureteral USER FRIENDLY ‘The type of input you want from the user depend greatly on the type of program you're coding. For example, a game may ‘ask for a character's name, whereas a database can ask For personal details. ETE its not already, open the Python 3|DLE Shell, and start @ New File in the Editor Let's begin with something really simple, enter: printC*Hello”) firstname=inputC“What is your first name? “) print (*Thanks.") ‘surname=input(“And what is your surname? “) Save and execute the cade, and as you already no doubt suspected, in the IDLE Shel the program will ‘ask for your first name, storing its the variable firstname, followed bby your surname; also stored ints own variable (surname). BE) 2c cesses vee FRPP) Now that we have the user's name stored ina couple of variables we can call them up whenever we want: printC*Welcone”, firstname, surname, “. I hope youre well. today.”) BE TERE DD ur the code and you can see astight isu, the fullstop after the surname follows a blank space. To eliminate that we can add plus sign instead of the comma in, the code: printC*Nelcone”, firstname, surnames. I hope you"re well today.”) You don't always have to include quoted text within the input command. For example, you can ask the user their name, and have the input inthe line below: printC*Hello. What”s your name?”) hname=inputC) userinput py -/home/pi/Documents/Python Code/us\ [Ble Edt Farmst Bun Options Windows Help iprant(Helle, what's your nase?) hane=input() (User input Cl what youve created here isa condtion, whch we SES) will cover soon. In short, we're using the input From the user and measingRagasta condo, So the ser enters Dads ther name, te guard wil alow them to pss unhindered Ete, they enter a name other than Dai, the qurdchalenges them toafiht FETTER) The code from the previous step is often regarded asbeing alittle neater than having a lengthy ‘amount of text in the input command, butit’s not arule that’s set in stone, so do as you like in these situations. Expanding on the code, uythis print(*Halt! Who goes there?’ nameinputC) ‘Be E Farat Bin Stans YnSon Hep BITEEE ADs 2 900d start to a text adventure game, perhaps? Now you can expand on t and use the raw input from the user to flesh out the game alittle: ‘if name=="David”: printC*Welcome, good sir. You may pass.”) else: printC*I know you not. Prepare for battle! ie 588 Fart in Stes roe te wera publications com ust as you learned previously, ary input from a User is automatically string, so you need to apply a STEP 9 ‘TypeCast in order to turn it into something else. This creates some interesting additions to the input command. For example # Code to calculate rate and distance print(“Input a rate and a distance”) rate = floatCinput¢“Rate: “)) fe Et Format Bin otons nds Ue Raat 8 BRTTSETBD 1 finalise the rate and distance code, we can add: distance = floatCinput(“Distance: “)) print(*Time:”, (distance / rate)) Save and execute the code and enter some numbers. Using the float{input element, we've told Python that anything enteredis a Fioating point number rather than a string Python a cerforsesinness @Yy z= Getting Started with Python Creating Functions NOMEN aUrecrs te kia curcumin Tele cy Geechee rca eet ars untclmene tase Crack une cimatu FUNKY FUNCTIONS A funct ‘works on it and then returns the result. .a command that you enter into Python to do something. Its a little piece of self-contained code that takes data, {enath or type of items. Basically, a function is a short word that's Followed by brackets. For example, len(), list) or type) A function takes data, usually variable, works on It depending on what the Function is programmed todo and returns the end value. The data being worked on goes Inside the brackets, soifyou wanted to know how many letters are in the word antidisestablishmentarianism, then you'd enter: ‘Len¢“antidisestablishmentarianism”) and the number 28 would return, 3 BETERERD You con pass variables through functionsin much the sare manner. Let's assume you want the ‘numberof letters in a person's surname, you could use the following code (enter the text editor for this example): ane=input (“Enter your surname: “) ‘count=LenCname) print (“Your surnane has“, count, “Letters in im Press FS and save the code to execute it. Python has tens of functions bul inti, Far too ‘many to get into inthe limited space available here. However, to view the list of builtin Functions avaiable to Python 3 navigate to www-does python.org/3/library/functionshtml. These are the predefined functions, but since users have created many ‘more, they'e not the oly ones avaliable. PEPID *ccitional functions can be added to Python through madules. Python has a vast range of modules available that can cover numeraus programming duties They add Functions and can be impor example, to use advanced mat import math ed as and when requited. Fr ‘tics Functions enter: Once entered, you have access to all the Math module Functions. FORGING FUNCTIONS ‘There are many different Functions you can import create Tose funcon{rom amodul eter the ne of SUz6 the module followed by a full stop, then the name ofthe Function Forinstance, sng he Math module nce youve just imported it into Python, you can utilise the square root Function, Todoso, enter: math. sqrt(16) ‘You can see thatthe code is presented as madule function(data. by other Python programmers and you will undoubtedly come ‘across some excellent examples in the Future; you can also create your own with the def command. eee eerns tion called Hello eee ert eee PPD 11s now expand the functionto accept a variable, the user's name For example. Edit your parser ina Sanna peers teats ‘worabdmpublications com Cece ats ee aed the Editor and file (File> Ne EID what you've just do Pee Pea net, ease eee: i b) result — a + by creating rincions CRI z= Getting Started with Python Conditions and Loops eo See eae Msn R neces Pea ata uh cic Reset ec isaat| cy ELenTay hey could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking if something is TRUE, then doing something else sees word=input(*Please enter a four-letter word: ERPS Now we can create anew variable, chen use the len Function and pass the word variable thraughit to ‘get the total numberof letters the user has just entered: word~input(“Please enter a four-letter word: “) word_Length=LenCword) IT) 220 eevee ERTERERD ow you can use aniFstatement to checkif the word_length variable is equal to Four and print a friendly conformation fit applies tothe rule: word=input(“Please enter a four-letter word: word_length=LenCword) ‘if word_length == 4: print (nord, “is a four-Letter word. Well done.”) ‘The double equal sign (==) means check if something is equal to something else. ‘The colon atthe end of IF tells Python that I this statements true do everything after the colon that's indented, Next, move the cursor back tothe beginning of the Editor: word=input(“Please enter a four-letter word: word_Length=LenCword) if word length == 4: print (nord, “is a four-letter word. Well done.”) else: print (word, “is not a four-letter word.”) ten rst 9 te Condonsanitoons ORE PRIM Press 5 and save the code to execute't. Enter a Fourdetter word in the Shel to begin with, you should have the reture hat it's the word is Four Now pressF5 again and rerun the program but ths time en five-letter word. T hell wil display that it's not a Fouretter word, LOOPS ESTEE "Yow expand the code to include another conditions Eventually t could become quite complex We've ‘added a condition for three-letter wor word=input(“Please enter a four-letter word: “) word_Length=LenCword: if word_length == 4: print (word, “is a four-letter word. Well done”) elif word_length = 3: print (nord, “is a three-letter word. Try again.”) else: print (word, “is not a four-letter word.”) ‘loop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same block of code a number of times, usually with the support of a condition. STEP 1 QeeerisCr Emme icencucrat as rire tint Sree b= 1 fehile x < 10:) print OO] The difference between if and while Cena eg Meena asec re nner re praia ose etter et ‘worabdmpublications com rere cae! geet pee ors ‘or x in range Ci, 10):) print Oo) Senet Cee ing the range Function: Ces Cee ee eee) Getting Started with Python Python Modules MASTERING MODULES Think of modules as an extension that’s imported into your Python code to enhance and extend its capabilities. There are countless modules available and as we've seen, you can even make your own. the builtin Fune ‘The results an errorin the IDLE Shell asthe Althousha a? are limited. The use of nised or installed in tomate more sophisticated programs. Asyouare aware, modules” Python Toistallam CP istals Packages). Bre Python spt that are ported, suchas mport math Close downthe DLE Shelland opin command prompt o Terminal session, At an elevated admin command prompt, enter pip install pygame ime examoe.Soly, other odes aren awa avlable 4 suse can serch or CMD vite Stat ton an ‘example on non-Pi platforms isthe Pygame madule, which contains click the result then click Run as Administrator. Linux and Mac users ‘many functions to help create games. Ty import pygame, can use the Sudo command, with sudo pip inst al package. DMs Definitive Guide Series -Volome 33 Python Modules E Hm clesteconmardsemetcteraand —— EERERI) tte ocean be imparidwatinarce SUED esnch che OLE shel when you now enter: SEED 5 oendour example use ‘mportpygane the ode wlbemprtedinathe coe ‘tout ay problems Yu'lfind hat most code dowicadedorSMPOTENtandon copied From the Internet will contain a module, mainstream oF _ ‘unique, these are usually the source of errors in execution due to for I in range(S): them Belg ising Drint Crandon. randint2, 2599 Bean prinkcoath. pi FETTER The modules contain the extra code needed to PEED The result isa string of indo numbers Followed achieve a certain result within your own code, 2s by the value of Pas pulled from the Math module ‘we've previously experimented with. For example: Using the print(math.p function. You canals pullin certain : fanaons froma medley ung the fom and pat commands, ‘import: random funaio brings inthe cade fromthe Random Number Generator module . . You can then use this module to create something like: ‘firominendomEapoeRnonaLre os for i in range(5): for i in range(10): = print(random.randint(1, 25)) aaeneeniemmemn! Dive Sasa PRPIIEDD This code, when saved and executed, will displayten MBI this helos create amore streamlined approach to random numbers from to 25. You can play around programming. You can also use import module*, withthe code to display more orless, and from agreat orlesser which wll mport everything defined within the named module. range. For example: However, t's often regarded as a waste of resources but it works ED nonetheless Finally, modules can be imported as aliases: for i in range(25): ‘import math as m printGrandom.randint(1, 100)) print¢m-pi) (Of course, adding comments helps to tll others what's going on. Dt Cevtibeaneanienati BF =e x pmo senses Prensa Working Wie . = “The most important single aspect of software development is to be clear about what you are trying to build.” ~ Bjarne Stroustrup (Developer and creator of C++) ora bmpublcations com ( working with Data Cl Data is everything. With it you can display, control, add, remove, create and manipulate Python to your every demand. Over these coming pages we look at how you can create lists, tuples, dictionaries, multi-dimensional lists; also how you can use them to forge exciting and useful programs. Then, you can learn how you to use the date and time Functions, write to files in your system and even create graphical user interfaces that take your coding skills tonew levels and into new projectideas. 46 Lists 48 Tuples 50 Dictionaries 52 _ Splitting and Joining Strings 54 Formatting Strings 56 DateandTime 58 Opening Files 60 Writing to Files 62 Exceptions Python Graphics Lists are one of the most common types of data structures you will comes across in Python. A list is simply a collection of items, or data if you prefer, that can be accessed as a whole, or individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. A list can be strings, integers and also v and lists within lists. les. You can even include functions in lists, Alistisa sequence of data values called items. You create the name of your list followed by an equals sign, then square brackets and the items separated by commas, ‘note that strings use quotes numbers = [1, 4, 7, 21, 98, 156] mythical_creatures - [“Unicorn”, “Balrog”, “Vampire”, “Dragon”, “Minotaur”) BRPISPR Once you've defined your list you can call each by referencing its name, followed by a number. Lists start the first item entry s 0, followed by 1,2, 3 and soon, For example: punbers Tocallup the entire contents ofthe lst. punbers[3] To callthe third From zero item inthe lst (21 in this case). ET) 2s ec seve You can also access or index, the lat item ina list by Using the minus sign before the item number 1}, for the second to last item with [2] and so on. Trying to reference an item thatisntin the st, such as 10] will return an error punbers[=1] mythical_creatures[~4] ESPEPD Sicingissimiartoindexing but you can etrieve ‘multiple tems in alist by separating tern numbers witha colon. For example: unbers[1:3] \ill output the 4 and 7, being item numbers 1 and 2. Note thatthe returned values don't include the second index position (as you ‘would numbers[t:3] to retuin 4,7 and 21). You can update items within an existing list, remove items and even jon sts together. For example, to Join two lists you can use: everything = nunbers + mythical creatures ‘Then view the combined list with: everything Css CE Youcanvew what canbe done wth ists by entering S28 dir(list) Into the Shell. The output is the available functions, for example, insert and pop are used to add and remove itersat certain positions To insert the number 62 at item index 4 nunbers-insert(4, 62) Toremove it: numbers .popC4) PTT ers can be added toast by entering nunbers=nunbers+[201] Or or strings: mythical_creatres=mythical_creatures+[“Griffin”] ‘Or by using the append function: mythical_creatures..append(“Nessie”) ‘numbers .append(278) Removal of tems can be done in two ways. The first del nunbers(7] Alternatively, by item name: mythical_creatures. renoveC“Nessie”) wera publications com You also use the lst Function to break a string down into its components. For example STEP 9 Listc*Davia”) Breaks the name David into'D, 2, toa new lis: nave=1ist“Dovid Hayward”) name ge [44] user = none + age user id. Thiscan then be passed FEET) 82520 on that, you can create a program to store someone's name and age as alist: pane=inputCWhat”s your name? “) TnameslistCnane) ‘age=intCinput "How old are you: “)) Lage=[oge] user = Inane + lage ‘The combined name and age lists called user, which can be called by entering user into the Shel, Experiment and see what you can do. Python a cerforsesinness Qi Tuples are very much identical to lists. However, where lists can be updated, deleted or Cee elu se ne chute cea ica perfect for storing fixed data items. THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the prograr special but they're also used for example, in an adventure gam is intended to do. Normally, a tuple is reserved for something ‘where non-playing character names are stored. BITE *turle is created the same way as.list but in this [EREESEEMM You can create grouped tuples into lists that contain instance you use curved brackets instead of square ‘multiple sets of data. For instance, here isa tuple «called NPC (Nor-Playable Characters} containing the character name brackets. For example: tronths=C*January"si"February”sesMarchsesaprinms _2ndthelr combat rating For an adventure game “May”, “June”) NPC={C*Conan”, 100), (*Belit”, 80), (“Valeria”, months 95)] EETeEED estas with tists, the tems withina named tuple can [RRESSWAM Each of these data items can be accessed as a be indexed according to their position inthe data whole by entering NPC into the Shell or they can be Indexed according to their postion NPC(O). You can also index the range, ie: months[0] Individual tuples within the NPC lst: rmonths[S] NPCtO] CLI However, ay atternpt at deleting or adding to the tuple willresult wil display 100, Jinan errorin the Shel, ED coms vetntive cide seris- volume 33, Tes woth noting tat when referencing mile Eu?S tuples within a list, the indexing is slightly different from the norm. You would expect the 95 combat rating ofthe character Valeria to be NPCIA][S], but’s not. t's actualy: NPCC2I01] oe Ea pty os nt ube FETT This means of course that the indexing Follows thus: o mm a0 2 a1 20 1 2a 10 Which as you can imagine, gets ate confusing when you've got a lot of tuple data to deal with, PEPER tuples though utilise a feature called unpacking, where the data ters stored within atuple are assigned variables First create the tuple with two items (name and ‘combat rating): NPG=C*Conan”, 100) wera publications com Now unpack the tuple into two S28 corresponding variables: (Chane, conbat_rating)=NPC ‘You can now check the values by entering name and combat_rating FETED emember, as with lists, you can aso index tuples Using negative numbers which count backwards from the end of the data list. For our example, using the tuple with multiple data items, you would reference the Valeria character with NPctz][-0] You can use the max and min anctionstofnd the Sup highest and lowest values of a tuple composed of numbers, For example numbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) The numbers canbe integers anc oats To output the highest and lowest se print (maxCnunbers)) print (minCnunbers)) Dictionaries Lists are extremely useful but dictionaries in Python are by Far the more technical way of dealing with data items. They can be tricky to get to grips with at first but you'll soon Ite CLeoL PURO N ol mon Keele a KEY PAIRS. ‘A dictionary is ike a list but instead each data item comes as a pair, these are known as Key and Value. The Key part must be ‘unique and can either be a number or string whereas the Value can be any data item you like. ERTESERD 2:5sav you want to create a phonebook in Python, You would create the dictionary name and enter the data in curly brackets, separating the key and value by 8 colon Key:Value. For example: phonebook={“Enma”: 1234, “Daniel”: 3456, 6789} “Hannah”: Just. as with most lists, tuples and so on, strings need be enclosed in quotes (sinole or double), whilst integers can be left open. Remember thatthe value can be either a string or an integer, youjust need to enclose the relevant. fone in quotes: phonebook2={"David”: “0987 654 321”} ET) secs veee ‘swith ists and tuples, you can check the contents ofa dictionary by giving the dictionary @ name: ‘phonebook inthis example. This wil display the data items you've entered ina similar Fashion toa lst, which you're no doubt familar with by now, BEPEPM the benefit of using a dictionary is that you can enter the key to index the value. Using the ‘phonebook example from the previous steps, you can enter: phonebook “Enna” phonebookf"Hannah”] value items ike: phonebook[“David”] = phonebook ‘Adding to a dictionary easy too. You can include ‘a new data item entry by adding the new key and You can also remove items from a dictionary by Issuing the del command Followed by the tem's key, the value wil be removed as well, since both work asa pair of data items: Riad del. phonebook[“David”] Tang thisasep ther how bout ceting usd piece of code that will ask the user for the dictionary key and value ters? Create a new Editor instance and start by coding in anew, blank dictionary: phonebook={} wera publications com ‘Opn Cll Dictionaries Next you needto defn the userinputs and S28 variables: one for the person’s name, the other for their phone number (let's keep it simple to avoid lengthy Python code): ane=inputC*Enter nam unber=intCinputC“Enter phone nun » aT STEP 9 Note we've kept the number as an integer instead (fa string, even though the value can be both ~aninteger ora string, Now you need to add the user's inputted variables to the newly created blank dictionary. Using the same process asin Step 5, you can enter: phonebook{name]) = number pret)» mater Now when yousave and execute the code, Python Sup will ask fora name and a number. It will then insert. ‘those entries into the phonebook dictionary, which you can test by entringinc the Shel phonebook phonebook[“David") IF the number needs to contain spaces you need to makeitastring, ‘so remove the nt part ofthe input. Splitting and Joining Strings ANA aKel tare ROUiea Ke eM Aenea e911 WCE TUS TaN Lele OLR UT AU Te Colel oc Te) come across long sets of strings. A useful skill to learn in Python programming is being able to split those long strings For better readability. STRING THEORIES You've already looked at some list Functions, using insert, .remove, and .pop but there are also Functions that can be applied tostrings. ESTED te main tootin the string function arsenals spt. With ityou'e able to split apart string of data, based on the argument within the brackets. For example, here's string with three ters, each separated by a space: ‘text="Daniel Hannah Enna” BRTISPRD Now let's turn the string ntoa list and split the content accordingly: names=text-splitC* *) Then enter the name of the new ist; names, tosee the three items, Es ec seve BTSED ote that the text spit part has the brackets, uotes, then a space followed by closing quotes ‘and brackets. The space isthe separator, indicating that each lst ‘tem entry is separated by a space. Likewise, CSV (Comma Separated Value) content has a comma, so you'd use: texts” January, February,March, April May, June” months=text.split(*,") months EEPEPR Youve previously seen how you can split a string into individual letters asa list, using a name: name=ListC“David”) name The returned value is'D,'a, Whilstit may seem a little useless under ordinary circumstances, it could be handy For creating aspeling game for example BSED The opposite of the split function is join, where you will have separate items na string and can join them all together to form a word or ust a combination of items, depending on the program you're writing. For instance: ‘alphabet="". join([“a","b","c","4","e"1) ‘alphabet. ‘This will display ‘abcde’ the Shell. You can therefore apply join to the separated name you made in Step 4, combining the letters again to Riad form the name: ‘name="". joinCnane) ‘name C Splitting and Joining Strings Cl stop, a hyphen or whatever you ike: colours=[*Red”, “Green”, “Blue”] Join(colours) STEP 9 ‘titLe="conan the cimmerian” title.capitalize() title.titleo ‘swith the spit function, the separator doesn’t have tobe a space, itcan also be acomma, 2 full ‘There's some interesting Functions you apply toa string, such as.capitalize and itl, For example ‘We've joined the string back together, and retained the lst called fname, passing itthrough the join Function. You can alot osc operators on tring, Sup ‘with the ‘in’ and ‘not in’ Functions. These enable ‘Agood example of using the join Function is when you have a ist of words you want to combine into a sentence: you to check iFastring contains (or does not contain) a sequence ListeL“Conan”, “raised”, “his”, “mighty”, “snora”, characters “and”, “struck”, “the”, “denon”] inessage="Have a nice day” texte” text Note the space between the quotes before the join Function (where there were no quotes in Step 6's oi). *.joinclist) “nice” in message "bad? not in message “day” not in message “night” in message Se ae — rsam coe | wera publications com Python & C++ For Geginers zk Working with Data Formatting Strings When you work with data, creating lists, dictionaries and objects you may often want rune ee Ure Mane rere faeces PR eIoa anak keoulel ures STRING FORMATTING Since Python 3, string Formatting has become a much neater process, using the format Function combined with curly brackets. It’s a more logical and better formed approach than previous versions. BRPEE RD the basic formatting in Python is to call each ESTISEDD You can of course aso include integers into the mix: variable into the string using the curly brackets = nunber= ‘name="Conan” printC“{} of {} was a skilled mercenary, printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a ”. format name) merchant..”.format(name, place, nunber)) Remember to close the print Function with twa sets ‘There are many different ways to apply string af brackets, as youve encased the variable none, formatting some are quite simple, as weve shown and he pint function n another. Youcan nude multiple cases of youhere; others canbe significantly more complex. all depends String Formatting na singe prin Function Using Modules ) Calendar Module WORKING WITH DATES The Calendar module is bul calendar as a Windows administrator or sudo pi into Python 3. However, if For some reason it's not installed you can add it using pip install install calendar For Linux and macOS. Launch Python 3 and enter: import calendar to callup the module and its inherent Functions, Once it’s loaded into memory start by entering sep=calendar.TextCal endarCcalendar.SUNDAY) sep.prmonth(2019, 9) [ee 3.0 2017 fe) on aga ‘ype Soy igh Sredts? or Scene) for sore inforation. S33 sepsealendar:Toxtcalondar (calendar SUNOAY) 533 stp: prnonth( zou, 8) FRPIPB You can see thatthe days of September 2019 are displayed in a wal calendar fashion. Naturally you can change the 2019, 9 part ofthe second line to any year and month you want, a birthday For example (1973, 6). The first ine configures TextCalendar to starts weeks on a Sunday; you can opt for Monday ifyou prefer. oe git Sot pug ten rdw te Se 32 SS S$ —2 ter ED) 22sec seve There ae numerous Functions wthin the Calendar Su? ‘module that may be of interest to you when forming your own code. For example, you can cisplay the number of leap years between two specific years ‘Leaps=calendar.leopdays(1900, 2019) printCleaps) ‘The result is 29, starting from 1904 onward (ytion 35-3 (dofutt, sep 27 2018, 1775) sta" Or "License()" for mre safornation import. calendar print(>>>>55>>>>Leap Year Calculator Using Modules OS Module INTO THE SYSTEM ‘One of the primary Features of the OS module is the ability to list, move, create, delete and otherwise interact with files stored on the system, making it the perfect module for backup code. ESTEE You can start the OS module with some simple PEPER) The windows outputis different a that's the Functions to see how interacts with the operating current working directory of Python, as determined system environment that Python is running on. Fyou're using Linux by the system; as you might suspect, the os getcwd() Function is Cr the Raspberry Pi, try ths: ‘asking Python to retrieve the Current Working Directory. Linux users imma wise something alongthe sae ne the Raspberry, wi home=os..getcnd() print Chome) PEPER The returned result from printing the variable home | FB yer another interesting element to the OS module, isthe current user's home folder on the system. Isis ability to launch programs that are installed inour example that’s home/p:it wil be efferent depending on _inthehost system. Fo instance, if you wanted to launch the the user name you login as and the operating system you use. Chromium browser Fram within a Python program you can use For example, Windows 10 wil output: C\Program Files (86) the command Python36-32 ee a browser=os.system(*/usr/bin/chromium-browser”) BETS The os-system( function is what allows interaction with external programs; you can even call up previous Python programs using this method. You wil obviously need to know the Full path and program file name fort to work successfully, However, you can use the Following: import os os.system(‘start chrone “https://mw. youtube. com/ feed/misic””) PETER For step 5's example we used Windows, to show that the OS module works roughly the same across allplatforms. n that case, we opened YouTube's music Feed page, so itis therefore possible to open specific pages: import os os.system(‘chromium-brouser “htty ‘bdmpublications..con/”*) ESTEGEAD "Note inthe previous step’s example the use of single and double-quotes. The single quotes encase the entire command and launching Chromium, whereas the double {quotes open the spectied page. You can even use variables to call multiple tabsin the same browser: import os ‘0=(*chromium-browser “http: //bdnpubli cations: con””") b=C‘chromium-browser “http: //mm.google..co.uk”*) os.system(a + b) The ably to morn recor folders STEPS you prefer, is one of the OS module's best Features. For example, to create anew directory you can use: import os (08 .mkdir(*NEW") This creates a new directory within the Current Working Directory, named according to the object the mkdir Function, import os (os. renameC*NEW”, “OLD” To delete them: import os os. rmdir(“OLD”) You can also rename any directories you've created byentering import os, shutil, time root_src_dir = r?/home/pi/Documents? root_dst_dir = ‘/home/pi/backup/? + time.asctimeC) for srcdir, dirs, files in os.nalk(root_src_dir): dst_dir = src_dir.replace(root_src_dir, root_ dst_dir, D if not os.path.exists(dst_dir): os.makedirs(dst_dir) for file_ in files: src_file = 0s.path.join(sre_dir, file_) dst_file = 0s.path. joindst_dir, file_) if 0s.path.existsCdst_fle): 0s. renoveCdst file) shutil.copy(srefile, dst_dir) print(*ssssssss5sBackup completecceccccece”) ora bmpublcations com => Using Modules ) Random Module RANDOM NUMBERS ‘There are numerous Functi Python programs. 's within the Random module, which when applied can create some interesting and very useful FE cc yancrosicircesoincn BR ows enna rosicopeoxsccapeny ‘import random random . choice [“Conan’ printCrandomint(@,5)) “Valeria”, “Belit”]) ‘This wil display one ofthe names of our adventurers at random, whichis a great addition toa text adventure game, FR oc conc times and it wil display diferent integer values from the set of numbers given, zero to five, The || pumrmnesourne seeesssseeee ecavsscenasdu overall effect, although pseudo- ff)» puma mane.) Sea eaitea rare [gone PEPTSER) You can extend the previous example somewhat by faciacebem having random. choice() select from alist of mixed ‘average programmer to utlse in : ” ‘memset variables. For instance: their code, renner ae Iste[“David”, 44, “BOM Publications”, 3245.23, “Pi”, True, 3.14, “Python”] ‘rndetandom.choiceClst) For a bigger set of numbers, including floating = BALD irc vtues youconextendtherangebyusingthe Primecend) multiplication sig: import random printCrandom.random() *100) rae Ta aw TTT ‘ill display a Floating point number between 0 and 100, othe tune —_|="y"han Tt “Heme fr sre stems ‘of around Fifteen decimal points. fo ain ED 2s ect seve Interesting youcan ao ea function wine SUES Random module to shuffle the items in the list, thus ‘adding a litle more randomnessinto the equation: random. shuffleCist) print(ist) ‘This way, you can keep shuffling the list before displaying a random item From. Using shuffe, you can create an entirely random lst (of numbers. For example, within a given range: Rico ‘import random Ast=[[i] for I in range(20)] random. shuffle(Lst) print(lst) Keep shuffling thelist and you can have a different selection of items From 0 to 20 every time. You can also select a random number from agiven import random for i in range(1o): printCrandom.randrange(®, 200, 7)) Results wil vary but you get the general idea as to how it works. wera publications com - ( Random Module cl Letsuse an example lee of ode whch ipsa Suz virtual coin ten thousand times and counts how ‘many times it wil land on heads or tals: import random ‘output={"Heads”:0, “Tails? coin=List (output. keys) for i in range(10000): ‘output Lrandom. choi ceCcoin)]}+=1 print(“Heads:”, output{“Heads”]) print(“Tails:”, output[“Tails”]) 20} Here's an interesting piece of code. Using atext file containing 466 thousand words, you can pluck ‘user generated number of wards fram the file (text file Found at: ‘www github.com/dwyl/english-words) ‘import random print¢‘s>>>>>>>>>Random Word Finder for w in random.sample(words, wds): print cn) print¢*= Zz »y Using Modules ) Tkinter Module GETTING GUI ‘Tkinteris easy to use but there's a lot more you can do with it. Let's start by seeing how it works and getting some code into it. Before long you will discover just how powerful this module reall PEPE Tiinteris usually built into Python 3. However iFt's available when youenter: import tkinter, then youneedto pip install. tkinter from the command prompt. We can start to import modules differently than before, to save on typing and by importing all their contents import tkinter as tk from tkinter import * PEPPER snot recommended ta import everything from a ‘module using the asterisk but it won't do any harm normally. Let's begin by creating a basic GUI window, enter: wind=TkO This creates a small, basic window. There's nat much else to do at this point but click the Xin the corner to close the window. BED 2s ect seve TEP btn. pack btn[“text”J="Hel1o everyone!” ‘The first line Focuses on the newly created window. Click back into the Shell and continue the ather lines You can combine the above into a New File ‘import tkinter as tk from tkinter import * btn=Button() btn. pack btn[text”]~"HeLlo everyone!” ‘Then add some button interactions: def clickO: printC*You just clicked me!”) btn{conmand’”J=click 7 (ie Ea Famat Bn Spine nds ep fem Tkinter Modul: cl (Tkinter Module Save and execute the code from Step S anda window appears with Hello everyone! inside. IFyou lick the Hello everyone! button, the Shell will output the text You just clicked me? It's simple but shows you what can be achieved witha Few lines of code. i = PPT 01 can also cisplay both text and images within 2 Tkinter window. However, only GIF, PGM or PPM Formats are supported. So find an image and corwert it before using the code, Here's an example using the BOM Publishing logo: from tkinter import * root = Tk) logo = PhototnageCile="/hone/pi/DownLoads/B0M_Logo. aif) wi = Label(root, root.title(“BDM Publications”), {nage=logo).pack(side="right") content = “Fron its humble beginnings in 2004, ‘the BDM brand quickly grew from a single publication produced by a tean of just tno to one of the biggest ‘names in global bookazine publishing, for two simple reasons. Our passion and conmitnent. to deliver the very best product each and every volune. While ‘the conpany has grown with @ portfolio of over 250, publications delivered by our international. staff, ‘the Foundation that it has been built upon renains ‘the sane, which 1s why we believe BOM isn’t just ‘the first choice it's the only choice for the snart w2 = Label(root, justifyeLEFT, ade = 10, text=content). pack(side="Left” root mainoop() The previous code's duite weighty, mostly due to the content variable holding apart (oF BDM's About page from the company ‘website. You can, ‘obviously change the tent, the root.title es ‘and the image to suit Easier a eee ora bmpublcations com FRPP) You can create radio buttons too. Ty: from tkinter import * root = TkO v = IntvarQ LobetCroot, root.titleC*Options”), text=”""Choose 4 preferred Language:”””, justify = LEFT, padx Radiobutton¢rost,, text="Python”, padx = 20, variable=v, value#1).packCanchorsit) RadiobuttonCrost , text="CH”, padx = 20, variable=v, value=2).packCanchor=W) maintoop( FETED) You can also create check boxes, with buttons and utputtto the Shell from tkinter import * root = TkC) def var_states() printC*arrior: %d,\nMage: #4” % (varl.get(, var2.getQ)) LabelCroot, root.titleC“Adventure Gane”), texte">>>>2>>>>>Vour adventure rolecc File) and create a True/False while loop: import pygame from pygane.locals import * pygane. init©) ‘gamewindon=pygane.display.set_nodeC(800,600)) pygame. display. set_caption(“Adventure Game”) fer ere infoacin runningsTrue hile running for event in pygane.event.get(). if event. type==QUIT: running=False Pygane. quitC) fle Ese Feat Aun Gotone Widows Hep PEPIIE BD 2rs create asimple game ceady wi iatitle Prome:display-seicaption( 800,509) ‘gamewindow=pygane. dispLay.set_node((800,600)) pygame. display. set_caption(“Adventure Gane”) that after the first line is entered, you need to click hell to continue entering code; also, you can change thing you tke Tunningersise PramesquitO ( Pygame Module cl ESTEE the Pygame window sil won't z close don't worry, it'sjusta ] discrepancy between the IDLE (whichis written with Tkinter) andthe Pygame module. I you run your code via the command line, it closes perfectly well You're going to shift the code around a bit now, ‘img=pygame. image. load(“/home/pi/Downloads/ running the main Pygame code within awhile loop; spritel.png”) itmmakes it neater and easier to follow. We've downloaded a graphic touse and we need to set some parameters for pygame: import pygame pygane. init© def spritecx.y): ganewindow.blitCimg, (x,y) x=(800*0.45) ‘y=(600*0.8) estan! gamewindow.fLLCwhite) while running: sprite(x,y) gamewindow=pygane. display. set_node(800,600)) _ ygane. display.set_caption(“Adventure Gone”) for event in pygane.event..get¢ black=(0,0,0) if event. type==pygane.QU white=(255, 255,255) Taport pam =(500"0.45) From ybame Locals inport * yr(soor0:8) ganenindon.fillUvhite) runningeteue Spritetsy) Pram display updater vile running: garewindow-pygane. display set_mode(600.600)) Brome dispiay-set-caption( adventure. cone") Elscee(o.0°0). {or evant in pygane event. get smnitent255 235,255) ie event. fypecsdutr “ngspyeme. image load(“/hone/ps/Ovmnleads/spritel.eng") innings aise prasnesauitO ef sprstece.yy: Senindoncb1sec img, (4.99) => Usi 9 Modules ) RPT RD 'ow we can change the code aroundagain, this -imgspeeds0 time containing a movement option within the while loop, and adding the variables needed to mave the sprite ‘around the screen: while running: for event in pygane.event.get(): if event. type==QUI import pygame running=False From pygane.tocals import * = : ae if event. type == pygame. KEYOONN: if event. key=pygame.K_LEFT: runming=True xchange=-5 ganevindon=pygane di splay.set_nodeC(800,600)) | — pygane.display.set_caption(“Adventure Gane”) black=(0,0,0) whites(255,255,255) ‘img=pygame image. Load¢“/home/pi /DownLoads/spritel. if event. type==pygame. KEYUP: if event. key==pygame.K_LEFT or event keye=pygame.K RIGHT: xchange=@ png”) def spritecx.y) x #= xchange ganenindon.bLitCing, x.y) ganewindon fill white) sprite(x,y) x=(8000.45) y=C600°0.8) pygone. di splay.updateC) xchange-0 pygane. quit PEPER) ony the code down and using the left and right arrow keys on the keyboard you can move your sprite across the bottom of the screen, Now, itlooks lke you have the makings oF a classic arcade 2D scroller inthe works [zee Pareto rome init) “romingersise BD) 20s cases tne ( Pygame Module cl Youcan now implementa ew additions and tse SAAD some revousttoral code Thenev demensare the Subprocess medule, of which oe function allows usto launch a second Python scrip from within anther; and were going to create a New File called pygametst py inport pygane inport time Inport: subprocess pygane.init© screen = pygame.display.set_mode((800, 250)) Clock = pygane. time. Clock) font. = pygane. font:.FontNone, 25) def text_generator(text): tapleLse for letter in text: ‘tmp += letter if letter I= yield tmp Class DynamicTextCobject): def _init_(self, font, text, pos, autoreset=False): self.done = False self. font = font self. text = text self._gen = text_generator(self.text) self.pos = pos self.autoreset = autoreset self.updateQ) def reset(self): self._gen = text_generator(self text) self.done = False self.updateQ) def updatecself): if not self.done: try: self.rendered = self. font. render(next(self._gen), True, (0, 128, @)) except StopIteration: self.done = True time. sleep(10) subprocess.Popen(“‘python3 /home/pi/Documents/ Python\ Code/pyganel.py 1”, shell=True) def dranCself, screen): screen. blit(self.rendered, self.pos) text-C*A long time ago, barbarian strode fron the Frozen north. Svord in hand...") message = DynanicTextCfont, text, (65, 120), autoreset-True) wile True: for event in pygane.event.get( if event.type == pyoane. QUIT: break if event. type == pygane.USEREVENT: message. updateQ) else: screen.fill(pygane. color Color¢ black") message. draw(screen) ora bmpublcations com an aceon pygane. display ip clock. tick(60) continue break pygane.quit© ‘When you run this code it wil display along, narrow Pygame window with the intro text scrolling to the right. After a pause often seconds, itthen launches the main game Python script where you can move the warrior sprite ‘around, Overall the effect quite good but there's always room for improvement. Zz »y Using Modules ) Create Your Own Modules BUILDING MODULES Modules are Python files, containing code, that you save using a py extension. These are then imported into Python using the now familiar import command. def timestwoC: return x * 2 def timesthree(x): return x * 3 def square(x): return x * x def poner(x,y): return x ** y PPI R under the above code, enter functions to callthe code: print (timestwo(2)) print Ctimesthree(3)) print CsquareC4)) print Cponer(S,3)) Save the program as basic math py and execute itto get the results. ee CE | re renetnpeynd | eee | PEPTIED) (‘Yow you're going to take the Function definitions ‘out ofthe program and into a separate file. Highlight the Function definitions and choose Ect > Cut. Choose File > New File and use Edit > Paste in the new window. You now have two separate files, one withthe function definitions, the other with the Function cals. BSTeEE DD | younow tryand execute the basic math.py code again, the ecror‘Name€rror: name ‘timestwo' is not defined’ willbe displayed, This is due tothe cade no longer having access to the function definitions. Retuto SNP the newly rested window contining the Function deitons, and lke» Sve As Name ths minimath py and save inthe tae location asthe inal basic mathpy oroaram. Now close the minmathgy window sothe baie mathoy window ietopen (Create Your Own Modules cl FTE 2k tothe basic mathpy window: atthe top of the FEREESIEEM Finally, you can now create arange ofistatements code enter: to determine what to do with the number and neers utlise the newly created function definitions if choice == ‘1: is wllimportthe function definition as a module Press F5 to Swonlomatetepooniosetneden EE STAASSPOCTNDD elif choice == ‘2° eee printCtimesthreeCnunt)) elif choice = ‘3? print(square(num1)) elif choice == “4°: num2 = intCinput(“Enter second number: “)) se MCPonErCren, a2)) print(“Invalid input") (ie at Farat at tos Wows te FPIIED You can now use the code Further to make the programa little more advanced, utilising the newly created module to itsFull.include some user interaction. Start by 2 | using namespace std; 3 | void main() 4 |D{char ch; 5 cout<<"Enter a charater to check it is vowel or not"; 6 cin>>ch; 7 switch (ch) 8 9 case'A': 10 cout< App Store. In the Search box enter Xcode’ then turnsinto install App. Enter your Apple ID {and press Return. There are many suggestions filing the App Store and Xcode begins to download and install. may take sometime ‘window but isthe Fist option, Xcode, that youneed toclickon. depending on the speed of your Internet connection. PEPIIP DD Take a moment to browse through the app's PEEP RD wren the instalationis complete, click on the Information, including the compatibility to ensure (Open button to launch Xcode. Click Agree to the you have the correct version of macOS. Xcode requires macOS licence terms and enter your password to allow Xcode to make 10.12.6 or later to install and work ‘changes to the system. when that fs done, Xcode begins to install, in ‘additional components ELD coms detnive cui Series-Volome 33 / (_ Howto Set Up C++ on a Mac Cll Tes that you've worked on; with a fresh install though, this is blank. Welcome ta Xoode Sr eke FETED tert by clicking on Create New Xcode Project; this ‘opens a template window to choose which platform you're developing code For. Click the macOS tab, then clckthe ‘Command Line Tool option. Click Next to continve. Ean aoe 1% Fillin the various Fields but ensure that the Language option atthe bottom i set to C++; simply ‘choose it from the drop-down list. When you've filed inthe field, ‘and made sure that C++ isthe chosen language, clickan the Next button to continue The next step asks where to create a GitRepository forall your Future code. Choose a location on your ‘Mac, or a network location, and click the Create button. When you've done all that, you can start to code. The lefthand pane details the files used in the C++ program you're coding, Click on the rmain.cpp file inthe lst FETED) You can see that Xcode has automatically completed a basic Hello World program For you. While itmay not make much sense at present, you wil discover more as you progress, the content i just Xcode utilising what's available on the Mac. REET T erry coe FETE ERT When you wantto run the code, click on Product > Run. You may be asked to enable Developer Mode ‘on the Mac; this isto autharise Xcode to perform Functions without needing your password every session, When the pragram executes, the output i displayed at the bottom of the Xcode window. wera publications com z= Say Hello to C++) How to Set Up C++ in Linux Linux is a great C++ coding environment. Most Linux distros already have the essential Leola Toney Cel re ene Reon eM dee ole E oa (na cole entering code into, including colour coding. There's also tons of extra software available to help you out. LINUX++ IF you're not familiar with Linux, then we recommend taking a look at one of our Linux titles From the BOM Publications range. IFyou have a Raspberry Pi, the commands used below work just fine and For this example we're using Linux Mint. FETED The Fist step isto ensure Linux is ready For your C++ cade, 0 check the system and software are up ta date. Open a Terminal and enter: sudo apt-get update && sudo apt- ‘get upgrade. Then press Return and enter your password. These ‘commands update the entire system and any installed software, PPP D ost Linux cistras come preinstalled with al the necessary components to start coding in C#4; however, it’s always worth checking to see if everything is present. Stil within the Terminal, enter: sudo apt-get install build-essential and press Return F you have the right ‘components nothing is installed; iF you're missing some are installed by they Siac ral DMs Definitive Guide Series -Volome 33 Amarin, tats eveything aleady for you SUE? to start coding. Here's how to get your first C++ program upandrunning.nLnux Mint the man tert dre th you ean aun by clkng onthe Menu an typing ed nto the searhbarCkonthe Text Etor button inte ighchand pane toopenit EEE Xd, or any other text editor you may be using, enter the lines of cade that make up your C++ Hello World program. It's alitle diferent to what the Mac produced: include int main) { Uy first C+ program std::cout << “Hello World! pean-jxoojaa ( How to Set Up C++ in Linux Cl When youve entered your cde click Fle> Save As Before you can execute the Cr fle younedto Suz75 and choose a folder in which to save your program. sna) compile it. In Lnuxit's common to use g++, an open pp (tcan be any name as ang asithas source C++ compiler as you're now inthe same folderas the C++ Save to continue, nter: g++ helloworld.cppin the Terminal and press Return, ‘The First thing to notice i that Xed has Ittakes a short time while the code is compiled by automatically recognised this asa C++ file, since the g++ but providing there are no mistakes or errors in File extension is now setto. see 88 ie Git Vow Sch Tein Hep th your code now sve, dopint the Terminal The aout the compiled Cr code Torun sui again. You need to navigate to the location of Sup the code enter: /a.out and press Return. The C+ file you've just saved, Our example isin the Docume: ql ‘words Hello World! appear on the screen, However, a.out isnt folder, so we can navigate to itby entering: ed Documents. very friendly. To name it something else postcompiling, you can Remember, the Linux Terminals case sensitive, so any capitals reco h: g++ helloworld.cpp 0 helloworld. Ths creates an must be entered correctly, ‘output file called helloworld which can be run with: fhelloworld Fle Cot Ven Seach Teal Hep ie tt vow Sch Teil Hb z= Say Hello to c++ ) Other C++ IDEs to Install ACMA cic co ach me emer Maa el plenty of options available to you. Windows is the most prolific platform for C++ IDEs tae cso eee atrdce DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or al of them if you like, but find the one that works best For you. Ra E ESE Eclipse isa hugely popular C++ IDE that offers FRENTE Codeliteisa free and open source IDE that's the programmer a wealth of Features. thas @ regularly updated and available for Windows, ‘great, clean interface, is easy to use and available for Windows, Linux and macOS. I's lightweight, uncomplicated and extremely Linux and Mac. Head over to wwweelipse.org/downloads/ to powerful. You can find out more information as well as howto download the latest version. IFyou'te stuck, click the Need Help link download and install tat www.codelite.ora/. For more information. “The GNAT Programming Studio (GPS) isa powerful ‘Another popular choice is NetBeans. This and intuitive IDE that supports testing, debugging isanother excellent IDE that's packed with {and code analysis. Te Community Edition i free, whereas the features and a pleasure to use. NetBeans IDE includes project based Pro version costs; however, the Community Edition is avalable for templates for C++ that give you the abty to build applications with \windows, Mac, Linux and even the Raspberry Pi. You can find tat dynamic and static libraries. Find out more at www.netbeans.org/ wwwadacore.com/download. Features/cpp/index.html. EE corrsdetntive cide Series-volume 23 UENO Microsoft's Visual Studiois 2 mammoth C+ IDE that allows you to create applications for Windows, Android, iOS and the web. The ‘Community version isFree to download and install but the other versions allow a ree trial period, Go to www.visualstudio.com/ to ssee what it can do For you. PERS 1's ross-latform IDEs desioned to create C++ applications For desktop and ‘mobile environments. It comes with a code editor and integrated tools for testing and debugging, as well as deploying to you chosen platform. I's not free but there isa trial period on offer before Fequiting purchasing: www.qt.io/at-features-libraries-apistools- andiide/. Bloodshed Dev C++, despite its colourful name, is anolder IDE that is for Windows systems only. However, many users praise its clean interface and uncomplicated ‘way of coding and compiling. Although there's not been much updating for some time, it’s certainly one to consider if you want something different: www.bloodshed.net/devepp html wera publications com (_ Other C++ IDEs to Install Cll \ “The Anta DeStud sa Lnuony DE that EXUDES Features some of the more advanced features you would normaly nd ina pad software development sto. Theres .2GUI designer, source editor, app wizard, interactive debugger and much more, Go to www anjuta.org/ For more information Bra ane Aa bre 00s ne IIa a nerem is excellent DE allows developers towrite C++ code For desktop and ‘web applications across al the major platforms. There's an advanced text editor, integrated debugger and a configurable workbench to help you create your code. t's availabe for Windows, Mac and Linux andis free to download and use: www.monodevelop.cony. ——————— il we Utimate++ isa cross-platform C++ IDE that boastsa rapid development of code through the smart and agressive use oF C++. For the novice, i's a beast of an IDE but behind itscomplerty isa beauty that would make a developer's knees go wobbly, Find out more at www.ultimatepp.org/index html Index) DMs Definitive Guide Series -Volome 33 C++ Fundamentals Within this section you can start to understand the structure of C++ code and see how to compile and execute that code. These are the core Fundamentals of C++, that teach you the basics such as using comments, variables, data types, strings and how to use C++ mathematics. These are the building blocks of a C++ program. With them, you can form your own code, produce an output to the screen and store and retrieve data. 98 Your First C+ Program 100 Structure of a C++ Program 102 Compile and Execute 104 Using Comments 106 Variables 108 Data Types 110 Strings C+ Maths ~ Brian Kernighan (Co-developer of UNIX and author) ‘worabdmpublications com Python & for Besnners ZZ » C++ Fundamentals) Your First C++ Program Eanes ecn ues cuca eas Mita l Ts working exclusively in Windows and Code::Blocks from here on. Let's begin by writing at cent eae ae ecru mes chen h HELLO, WORLD! It's traditional in programming for the First code to be entered to output the words ‘Hello, World!’ to the screen. Interestingly, this dates back to 1968 using a language called BCPL. BR cocinvcc crowns iomsite BER momen coon cic mh ithelloworld.cpp. Clckthe Save as type box and select C/C++ Fes Click the Save button. ESTs "Yow you can see a blank screen, withthe tab PPP You can see that Code:Blocks has now changed labelied *Untitledt, and the number one inthe top the colour coding, recognising thatthe flleisnow \eftof the main Code:Blocks window. Begin by clicking in the main C++ code. This means that cade can be auto-selected fram the window sa the cursors nextto the number one, and entering Code:.Blocks repository, Delete the ifinclude line and os re-enter it. You can see the auto-select boxes appearing, EE) coms detnive cui Series-volome 33 BSTISERD 2utoselection of commands s extremely handy and cuts aut potential mistyping, Press Return to get to line 3, then enter: ‘int mainO Note: there's no space between the brackets. [resell] Sa ¢ be Note again the colour coding change. Press Return at SES) the end of the previous step’s line, and then enter: std::cout << “Hello, world!\n"; o> os Nmnibial> oC ce Xs Sma Fries FPR onthe nextline below int maind, enter a curty bracket: t ‘This can be done by pressing Shift and the key to the right of Pon an English UK keyboard layout. relia © — My first Get program Peireqawigia- ele wera publications com FETED ust as before, CodeBlocks auto-completes the Code you're entering, including placing a closing speech mark as soon as you enter the fist. Dont forget the semicolon at the end of the line; ths is one ofthe most important elements to a C++ program and we'lltell you why in the next section. For naw, move the cursor down to the closing curly bracket and press Return. Pricrxs simv Learning the basics of programming, you begin to understand the structure of a program. The commands may be different From one language to the next, but you will start to see how the code works. #INCLUDE ‘The structure af a C++ program a isquite precise. Every C++ code begins witha directive: include 2 ‘©. The directive instructs the 3 pre-processor toinclude a A 5 6 #include (C++ was invented by Danish student Bjame Stroustrup in 1979, asa partofhisPhD. thesis. tally C++ was called C with Classes, which added Features tothe already popular C programming language, while making ita more User riendly environment: through anew structure section ofthe standard C++ code. For example: #include -clostream> includes the iostream header to support input/output operations. Blame Stroustrup, inventor E ofce, : : INT MAIN() *helloworld.cpp i int main() initiates the declaration of a function, which 8 eanaes oe isa group of code statements 2 under the name man’. ll, 3 | int main() 3 Cte code begins tthe main is 3 function, regardless of where 3 actualy lies within the code. 5 i 6 i LA BRACES #include The open brace (curly brackets) is something that youmay not have come across before, especialy if you're used to Python. The ‘open brace indicates the beginning ofthe ‘main Function and contains allthe code that belongs to that Function int main() ; nae FEED corr: Definitive cide Seies-volume 33 COMMENTS Lines that begin with a double slash are comments. This means they won't be executed in the code and are ignored by the compiler, Comments are designed to help you, or another programmer looking at your code, explain what's going on, There are two types ‘of comment: /* covers multiple line comments, //asingle tine. Lines ‘that begin witha double slash are comments, This means they won't be executed in the code and {are ignored by the compiler. Comments are designed tohelp you, or another programmer looking at your code, explain what's ‘going on. There are two types of comment: /* covers multiple line comments, //2 single tine ant main STD \hile std stands for something quite different, in C++ it means Standard. I's part ofthe Standard Namespace in C++, which covers ‘a number of diferent statements and commands. You can leave the stds part out ofthe code but it must be declared atthe stat with: using namespace std; nt both. For example: #include using namespace std; COUT In this example we'te using cout, whichis part of the Standard Namespace, hence why it’ there, as you're asking C++ to use itfrom ‘hat particular namespace. Cout means Character OUTput, which displays, or prints, something to the screen. IFwe leave std out we have to dedareit at the stat of the code, as mentioned previously. Finclude using namespace std: int main() 1 cout wera publications com (Structure of a C++ Program Cll << ‘The two chevrons used here are insertion operators, This means that whatever Follows the chevrons's to be inserted into the std:cout statement. n this case they're the words Hello, work ‘which are tobe displayed on the screen when you compile and execute the code OUTPUTS Leading on, the “Hello, worl” partis what we want to appear on the screen when the code is executed. You can enter whatever you Uke, as long as it’s inside the quotation marks. The brackets aren't ‘needed but some compiles insist on them, The \n partindicates a new line ist be inserted //My first C++ program cout << “Hello, world!\n” ; AND} Finally you can see that lines within a Function code block (except comments) end with a semicolon. This marks the end of the statement andallstatementsin C+ must have one at the end or ‘the compiler Fas to build the code, The very last line has the closing brace to indicate the end ofthe main Function Finclude ‘using namespace st: int main() ‘cout << "Hello, world! \n" ce C++ Fundamentals | Compile and Execute You've created your first C++ program and you now understand the basics behind the Pett a eer denen eu Enema ccurcocet aarti g Sete ueat keen coe GREETINGS FROM C++ ‘Compiling and executing C++ code from Coder:Blocks is extraordinarily easy; ust a matter of clicking an icon and seeing the result. Here's how it’s done. semicolons at the end of the std:cout ine the results of the Build by looking to the bottom window pane, Any messages regarding the quality ofthe cade are displayed here, Build log © Build messages x J) CppCheck/Ve in “no project" (compiler: unknown) === 5), 0 warning(s) (0 minute(s), 0 second(s) cies FERED your code islooking similar to the one in our BETS DD Yow click on the Runicon, the green play button. screenshot, then look to the menu bar along the top command ine box appears on your screen (of the screen. Under the Fartran entry in the topmost menu you can displaying the words: Hello, world, allowed by the time it's taken see a group oF icons: yellow cog, green play button anda cog/play to execute the code, and asking you press akey to continue. Well button together, These are Build, Run, Build and Run functions. done, you ust compiled and executed your frst C++ program. g Fortran wxSmith Too! ESTED essing any keyin the command tine box closest, returning you to Code:Blocks, Lets alter the code slightly, Under the include line, enter: using namespace std; ‘Then, delete the td: part of the Cout ine; like so: cout << “Hello, world\n"; 5 ot 7 1] cont << world!\n apply the new changes to the code, you Inorde SUES need to re-compile, build, and run it again. This time, however, you can simply click the Build/Run icon, the combi yellow cog and green play button rs ve mentioned inthe previous pages, you don't need to have std:cautifyou already declare using namespace std atthe beginning ofthe code. We could have easily clicked the Build/Run icon to begin with but it's worth going through the available options, You can also see that by building and unning, the file has been saves Boas erxeaiaslorsen A Sree Se a . sou ‘worabdmpublications com Cconpieandbecte COX FPTID rcate a deliberate errorin the cade. Remove the semicolon from the cout ine, soit reads: cout << “Hello, world! \n” Starthere | *helloworld.cpp 2‘ Finciude using namespace std; 3 4 _ int minyy s Fit ‘ 7 || cout << *Helt0, world! 8 o ly 10 n B Now lickthe Buld nd Run con againto apply the changesto the code Thistine code:Blodks refuses code, due tothe error you putin. inthe Log pane at ne bottom of the screen you ae informed ofthe errr, in this case Expected '’ before token, indicating the missing semicolon. FETE ERED place the semicolon and under the cout line, enter anew line to your code cout << “And greetings from CH!\n"; ‘The \n simply adds @ new line under the last line of outputted text. Build and Run the code, to display your handiwork Pthonaces forBesinners QE Zz 2) C++ Fundamentals Using Comments While comments may seem like a minor element to the many lines of code that CC ee eee EU Cums r ced Mac ee en Roma aus aed fc THE IMPORTANCE OF COMMENTING Comments inside code ate basically human readable descriptions _the reader. However, ifx equalling zero is something that drastically that detail what the code is doing atthat particular point. They don't changes the program for the user, suchas, they've run out of lives, sound especially important but code without commentsis one of then it certainly needs to carmmented on, the many Frustrating areas of programming, regardless of whether you'r a professional or jst starting out, Even ifthe code is your own, you should write comments as if you ‘were going to publily share it with others, This way you can return In shor, all code should be commented in such a manner as to tothat code and always understand what it was you did or where it effectively describe the purpose ofa line, section or individual was you went wrong or what worked brilliantly. ‘elements. You should get in tothe habit of commenting as much as. possible, imagining that someone who doesn't know anything Comments are good practise and once you understand how to add a about programming can pick up your cade and understand whatit’s comment where needed, you soon do itas it’s second nature. {going to do simply by reading your comments Ina professional environment, comments are vital to the success Ste ona hte at each geo (of the cade and ultimately, the company. In an organisation, many fee Seda Sk Sn seat set programmers work in teams alongside engineers, other developers, anf sinvecan iene hardware analysts and soon. IF you're apart ofthe team that’s i writing a bespoke piece of software for the company, then your comments help save a ot of time should something go wrong, and ~another team member has to pick up and Follow the trail to pinpoint the issue Place yourself in the shoes of someone whose job isto Find out What's wrong with a program. The program has in excess of 800,000 lines of code, spread across several different ‘modules. You can soon appreciate the need forallitie help from the original programmersin the Form of a ‘good comment. The best comments are always concise and link the code logically, detaiing what happens when the program hits this, line or section, You don't need to-comment (on every tine Something along the lines of: if: doesn'trequire you tocomment that x equals zero then do something; that's going tobe obvious to FEED corre Detntive cide Series-volume 33 C++ COMMENTS ‘Commenting in C++ involves using a double Forward slash ‘/, or a forward slash and an asterisk, brief examples but this is how they work. (Using Comments Cll You've already seen some PEPER Using the Hello World code as an example, you can easily comment on different sections of the code sing the double forward slash Uy first C++ program cout << “Hello, world!\n"; include ewwream lasing namespace sta: int main() t | cout << "Hello, vorld!\2" KES eovameune| FETS RD However, you can also add comments to the end of aline of code, to describe in a better way what's going on: cout << “Hello, world!\n?; //This Line outputs the words ‘Hello, world!”. The \n denotes a new Line. Note, you don't have to puta semicolon at the end of a comment. This is because it'sa lie inthe code that's ignored by the compiler, Youcan comment out sevealtnesby using the gua?3 Forward slash and asterisk: /* This comment. con cover several Lines without the need to add more slashes */ Just remember to finish the block comment withthe opposite asterisk and forward slash. wera publications com FEETP DD (5 careful when commenting, especialy with block comments 's very easy to forget to add the closing asterisk and forward slash and thus negate any code that falls inside the comment block ql Obviously if you try and build and execute the code it errors out, complaining ofa missing curly bracket’ to finish off the block of code. F you've made the errora few times then itcan be time consuming to go back and rectify. Thankfully, the colour coding in CodeBlocks helps identify comments from code. SS i yout using back comments, good practise SUz?6 iin C++ toadd an asterisk to each new line of the comment bck This hebs yout remeber to close the Comment block off before continuing withthe code /* This comment. con * cover several lines * without the need to add more slashes */ Python & C++ For Geginers | C++ Fundamentals Variables Wee eR CIR eet ele Mate simply state that'‘a’ equals 10 and a variable is assigned. However, in C++ a variable has to be declared with its type before it can be used. THE DECLARATION OF VARIABLES You can declare a C++ variable by using statements within the code. There are several distinct types of variables you can declare, Here's how it works. ‘Open up anew, blank C++file and enter the usual code headers #include using namespace std; int mainc) Fincluse using namespace std; pence : ‘auto pi = 3.141593; PEEP speciticto c++, you can also use the Following int main) to.assign values toa variable as so0n 2s you 7 declare them: double area, radius = 1. int a (10); int b (5); Then, from the C++ 2011 standard, using c int result {a+b}; area = pi * radius * radius; cout << area; BRD 227 et salaries which rey . . anyfuncion within the entire code. What youve usedsofarare [SURE ) AcouPle fnew elementshev: fist auto wort local variables: variables used inside the Function. For example: ST SEG RSP nE CTT ea cra < tckthe boxlabeled Have G++ follow the C++11 'SO.C++ Language include Standard Estdec++1], Then the new datatype, dovble wich using nanespace stds ble pr Gee, then int StartLives = 35 int main © ; E startLives = Startlives - 1; cout << StartLives; sion Floating point valu ‘worabdmpublications com Python & for Besnners Zz » C++ Fundamentals Data Types NET CEE ce CUE acter nc mel ON and manipulate if required. Variables are simply reserved memory locations that store Ree ce Cues ue Cate cde tcch THE VALUE OF DATA ‘There are many different data types available forthe programmer in C++, such as an integer, floating point, Boolean, character and so con. k's widely accepted that there are seven basic datatypes, often called Primitive Builtin Types; however, you can create your Own, data types should the need ever arise within your code. ‘The seven basic data types ae: aa errs fees) ea esas ees Eooccy bool} Peeuee ions Pree ec ‘These basic types can aso be extended using the Following modifiers: Long, Shor, Signed and Unsigned, Basically this means the modifiers ‘an expand the minimum and maximum range values for each data type. For example, the int data type has a default value range of 2147493648 to 2147483647, afair value, you would agre. Now, Ifyou were to use one ofthe modifiers, the range alters: Unsigned int= 0 to 4294967295 Signed int =-2147483648 to 2147483647 Short int =-32768 to 32767 Unsigned Short int = 0 to 65,535 Signed Shot int =-32768 to 32767 Long int = 2147483647 to 2147483647 Signed Long int =-2147483647 to 2147483647 Unsigned Long int = 0 to 4294967295 Oty Naturally you can get away with using the basic type without the ‘modifier as there's plenty of range provided with each data type, However, it's considered gaod C++ programming practise to use the modifiers when possible. There are issues when using the modifiers though. Double represents a doublefloating point value, which you can use for FEED corr: Definitive cide Series-volume 33 incredibly accurate numbers but those numbers are only accurate upto the fifteenth decimal place, There's alsothe problem when displaying such numbers in C++ using the cout Function, in that cout by default only outputs the First five decimal places. You can combat that by adding a cout precision () Function and adding a value inside the brackets, but even then you're stil limited by the accuracy of the double datatype. For example, try this code: #include using namespace std; double PI = 3.141592653589793238463; ‘int main) { } cout << PI; <= [[Rathee x) Datatypescop | tinclade using namespace st: | doubie pr = 3.161ss26saseo7992504637 | oout << PI; © cAUserndaia DocumentAC+ \DaaTypesoe Build and run the code and as you can see the outputis only 3.14159, representing cout’ limitations inthis example You can alter the code including the aforementioned cout precision function, for greater accuracy. Take precision athe way up to 22 decimal places, with the following code #include using namespace std; double PI = 3,141592653589793238463; int main { cout.precision(22); cout << PI; } Starthere | Datatypes.cop x YT finclude 15.142857142857142857142857142857 DEG HYP FE Me ms x” sin cos tan v 10* log Bp Mod ct cE Hig ale ON WW @ A ‘worabdmpublications com significant ciitsin a floating-point number) a ingthe valu to. you divi ts of precision, Tobe honest, iFyou'e creating code that needs to be accurate to more thaa Fifteen decimal places, then you wouldnt be using C++, you would use some scientific specific language with C++ asthe ‘onnectve tissue between the two languages. You can create your own data types using an aliasike system called pedef. For example: wed include using namespace std; ‘typedef int metres; int mainc) { metres distance; distance = 15; cout << “distance in metres is: << distance; This code when executed creates a new int datatype called metres. Then, in the main cade block, there's anew variable called distance, which isan integer so you're basically telling the compiler that there's another nar stance id displayed the out for int. We assigned the value ts distance in metres is 15. It might sound alittle confusing t C++ and create your own code, the ea reyouuse Sesriem CRU cike circa cL could have a universal greeting in your code ‘Welcome’ and assign that asa string to be ee Meee a cece STRING THEORY ‘There are different ways in which you can create a string of characters, which historically are all carried over from the o C language, and are still supported by C++. Tocreateastingyou use the char Function, Opena sn? il new C++ file and begin with the usual header: #include using namespace std; int main Q t ' [Mea Qaforson Fe sir -cisia| ide bED Its easy to confuse a string with an array. Here's an #include using namespace std; int main © t char greet[8] = {'W’, ‘e’, ‘1, *c’, ‘0%, tm’, ‘er, NO}; cout << greet << “\n"; BED ovis arc rin the code and Welcome appears nota sting. sting isa lass ich defines objects that canbe represented as steam of characters ans doesn needto be termined ike an aay. Te cade con therefore be represented a: Finclude using namespace std; ‘int main C i char greet[] = “Welcome”; cout << greet << “\n”; FPP 0 c++ there's alo a string function, which works in ‘much the same way. Using the greeting code again, you can enter: include using namespace std; int main © t string greet = “Welcome”; cout << greet << “\n"; , FEED corre Detntive cide Series-votume 23 PEPE There are alco many different operations that you FIMEPBB ust as you might expect, you can mixin an integer can apply with the string Function. For instance, to and store something to do with the string. n this get the length ofa string you can use ‘example, we created int lenath, which stores the result of string, no size() and outputsittto the user using namespace std; include ee using namespace std; 1 int main © string greet = “Welcome { cout << “The Length of the string is: int Length; cout << greet.size() << “\n"; string greeti = “Hello”; } string greet2 = “, world!"; string greet3 = greet + greet2; ore Length = greet3.sizeQ); cout << “The Length of the conbined strings ist * << Length << “\n"; : ae eae ae cases ae eD conte Rnctudeciostream ‘contents of the string. Naturally, if you call your string something = = * ‘ther than greet, then you need to change the command toreflect intimaini@) this. t's always tringnameoperation. Build and run the code tosee . i therenibs, string strg (“Here is a long sentence in a © caved ocamers\CoStngre sentpgreos cout << strg << ‘\n strg.erase (10,5), cout << strg << ‘\n?; strg.erase (strg.begin()+8); . . . cout “<< strg << ‘\n?; SUD ou ener cou oe eens ee strg.erase (strg.begin()+9, strg.end()-9); cout << strg << “\n’; #include using namespace std; int main © { BSTeERERD '¢s vorth spending some time playing around with “Helo”; the numbers, which ae the character positions ae inthe string, Occasionally, it can be hit and miss whether you gett string greet2 = “, world!”; sto peatlos makes perfect Take ol Teese SS iat sopracice mates pret Tee ookat the eesti see cout << greet3 << “\n"; C++ Maths RUPE eee ESN Muna sem acest cues built-in scope For some quite intense maths. C++ has a lot to offer someone who's Frayed a ee RU Lea ur lee eure CT NCR meee Melee eeoli nee eens ena C++ = MC2 ‘The basic mathematical symbols apply in C+ as they do in most other programming languages. However, by using the C++ Math Library, you can also calculate square roots, powers, trig and more. PEPER) <++'s mathematical operations follow the same patterns as those taught in school, in that ‘multiplication and division take precedence over addition and subtraction. You can alter that though. For now, create a new fle and enter: #include using namespace std; int main © 1 float nunbers = 100; numbers = nunbers + 10; // This adds 10 to the initial 100 cout << numbers << “\n"; numbers = nunbers = 10; // This subtracts 10 From the new 110 cout << numbers << “\n”; FEED While simple, it does get the old maths muscle warmed up. Note that we used afloat for the numbers variable. While you can happily use an integer, if you suddenly started to use decimals, you would need to change to @ float ora double, depending on the accuracy needed. Run the code and see the results. ‘Multiplication and division can be applied as such #include using namespace std; int main © { float nunbers = 100; numbers = nunbers * 10; // This mltiplies 100 by 10 cout << numbers << “\n"; numbers = nunbers / 10; // And this divides 1000 by 10) cout << numbers <<“ FTIR 2c2In, execute the simple code and see the results While not particularly interesting, it'sastartinto C++ maths. We used afloat here, so you can play around with the code ‘and multiply by decimal places, as well as divide, add and subtract. The interesting maths content ‘upon the C -omes when you call Math Library. Within this header are dozens of mathematical functions along with Further operations Everything from computi tothew ‘osine to arc tangent with two ue OFPI, You can call the header with: #include include using namespace std; int main © PST Setby getting the square root of a number: #include #include using namespace std; int main © float number 134; cout << “The square root of “ << number << “ee sqrtCnunber) << “\n Here we created anew Roa called number and SUZ used the sqrt(number) Function to display th square root of 134, the value ofthe valble, ber, ul and run the code, and your answer reads 11.5758, ‘worabdmpublications com cons CE PPD 2lculating powers of numbers can be done with: include winclude using namespace std; int main © { float nunber = 12; cout << number << “ to the poner of 2 is “ << ponnunber, 2) << “\n"; cout << number << “ to the power of 3 is ponnunber, 3) << “\n"; cout << number << “ to the power of .08 is << ponCnumber, 0.8) << “\n PET Here ve created afloat called number with the value of 12, and¢ the calculation happens. OF course, you can calculate powers and square roots without using variables. For example, pow (12,2) ‘outputs the same value asthe frst cout line in the code, pow(variable, power) is where #include include using namespace std; int main © { double area, radius = 1 area = MPI * radius * radius; cout << area << “\n"; C++ Input/ Output (C++ Input/Output There's a satisfying feeling when you program code that asks the user for input, then uses that input to produce something that the user can see. Even if it’s simply asking For someone's name and displaying a personal welcome message, it’sa big leap forward. User interaction, character literals, defining constants and file input and output are all covered on the Following pages; all of this helps you to gaina better understanding of howa C++ ol =4 program works. Pree “a Meek ald User interaction computing Character Literals eee Defining Constants File Input/Output perform them quickly, and so that human beings can understand them clearly.” aT (Computer scientist, ere ee) vovoubdmpubleations.com Python a cr+forgeginners QEEF z= C++ Input/Output User Interaction There's nothing quite as satisfying as creating a program that responds to you. This ete ace aestet eee aee teens Meter eek enue neues ete mrs HELLO, DAVE You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard input stream, to prompt a user response. anthnatntyoovan te vertorostitatte ETERS thecnconmandworsinte copate won Sl program needs to be stored somewhere in the Sua? the cout command. With the first cout line you're system memory, soit can be retrieved and used, Therefore, any outputting ‘What's your age’ to the screen, as indicated with the input must Fist be declared as a variable, soit’s ready to be used by _chewrons. Cin uses opposite Facing chevron, indicating an input. The the user. Start by creating a blank C+ file with headers input is put into the integer age and called up in the second cout ‘command. Build and run the code, Wincluae using namespace std; int masn 0) Eee DD youre asking a question, you need to store the input asa string; to ask the user their name, you would use #include FETTER The data type ofthe variable mustalso match the using namespace std; type of input you want from the user. For example, — inom os ea aes Caos! t cout << “\nHello, “ << name << “. I hope you’re ‘int age; well today?\n"; cout << “what is your age: “; } cin og! couticerouiare:ticcapercetyearsota.ts SaidwiSias =i EEE corre definitive cide Series-volume 33 (. User Interaction Cll FRPTRD The pxincipal works the same as the previous code. The user's input, their name, isstored ina string, becauselit contains multiple characters, and retrieved inthe secand cout line, As long as the variable ‘name’ doesn't change, then you canrecal it wherever you liken your code. PPP R You can chain input requests to the user but just make sure you have a valid variable to store the input to begin with. Let's assume you want the user toe whole numbers: include using namespace std; int main © { ‘int: num nun; cout << “Enter two whole numbers: cin >> num >> nun2; and “ << cout << “you entered “ << numl << pum << “\n5 } FETED Licwise, inputted data can be manipulated once You have it stored in a variable. For instance, ask the user For two numbers and do some maths on them: #include using namespace std; int main © i float num, nun; cout << “Enter two numbers: \n"; cin >> num >> nun2; cout << numd <<“ +“ << numa <<“ is: * << pum + mum. << *\n’ ‘worabdmpublications com PID Wile cin works well for most input tasks, it does havea limitation. Gn always considers spaces asa terminator, so it’s designed for just single words not multiple words. However, getline takes cin as the frst argument and the variable as the second: #include using namespace std; int main © { string mystrs cout << “Enter a sentence: \n"; getline(cin, mystr: cout << “Your sentence is: “ characters long.\n"; << mystr.sizeQ << PPI cud and execute the code, then enter a sentence with spaces. When you're done the cade reads the ‘number of characters. Ifyou remove the getine line and replace it with cin >> mystr and try again, the resul displays the number of BEER ettine is usually a command that new C++ programmers forget to include. The terminating white space is annoying when you cant figure out why your code isn't working. In shot, it's best to use getlne(cin, variable) in Future: #include using namespace std; int main © { string name; cout << “Enter your full name: \n”; getlineCcin, name); cout << “\nHello, “ << name << “\n"; Puthonaces forBesinnes QE | C++ Input/Output Character Literals In C++ literal is an object or variable that once defined remains the same throughout the code. However, a character literal is defined by a backslash, such as the \n you've been using at the end of a cout statement to signify a new line. ESCAPE SEQUENCE When used in something like a cout statement, character literals are also called escape sequence codes. They allow you to insert a quote, an alert, new line and much more. PEED create anew C++ fileandenterthe relevantheaders: EIB iryou wanted toinsert speech quotes inside a cout statement, you would have to use a backslash as it #include already uses quotes: using namespace std; #include int main © using nanespace stds f int main © t + cout << “Hello, user, This is how to use \"quotes\”.”5 Finclude = int main 0) bev PEPEB You've already experienced the \n character iteral EFM There's even a characte literal that can trigger an placing a new line wherever i's called. The line: out alarm. In windows 10, I's the notification sound << "Hello\n” <<"'ma C+s\n" <<"*Program\n"; outputs three lines that chimes when you use \a. Try this code, and turn up your sound. of text, each starting after the last #include using namespace std; int main © { aSpa- hl cout << “ALARM! \a"; Be EEED corre Definitive cide Series-volume 33 AHANDY CHART ‘There are numerous character literals, or escape sequence codes, to choose from. We therefore thought it would be good For you to have a handy chart available, for those times when you need to insert a code, ESCAPE SEQUENCE CODE CNAs ce eT eta Cer Reon Cee ¥ oie) i fea ¥ eran tt Horizontal uy rey 0 oc ten Cera) Cd Unicode (UTF-16) (UTF-8) @ Unicode characters are symbolso characters that arestandadacress allltforms For example the copyight sprbal that canbe en Mate keyboard by entering the Unicode c edbyALTex ne case ofthe copyright symbol enter H.Inc++ code you would enter UNICODE CHARACTERS he Starthee _%/ userinteractioncpp e using namespace sta #include int main using namespace std; cout int main © { cout << “\u00A9"; CHARACT CHARACTER TABLE = ‘A.complete list of the available Unicode naracters can be found at wawwaunicode- a= table.com/en/. Hover your mouse over the naracter to see the unique code to enter in le itmay be a little overwhelming krmark th need to come back hing, the table will as from different languages, such as: 2. This means yo y universal fecan be z= C++ Input/Output Defining Constants Constants are Fixed values in your code. They can be any basic data type but as the name suggests their value remains constant throughout the entire code. There are two separate ways to define a constant in C++, the #define pre-processor and const #DEFINE ‘The pre-processors are instructions to the coms code. #include is a pre-processor as is #define. to pre-process the information before it goes ahead and compiles the FETED You can use the #define pre-processor to define any constants you want in our code, Start by creating a new C#+ File complete with the usval headers: #include using namespace std; int main Q Eee "ow let's assume your code has three different constants: lenoth, width and height. You can define them with #include using namespace std; define LENGTH 50 define WIDTH 40 define HEIGHT 60 int main © { k [Eaten 2] ocmmgcnenantncre >] Te | lec BET) cece vee FEED ote the capitals for defined constants it's considered good programming practise to define all Constants in capitals. Here, the assigned values are $0, 40 and 60, so let'scallthem up: #include using namespace std; define LENGTH 50 define WIOTH 40 define HEIGHT 60 int main © 1 cout << “Length is: << LENGTH << "\n"; cout << “Width is: “ << WIDTH << “\n"; cout << “Height is: “ << HEIGHT << “\n"; lex Build and run the code, Just as expected, ie displays the values for each ofthe constants created. i's ‘worth noting that you don't need a semicolon when you're defining ‘a constant with the #define keyword, You can also define other elements asa constant For example, instead of using \n For a newline inthe cout statement, you can define it at the start ofthe code: include using namespace std; define LENGTH 50 define WIDTH 40 define HEIGHT 60 define NEWLINE *\n? int main Q { cout << “Length is: “ << LENGTH << NEWLINE; cout << “Width is: “ << WIDTH << NENLINE; cout << “Height is: “ << HEIGHT << NEWLINE; The code, when built and executed, does exactly the same as before, using the new constant NEWLINE toinserta newline in the cout statement. incidentally, creating a newline constant isn't a good idea unless you're making it smaller than \nor even the endl command, PEPE M veFining a constant is a good way of intalising your base values atthe start of your code. You can define that your game has three lives, or even the value of PI without having to call up the C++ math library #include using namespace std; define PL 3.14159 int main © 1 cout << “The value of Pi i “ ce PI using namespace std; int main © { const double PI = 3.14159; cout << “The value of Pi is: “ << PI << endl EE i Because you're using const within the main block of code, you need to finish the line witha semicolon You can use either, as long asthe names and values don't clash, but it’s worth mentioning that #define requires no memory, so iF you're coding toa set amount of memory, #define is your best bet Const works in much the same way as tdefine You can create static integers and even newlines: #include using namespace std; int main 1 const int LENGTH = 50; const int WIDTH = 40; const char NEWLINE = *\n"; int area; area = LENGTH * WIDTH; cout << “Area is: “ << area << NEWLINE; - Defining Constants Cll z= C++ Input/Output) File Input/Output The standard iostream library provides C++ coders with the cin and cout input and CMetatiecueMan nee ten h Meni tees) utilise another C++ library, called stream. FSTREAMS. There are two main data types wi ifstream. Here's how they work. the fstream library that are used to open a file, read from it and write to it, ofstream and. BR icckcwgencsnwc concn” RRB wevcnaccsemnensnoescceonastac nevfile.open lines), asked the user for their name and storedit and ‘hen written the data to the File, #include #include finclude using namespace std; To read the contents ofa file and outputitto the a screen, you need to do things slightly differently. First you need to create a string variable to store the file's contents (ine byline), then open the file use getline to read the ile line by coosesennnecsnnnees line and output those lines to the screen. Finally, close the Fle PEPER eecinby acking a user for theirname and writing string Line; that information toa file. Youneed the usual tring ifstream newfie (name.txt”); tostore the name, and getline to accept the input from the user. soosenn le cout << “Contents of the file: “ << endl; include include using namespace std; getline(newfile, Line); cout << line << endl; newfile.closeQ; int main © i string name; ofstream newfile; nnewfile.open(“name. txt”); cout << “Enter your none: “ << endl; getline(cin, nane); newfile << name << endl; newfile.closeQ); } toot ae Ses ed Ficiowiouot CR opened atext string Line; ‘ifstream nenfile C*c:\\users\\david\\ Documents\\Cinmeria, txt"); cout << “Cimmeria, by Robert E Howard: \n” << end; while CgetLine(newfile, Line)) cout << Line << endl} fe 7 Cimmeria, by Robert E Howard newfle.close(); Sa Spa eh ED, wee sen FED youcenno doubt see that we've included a while loop, which we cover in afew pages me, Ie means that while there are lines to be read from the textfile, C++ getines them, ‘Once all the lines are read, the output is displayed on the screen and the files closed. FRPTSRD The code above is great for opening afilewith one cor two lines but what if there are multiple lines? Here ESTEE DD ust as you might expect, you can write almost anything you lke to a File, For reading either in Notepad or via the console through the C++ code: string name; int age; of stream newfile: newfie. openC*nane. txt”); cout << “Enter your name: “<< endl; getlinecein, name); nenfile << nane << endl; cout << “\nHow old are you: “ cin >> ages << endl newfile << age << endl; newfile.closeQ); ‘The code from step 8 differs again, but only where Itcomes to adding the age integer. Notice that we used cin >> age, instead ofthe previous getline(cin, variable) The reason for hiss thatthe getline function handles strings, not integers; so when you're using a data type other than a string, use Standard cn, You can also see thatthe location ofthe text file CCimmeriastat isnt inthe same Folder asthe C++ program. When we created the First name bx file, it was written to he same Folder where the code was located; this is done by default To specify another folder, you need to use double-back sashes, as per the character iterals/escape sequence code. ‘worabdmpublications com Sz? 1 write several different elements to a text file, You ‘anhave auser's name, age, phone number etc. Maybe even the value of Pi and various mathematical elements. t's all good practice 3 a th python cts forBesiners QEEy nde : : “The most important property of a program is whether it accomplishes the intention of its user.” ‘worabdmpublications com (Loops and Decision Making Loops and repetition are one of the most important Factors of any programming language. Good use of a loop creates a Program that does exactly what you want it to, and delivers the desired outcome without issues or errors. ‘Without loops and decision making events within the code, your program cannot offer the user any choice. It's this understanding of choice that elevates your skills asa programmer and makes for much better code. 126 while Loop 128 For Loop 130 Do... While Loop 132__|[F Statement 134 [f... Else Statement Python & for Besnners z=» Loops and Decision Making While Loop Sete ne eee cue eT el kage ea Ce Tec condition remains true. When the while loop starts, it initialises itself by testing the Cone Mote eae ous n siete aeteetaa ttl oon TRUE OR FALSE? While loops are one of the most popular Form of C++ code looping. They repeatedly run the code contained within the loop while the condition is true. Once it proves false, the code continues as normal Clear hatyou've done ser andcretea new C++ Fistyou sn? il file. There's no. For any extra headers at the Uae) need to moment, soaddthe standard headers pe sil eatea condition s0usea varabecaled num ande it the value 1, Now create ie loop, stating tha #include using namespace std; ‘int main’ aslong as um i ess than 30, the lo t the loop the v. 5 is cisplayed an is more than 30 rrr few new elemenis here. the BALM 5:3: the opening nd dosing braces forthe ile oop. Tiss because ou loop sa compo statement ning a group of ter the whil fe return 0, which sa hile loop. Enter the code bel iean and preferr added comments to the i int num = 15 while Crum < 30) 4 cout << “Number: “ << num << endl; rum = num +13 3 iF you didnt need to see the continually increasing return 0; bale falue oF num, you could have done away with the ¥ -ompound tement and instead just added num byitselF unit and then displayed the value: t int num = 25 f while Crum < 30) cout << “Number: “ << num << endl; return 0; 5 ( While Loop Cll Iesimportan to remember not to ada semicolon SUz6 at the end of a while statement. Why? Well, as you know the semicolon represents the end oF Gx ne of code. you place one atthe en oFa while state your op we Dermanentl stuckuntlyou close the progam statement. When the code hits the while statement it reads that while the condition of 1 being less than 30s true, loop. The. semicolon closes the line, so the loop repeats; but it never adds 1 to ‘num, as twon't continue through the compound statement Inour example, iFwe were to execute the code the value of num would be 1, as set by the int Youcan manipulate the while statement to display different results depending on what code lies within he loop. For example, to read the poem, Cimmeria, ward by word, you would ente #include include using namespace std; int main © t string word; ‘ifstream nenfile C*C:\\users\\davia\\, Documents\\Cinmeria, txt”); cout << “Cimmeria, by Robert E Howard: \n” << endl; while (newfile >> word) 4 ¥ return 05 cout << word << endl ‘worabdmpublications com PEPE You can further expand the code to enable each word ofthe poem to appear every second. To do 59, youneed to pul ina new library, windows h>. Ths isa Windows ‘only library and within it you can use the Sleept) Function: include #include include using namespace std; int main Q t string word; ifstream nenfile (“C:\\users\\david\\ Document s\\Cinmeria. txt”); cout << “Cinmeria, by Robert E Howard: \n? << endl; hile (newfile >> word) 1 cout << word << endl Sleep(1000); return 0; BERT 8'2e00 worksin miliseconds, so Sieep(1000) is. ‘one second, Sleep( 10000) ten seconds and so ‘on. Combining the sleep function (along withthe header itneeds), {anda while loop enables you to come up with some interesting countdown cade. include include using namespace std; int main © t int a= 10; while Ca != 0) { cout << a << endl; a=a-1; Sleep(1000); cout << “\nBlast OFF!" << endl; return 05 Python & for Besnners Insome respects, a for loop works ina very similar way to that of a while loop, although it’s structure is different. A for loop is split into three stages: an initialiser, a condition and an incremental step. Once set up, the loop repeats itself until the condition becomes false. LOOPY LOOPS The 5 stage of a for loop is executed only once and this sets the p evaluated reference for the loop. The condition. by the loop to see iF it’s true or False and then the increment is executed. The loop then repeats the second and third stage. ERTIRERD ieate a new c++ file, with the standard headers: #include using namespace std; int main © Siar ‘each increment: Start simple and create a for loop that counts from 1 to 30, displaying the value to the screen with t ‘Y/For Loop Begins for(int mum = 1; num <3; num = num +2) 1 cout << “Number: “ << num << endl; z return 0; i BSTTSED) Working through the process ofthe For loop, begin by creating an integer called num and assigning ita value oft. Next, set the condition, n this case num being ess than 130. The last stage is where you create the increments; here t's the value of num being added by 1. for( int num = 17 num < 307 mum = num 41) soe en cSt ERED ‘ter the loop, you created a compound statement. in braces (curly brackets), that displays the current value ofthe integer num, Every time the for loop repeats itself, the ‘second and third stages ofthe loop, it adds 1 until the condition <30 's false, The loop then ends and the code continues, ending neatly with return 0. for( int num = 1; num < 30; num = num +1 4 cout << "Miumber: " <¢ num << endl: , return 07 ‘Afor loop is quite a neat package in C++, all Ske oscsinea within is own brackets, white other elements outside ofthe loop are displayed below. IFyou want to create a 10second countdown, you could use: #include include vindows.h> using namespace std; ‘int main © i 7 7/For Loop Begins for( int a= 10; a !=0; =a -1) 4 cout << a << endl; Seep(1000); cout << “\nBlast OFF!" << endl; return 0; for loop displaying the of 8 user inputted number. FEED ere'san exam sh library, so you can use the S ‘multiplication tab ne cade; inthe command console you can Handy fr students s 10 to 1 countdown in one second increments, until hes zero and Blast OFF! t itreaches zero and Blast OFF! a — i oumnurnenaraane cout << “Enter a nunber to view its times table: “5 cin >>; for Cint i= 4; i <= 12; 441) ¢ cout > nj; for Ci = 1; i « fact *= i; Y coute< “\nFactorial of “<< n <<” = “ce fact << endl; return 0; = PEPET BD The value of the integeri canbe expanded f 12 to whatever number you want, displaying 2 — very large multiplication table in the process (ora small one). OF ‘ourse the datatype within aFor loop doesn't have to be an integer slong as e's valid, it works. for ( float i = 0.00; i < 1.00; i += @.01) we i : cout << i << endl 3 return 0; The code rom step 7 when bit end ru, ast fora nero ‘number, then displays the Factorial of that number hrough the for loop. The user's number is stored in the integer » Followed by the integer | which is used to check f the condition i is true of False, adding 1 each time and comparing itto the user's (tte number, hoe ce bce an z=» Loops and Decision Making Do... While Loop Ado... while loop differs slightly from that of a For or even a while loop. Both for and while set and examine the state of the condition at the start of the loop, or the top of the loop if you prefer. However, a do... while loop, is similar to a while loop but instead checks the condition at the bottom of the loop. DO LOOPS ‘The good thing about a do... while loop is that it’s guaranteed to run through at least once. It's structure is: do Followed by statements, while condition is true, Ths is how it works FRTIEID cecin with anew, blank C++ Fle and e standard headers #include using namespace std; 'slookat the structure of ado, you create an integer called num ‘int main () i F a p 1 Eee re eterno t IF the condition is true, the loop is executed. This TN Sued continues until the condition is False. Wt 6 set 4 cout << “Number: “ << num << endl; ‘pum = num + 13 + while Cnum < 30.5 return 0; oo..whieoon CE Suz75 until the user enters zero: S28 he vrcbe number. the user has entered te be = 0 senha emai cout << “**** Program to execute a Do... eaaeaaen ian oes _ a White Loop continuously ****” << endl; aetna cout << “\nEnter @ to stop and display the sum of all the numbers entered\n” << endl; ‘cout<<"\nPlease enter a runber: cin>snumber; sun += numbers z z : ee FEPTID) Using the countdown and Blast OFF! code used cout<<"Total sum of aLL numbers: “<> number; sum += number; ‘worabdmpublications com PuthonaceeforBesinners ER IF Statement The decision making statement ‘fis probably one of the most used statements in any Pre CUM eae n rie Ce eke me ATEN) SLe eI rt COM accent Mera anton lout Role alt) eon olaria IF ONLY IF uses a Boolean expression within its statement. Ifthe Boolean expression is true, the code within the statement is executed. IF not, then the code after the statement is executed instead. PSPISEDD First.create anew C++ file and enter the relevant standard headers, as usual: #include using namespace std; int main Q i Finclude ‘using namespace std; int main () q IFis best explained when you use a number- What's going on here? To begin, an integer called based condition: ‘num was created and assigned with the value of 1 1 ‘The ifstatement comes next, andin this case we've instructed the = «ode that ifthe coneition, the value, of num sess than 1, then the. code within the braces should be executed. if C num < 30.) { cout << “The number is less than 30.” << endl; tae en 8 COULEEEVOLUCTORINUNDERNSTESECEINUMIESICNLS | WRIA The second cout statement displays the current return 0; value of num and the program terminates safely t's ; easy to see how theif statement works if you were to change the Initial value of num from 1 to 31, pee weeny een Finclude using namespace std; int main () int num if ( mm < 30) i ESTER When you change the value to anything above PEPER The code in step 6issim 30, then build and run the cade, you can see that created a floating point integer called temp, thena only ine ta be outputted to the screen isthe second cout do... while loop that a the current temperature. statement, playing the current value of num, Thisis because the inital if statements False, soit ignores the code within the braces the user to ent PETE D the frstistatement checks to see ifthe user's inputted values less than or equal to zero. Fits, : Fectomentuithinada. hie tenthe outputis’rr its really cold’. Otherwise, the inputs ED oro oie, emenwittinedo--whle greater than zero the code outputs At east t's not freezing! t = float temp; te cm oe - aa do q a sas ~« cout << “\nEnter the temperature Cor E 10000 to exit): * << endl; ‘cin >> temp; if Ctemp <= 0) i couRzenarennyiersinecniyecolais §— PPPIB Final ifthe user enters the value-10000, which impossibly cold soi therefore a unrealistic valu, while loop i terminated anda friendly Good bye" is << endl; z the if (temp > 0) dis i cout << “\nAt Least it’s not Freezing!” << endl; 7 3 . waite C temp cout << “\nGood bye\n” << endl; return 0; . Me 2 seat os ise — PEPAET RD Usinaifis quite powerful fits u remember that ithe concition is true t utes what's inthe braces. IFnat, it continues on its 3. See what else you can come up with using iFand a combination ed correctly, Just the IF... Else Statement STR cat AN cua Mtge ORC nae Cone Tuc ecu ee cuca acelin tot etme Mees occ eRe ker A notes braces is used instead. IF YES, ELSE NO There are two sections of code that can be executed depending on the outcome in an visualise once you get used to its structure. ise statement. It’s quite easy to FETED Secinwith anew ++ Fleand the standard headers: REM The firstline inthe code creates the integer called ‘num and givesitavalue of 1, The ifstatement Wincludevciostreans | tron checks to see the vale of numis less than thirty and fit singimanespace std; = |“! neeerse a: ‘outputs "The numbers less than 30 tothe console. ‘int main © oo ; ibe I poses ; : ; r: Bo sees cot mater Ae tne ten 31+ ah > The else companion to if checks if the number ERTEED [siserpandthecode rom thetrstatementonthe UAE Suecomparon tor checks fae number previous page: ‘number fs greater than 30!” to the console; and finally the code is i terminated satisfactorily Aint num = 15 SSE eS BE SE DOT if Cum < 30) a t : cout << “The number is less than 30!” << = = endl; + “a PPR Vo. can chang the value of num nthe code or rRNA ‘you can improve the code by asking the user to — enter value: + i return 0; amen j cout << “Enter a number: “; cin >> num; if C mum < 30) peated t bat cout << “The nunber is less than 30! endl; “— + eae else Ftc nme 0 an 20 ot 4 ue cout << “The number is greater than 301” eae an acini tester ea << endl ¥ C return 0; ¥ FEED corre Derntive cide Series volume 23 PPT) The code works the same way, as you would expect, but what iFyou wanted ta display something ifthe user enter ‘ the number 302 Try this ‘int num; cout << “Enter @ number cin >> num; if C num < 30) { endl; t else if (num > 30) 1 cout << “The number is greater than 30!” << endl; cout << “The nunber is Less than 30!" << else if C num 4 end; } return 0; 30) cout << “The number is exactly 301” << PREM the new addition tothe code is what's known asa nested if... else statement, This allows you to check For multiple conditions. n this ease, i han 30, reater presented to them he user enters a number less nan 30 or actually 30 itself a different outcome is ‘worabdmpublications com steps Bi B ‘umber guessing game. Begin by creating the variables int num, guess, tries cout << “***** Two-player number guessing game sete ce endl cout << “\nPlayer One, enter @ nunber for Player Two to guess: “ << endl; cin >> num; cout << string(s0, *\n"); PEPER The cout << string(S0, (0) line clears the screen so Player Two doesn't see the entered number. Now you can create ado... while loop, together with if 0 1 ‘cout << “\nPlayer Two; enter your guess: cin >> guess; triest+; if (guess > num) i cout << “\nToo High!\n” << endl; ? else if (guess < num) i cout << “\aToo Low!\n” << endl; else if (guess == num) i cout << “Mell done! You got it in" << tries << “ guesses!” << endl; F while Cquess return 0; ‘num: ‘aba second player, then Player One enters the ‘number to be guessed, hen Player Two can take many guesses asthey need to get the right number. Want to make itharder? Maybe use decimal nur Pthonaces forBecsinners ER Working with Code ~ 5 7 J . * “| have always wished for my computer to be as easy to use as my telephone; my wish has come true, because | can no longer figure out how to use my telephone.” — Bjarne Stroustrup (yee keacoee ee Working with Code By now you should have the essential. building blocks of how to program in both Python and C++. You can create code, store data, ask the user questions, offer them choice and repeat functions until they prove true and provide the correct output. What's next then? This section looks at some of the more common coding mistakes that Python and C++ beginners make and where you can seek help to continue your Programming adventure. Common Coding Mistake mmon Coding Mistakes je Shh O MeO en eon ACen CMe Noel uel ise om TT CY Cetus rr occ eeuine ceed eae ems sad even experts make the occasional mishap. Thing is, to learn from them as best you can. X=MISTAKE, PRINT Y ‘There are many pitfalls For the programmer to be aware of, Far too many to be listed here. Being able to recognise a mistake and fix itis when you start to move into more advanced territory, and become a better coder. Everyone makes mistakes, even coders with over thirty years’ experience. Learning From these basic, common mistakes help build a better coding Foundation. e EASY VARIABLES Meaningful naming for variablesis a mustto eliminate common coding mistakes. Having letters of the alphabet Isfine but what happens when the code states there's. a problem with xvariable. t's not too difficult to name variables tives, money, playert and so on. It would be wonderfulto be able to Work like Neo from The Matrix movies. Simply ask, your operator toads it into your memory and you instantly know everything about the subject. Sadly though, we can't do that. Te First ‘major pitfall is someone tryin too much, too quickly. So take coding in small pieces and take your time. points = 10237 Lives = 3; write( "Points: "+points: Weite(‘Lives: “4lives)s weite("Total Time: "+totalTime+" secs"); weite( ” totalscore = //COMMENTS write("Your total Score is: "+totalscore); Use comments’ simple concept but commenting on jour code saves so many problems when you next come to look overt inserting comment Uneshelps you quchy sift PLAN AHEAD through the sections of code that are casing problems so useflif you need to review of older plete of code: While it’s great to wake up one morning and decide to code ong a classic text adventure, it's not always practical without a ‘900d plan. Small snippets of code can be written without too much thought and planning but longer and more i- depth code requires @ good working plan to stick to and help iron out the bugs. USER ERROR BACKUPS SYS eM a eo) SECURE DATA oe E130 z= Working with Code J Python Beginner's Mistakes MEIC Cucteee eae ua lecetCus tactic Reed ee KC come un eM Rouse eu 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. VERSIONS INDENTS, TABS AND SPACES. Todd to the confusion that most beginners already face when _—Python uses precise indentations when displaying its code, The coming into programming, Python has two live versions ofits indents mean that the code in that section isa part of the previous language available to download and use. There is Python version _ statement, and not something linked with another part ofthe code. 2.7.xand Python 3.6.x. The 3.6.x version isthe most recent, and _Use Fourspaces to create an indent, not the Tab key. the one we'd recommend starting, But, version 2.7.xcode doesn't always work with 3.6.x code and vice versa, atc THE INTERNET COMMENTING Every programmer has and does at some point go on the Internet Again we mention commenting. I's hugely important Factor in {and copy some cade to insert ito their own routines. There's programming, even i you're the only one who is ever going to view nothing wrong with using athers' cade, but you need to knowhow the code, youneed to add comments as to what's going on. ithis the code works and what it does before you go blindly running iton function where you lose a life? Write @ comment and help you, or your awn computer. anyone else, see what's going on Createldeete att fen a pyton program 1 sec op pyoeme EZED corre detntive cide series-volume 33 COUNTING LOOPS Remember that in Python a loop doesn't count the last number you specify in range. Sof you wanted the loop to count from 1 to 10, then you will need to use: n= ListCrangeCt, 119) Which will return 1 to 10. Drmnsane = @ x CASE SENSITIVE Python isa case sensitive programming language, so you will need to check any variables you assign For example, LiV@S=1O is 2 different variable to lves=10, calling the wrong variable in your code canhave unexpected results. TB Python 362 St Fle _Eait_Shell_Debug Options _Window Help Python 3.6.2 (v3.6.2:8£433b5, Jul 8 2017, 0 ‘on win32, ‘Type *copyrighc", “creaics" >>> Livesr10 dos Laves=s >>> print (Lives, 3 or “License ()" for mor lives) BRACKETS Everyone forgets to include that extra bracket they should have ‘added tothe end ofthe statement. Python relies on the routine having an equal amount of closed brackets to open brackets, so ary erorsin your code could be due to you Forgetting to count your brackets;including square brackets, def print_game_status(self): print (board[len(self.missed_letters)]) print ('Word: | + self-hide word()) print (‘Letrers Missed: ',) for letter in self.missed letter: print (letcer,) print () print (‘Letters Guessed: ',) for letter in seif.guessed letters: print (letter,) print () wera publications com ( Python Beginner's Mistakes Cll COLONS It’s common for beginners to Forget to add a colon tothe end of 2 structural staternent, such as: class Hangnan: def guess(self, Letter): ‘And so on, The colonis what separates the code, and creates the indents to which the Following code belongs to OPERATORS Using the wrong operator also a common mistake to make. When you're performing a comparison between two values, For example, you need to use the equality operator (2 double equals, ==). Using {single equal is an assignment operator that places a value toa variable (suchas, ves=10), OPERATING SYSTEMS, \writing code For multiple platforms is dificult, especially wien you star to utilise the external commands ofthe operating system. For ‘example, iF your code calls Fr the screen to be cleared, then For ‘Windows you would use ES. Whereas, for Linux you need to use ‘Clear. You need to solve this by capturing the error and isuing it with an alternative command. 1 code to aececr exzor for using # aittes os aysten( tee print (s\nossos>soobEython 3 File Managescceecccece\n") z= Working with Code ) C++ Beginner's Mistakes SEEM cl ters: eis C einen scr ee een CTU cyetc aurea ieee keane) Pe eee coarser cuts corte rately VOID(C++, MISTAKES) ‘Admittedly it's not just C++ beginners that make the kinds of errors we outline on these pages, even hardened coders are prone to the odd UNDECLARED IDENTIFIERS ‘Acommon C++ mistake, and to be honest a common mistake with ‘most programming languages, is when you try and output a variable that doesn't exis. Displaying the value oF x on-screen sine but not if you havent told the compiler what the value of xis to begin with, File Edit View Search Tools Documents Help Bop | onoss | YA) O9 itestt.cpp #include int main() I tieeasemrerer sy > SEMICOLONS Remember that each ine ofa C++ program must end with 2 semicolon. fit doesnt then the compiler treatsthe line withthe missing semicolon as the same tine with the next semicolon on. This, ‘creates all manner of problems when trying to compile, so don’t Forget those semicolons. |#include int main) { int a, b, cy ds alo; be20; | c30 desig; std::cout << a, b, c,d; p hap here and there. Here are some common issues to try and avoi STD NAMESPACE Referencing the Standard Library is common For beginners throughout their code, but iF you miss the std: element of statement, your code errors out when compiling, You can combat this by adaing using namespace std; Under the #include part and simply using cout, cin and soon from then on. include Using namespace std; dint aain() { int a, b,c, di onlo; bo ey cout << a, by c,d: ) GCC OR G++ IF you're compiling in Linux then you will no doubt come across ‘gccand g++. nshort, ges the Gnu Compiler Collection (or Gnu C Compiler as it used to be called) and g++ isthe Gnu ++ (the C++ version) of the compiler. you're compiling C+ then you need to use g++, asthe incorrect compiler drivers willbe used. . davidermint mate “Documents Fle Edt View Search Termial Hep COMMENTS (AGAIN) Indeed the mistake of never making any comments on code i back ‘once more, As we've previously bemoaned, the lack oF readable identifiers throughout the code makes it very dificult to look back at how it worked, For both you and someone else, Use more comments QUOTES Missing quotesis a common mistake to make, for every level of user Remember that quotes need to encase strings and anything that's {going to be outputted to the screen or into a file, For example. Most compilers errors are due to missing quotes in the code, EXTRA SEMICOLONS hile it’s necessary to have a semicolon atthe end of every C++ line, there are some exceptions to the rule. Semicolons need to be at the end of every complete statement but some lines of code aren't complete statements. Such as include ‘if Lines switch Lines IFit sounds confusing don't worry, the compiler lets you know where youwent wrong, ora bmpublcations com (C++ Beginner's Mistakes TOO MANY BRACES ‘The braces, or curly brackets, are beginning and ending markers {around blacks of code, So for every {you must have a}. Oftenit’s ‘easy to include or miss out one or the other Facing brace when writing code; usually when writing in a text editor, as an IDE adds them For yo. #include using namespace std; int main() ee int x; String mystring = “This is a string!\n" cout << "what's the value of x? cin >> x; cout << x; { cout << "\n\n"; cout << mystring ? INITIALISE VARIABLES In C++ variables arent initialised to zero by default. This means if you create a variable called x then, potentially, itis given arandom ‘number from 0 to 18,446,744,073, 709,551,616, which can be dificuleto include in an equation. When creating a variable, give it the value of zero to begin with: X80. sinetude Using mamaspace std; int maint) nt; cout << x3, » A.OUT ‘A.common mistake wien compiling in Linux is Forgetting to name. your C++ code post compiling, When you compile From the Terminal you enter: t+ code.cpp ‘This compiles the code in the file code.cpp and create an a.aut file that can be executed with /acout, However, iF you already have code in acut then i’s overwritten. Use: gH ‘code.cpp =o naneofprogran lett Vow seach Teil Hp Pythons cerforsesinners QE z= Working with Code ) Where Next? exe A ns cee Tenge cme een ecom MEM trea asa beginner any more but you still need to test your code, learn new tricks and hacks to Se aieieca Ccecitt ca me nanee cecum euler #INCLUDE What can you do to Further your skills, learn new co ‘thers using what you've experienced so far? TWITTER ‘Twitter ist all trols and antagonists, arong the well. publicised vitriol ae some genuine people who are more than wiling to spread theircoding knowledge, We recommend you Find a Few who youcan relate to and follow them. Often they post great tips, hacks and Fikes For common coding problems. KEEP CODING IF you've mastered Python fairly well, then turn your attention to Cr+or even GH. Stllkeep your Python sls going but learning anew coding language keeps the old brain ticking over nicely and give youa view into another community, and how they do things differently EZED corre vetntive cide seies-volume 33 practises, experiment and present your code and even begin to help OPEN PROJECTS Look for open source projects that you tke the sound of and offer tocontribute tothe cade to keep it alive and up to date. There are millions of projects to choose from, so contact a few and see where they need help. t ay onlybe a minor code update but it's2 noble ‘occupation For coders to getint, == Dm SHARE SKILLS Become more active on coding and development knowledge sites, such as StackExchange. I you have the skllsto start and help others ‘out, not only will you Feel really good For doing so but you can also (eam a lot yourself by interacting with other members. GOING MOBILE The mobile markets a great place to test your coding skills and present any games or apps you've created, IF your app is ood, then ‘who knows, it could be the next great thing to appear on the app stores. t's a good learning experience nevertheless, and something worth considering > coher = ot ONLINE LEARNING ‘Online courses are good examples of where to take your c skills next, even ifyou start From the beginner level again Often, an online course follows a strict coding convention, sof you'te sel taught then it might be worth seeing how other developers lay out their cade, and whats considered acceptable. Learn to code interactively, for free. L_] SHARE CODE Get sharing, even f you think your code isnt very good. The iitism, advice and comments you receive back help you iron out File and save it as FileMan.py. Once executed it will display the program title, along with the current time and date and the available options. Amport shutit Amport subprocess dee Read): patheinput("Enter the fle path to reads”) ve") ‘le.close() dee trite) path-input("Enter the path of file to write or create:”) SE os.path.isfle(path) print(‘Rebullding the existing Mle’) alee Print (‘Creating the new Sie’) textninput "Enter text:") ‘le=open(path,"w") Sie.write(taxt) dee addi) patheinput("Enter the Sle path") textninput("Enter the text to adds") sSle=open(path,’s”) Sie.write(\n'ttext) Get deteta() pathainput("Enter the path of Sle for deletion:”) Af o2.path.exista(path) print('File Found’) oe renove(path) Print(‘File has been deleted’) aise Print('File Does not exist’) det birist) patheinput("Enter the Disectory path to display:") sortlist=sorted(os. listdir(path)) =o while(iclen(eorttist)) rint(sortlist{i}¥"\n') Hel det check() fp=int (input ‘check existence of \nl File \n2. Dizectory\n')) Ae fpeel path-input("Enter the file path:") f-pathsefile(path) Python File Manager (c} Af os path Laftte(path)=tzue S.1dst files in a directory print (‘File Found’) S.chack fle existence rint('File not found’) 8.copy a file it tpe=2: Sicreate s directory patheinput("Enter the directory path:") i0.Delete a directory ‘os path. edix(path) 11.0pen a program if os.path.isdix(path)=-False: Eee prine(‘Directory Found’) = Print (‘Directory Not Found’) Sf deomt: Readi) sf dec=2) sput("Enter the source path of file to move:) write) fBe=int input(‘l Rename \n2.Move \n') Sf dace} path2=input(‘Enter the destination path and file nana! ‘shut il move (path1,path2) Delete() print(‘File renaned’) Sf dac=s: sf mr=2i Dirlist) path2ninput( ‘Enter the path to move:") st dec shut move(path,path2} Print ((File moved’) Check’) dee copy) pathisinput(‘Enter the path of the file to copy or renane:’) ath2ninput('Enter the path to copy to:’) shutit.copy (patht,path2) Makedix() Print('File copied’) 4 decid: Renovedir() def Makedic() if deo= path=input("Enter the directory nane with path to make Opensite() \neg. CA\selio\\owdis \nWhere Newdis is new Sf dac=t2: directory:") exit() os nakedire(path) crunint (input ("Return 0 menu\n2.Eeit \n")) prine(‘Directory Created’) Tie rune exit() ef Renovedir() pathainput('Enter the path of Directory:") treedireint(input('I Deleted Directory \a2.Delete Directory Tree \n3.Exit \a')) sf treediz= os endir(path) sf treedis shutil xmtree(path) print(‘Dizectory Deleted’) ef opentile() patheinput(‘Enter the path of program’) ery: ‘os startfile(path) except 3 : rine('File not found’) i ; aa 5 Imports : wake (cunt) There are three modules to import here: Sutil, OS and try: Time, The fist two deal with the operating system and fle os. systen(/cieas’) management and manipulation; and the Time module simply except OSError: os.systent cls") prine(‘\moosoospo>Bython 3 File Manager nunber: rint("Too high, tey again’) if guess == number: umber: SS EST Print (Well done, ° + Name + ‘! You guessed correctly in + guessestsed + * guesses.") smamber: jer = str (number) Print((Sorry, out of quest thinking of is * + numb ‘The number I was ‘Although thisisa reasonably easy to follow program, there are ‘ome elements to the code that are worth pointing out. To begin with, you need to import the Random module as you're using andom numbers within the code, This section of the code creates the variables forthe number ‘of guesses used, along with the name ofthe player, and also sets up the random number between 1 and 30. Fyou wider range of random number selection then increase the ‘number=random.randint(1, 30) end value of 30; don't make t too high though or the player willnever be able to guest. Fthe player guesses too low orto high, they are given the ‘appropriate output and asked to try again, while the number ‘oF guesses islessthan ive. You can aso increasethe number quesses from 5 by altering the while quessesUsed «5: valve ne player quessed the correct number then they are given a done’ output, along with how many quesses they used up. ithe player runs out of quesses, then the game over output is clispayed insta, along with evealing the number the computer was thinking of. Remember, iFyou do alter the values ofthe adam number chasen by the computer, or the number oF {uesses the player can take, then along with the variable values, you also needto amend the instructions given inthe print statements atthe stat ofthe code. Code Improvements Since this s suchas simple script to apply toa situation, there's plenty of room to mess around withitand make it mare interesting, Perhaps you can include an option to take score, the best out of three rounds, Maybe an elaborate way to congratulate the player Forgetting a hole in one’ correct guess on thelr Fst try, Moreover, the number quessing game code does offer some room For implementing into your c Ferent manner. What wi ‘mean by this, the code can be used to retrieve a random number between a range, which in turn can give you the statofa character Creation defined Function within an adventure game. Imagine the start ofa text adventure written in Python, where the player names their character. The next step isto roll the virtual random dice to decide what that character's combat rating, strength, endurance and luck values are, These can then be. carried Forwardinto the game under a set of variables that can be feduced or increased depending on the circumstances the playe’s character ends up in. ‘worabdmpublications com Number Guessing Game For example, as per the screenshot pravided, you could use something along the lines of Endurance=0| creo isek=o Endurance = random randint(t, 15) (CR = random.randint(1, 20) lack = random.randint(1, 10) Print ("Your character's state are as follows:\n") Print (‘Endurance:", Endurance) Print ("Combat Rating:", CR) Print ("Luck:", Lek) ‘The player can then decide to either stick with thir all or try again for the hope of better values being picked. There's ample ways in ich to implement this code into a basic adh Python & C+ ForBesinners C7 Code Repository Polygon Circles Geese eC h narra POLYGONCIRCLES.PY NaS ee ee ‘There's lots of mathematics used here along with some Breed ors p allen intricate coordinate manipulation withthe Turtle module. aay rear eee Enterthe code and execute ito see how i tums out mae ttl ee aes eeu tartuavanparte Celaya aati pant Ae cy espe Initia nese ERAS TESSeMIO mauutle:'Theend resultis-quité isscaset/io0 Pel cle gees elie =) for i in range(100) Arla a Tien el sele-1t el sisessin(:_¥1 sin(ttn):y2artcos(t4n) penup(); goto(«l yi) pendown();goto 2,32) taine Graphical Enhancements ‘There are several waysin which you can improve this code to make For example: itmare interesting. You can insert colours, perhaps a different colour for every line. You can display amessage inside the cle ‘for 4 4m range(00: {and have the Turtle draw aroundit Let your imagination run wild xlsr*sin(t); ylertcos(t) con this one, xdertein(ttn);y2erteos(ttn) spend fastee®) Tut's rapicscan take awhile to map out and draw, depend enor); soto) how big and how intate an image Risyoure designing. whist PandowmOvanto(x72) ne effect canbe quite stunning, Ris United bythe amount of ime ittakes to dsplay an image. Therefore i's worth seeing ifthe SEES ETAT This willrun through the code at the Fastest’ speed possible for the Turtle. e certainly makes a difference and is worth considering iiiteierstxstase cs if you're drawing Turtle mages for games or presentations. slowest sion ‘le E6e Farmat Bun Options Wdows Help normal From turtle import * ae {rae math por sn. oa, wb fastest {ne=2ps/100 far a. eapetvon) Rasessiney: yierteasce) ‘You can experiment withthe various speeds by adding the Function rairsintten)yoorteasctom) inthe For loop, just before the penup ine. ah one) Benopt): gorocrt.y1) oa eee ed ( Polygon Circles/Random Number Generator Random Number Generator User input and the ability to manipulate that input are important elements with any programming language. It’s what separates a good program from a great program, one that allows the user to interact and see the results of that interaction. More Input While an easy code to Follow, it could be more interesting Ifyou prompt the user For more input. Perhaps you can provide ther with addition, subtraction, mutipication elements with their numbers. Fyou're Feeling clever, see you can pass the code through a Tkinter window or even the Ticker windaw that’s available on Page 128. Furthermore, the core ofthe code can be used ina text adventure game, where the character Fights something and their health, along with the enemys, is educed by a random number. Ths ‘an be mixed with the previous code rom Page 90's Number Guessing Game, where we defined the stats For the adventure ‘game's character You can also introduce the Turtle module into the code and perhaps set some defined rules for drawing a shape, abject or something based on a user inputted random value from a ange cof numbers. t takes litle working out but the effects certainly really interesting, ora bmpublcations com RNDNUMGEN.PY lemight be simple but this little piece of code will ask the user For two sets of numbers, a start and a finish. The code will then pluck out a random number between the two sets and display it. from random import * print (*\nssoss>>s5>Random umber Generatorcceccees>ppoo>>>Random Turtle Inagecceeecccee\n") mbl=int{input "Enter the start number: ")) fanb2wint(input("Eater the second sumber: *)) nb3-int(input ("Enter the third number: ")) mbé=int(input("Enter the fourth number: ")) ‘turtle. forvard(nmbt) turtle. 1eft(00) ‘turtle. forward(nmb2) turtle.1eft(90) turtle. forward(amb3) turtle.1eft(90) ‘turtle.forvard(nmbs) turtle. 1e£t(00) \Whilstitsalittle rough around the edges, you can easly make it more suitable, Python & C+ ForBesinners C7 Code Repository Random Password Generator We'ré'alwaysibeirg told that our RNDPASSWORD.PY Pere bs le tiae tele ere ela ea eet] Us a cele elt co} uy lalate Ret mel a eatiatl ad Pee cue ene) generator code below will create a 12-lettef string Of Words (Both cases) EDC Maier ee a teeaa de atc Copy the code and runt; each time you'll get a random string of characters that can easily be used as a secure password which wil be incredibly difficult For a password cracker to hack. Amport string import random det randompassword() chars=string.ascii _uppercase + string.ascii _ lowercase + string digits size 8 return join(random.choice(chars) for x in range(size,20)) ‘print (randompassword()) Secure Passwords There's plenty you can do to modify this code and improve it ‘Adding a oop to print a password fifty tim further. For one, you can increase the number of charactersthe example: ‘generated password displays and perhaps you can include special characters too, suchas signs and symbols. Then, you can o Amport string the oafilethensecurelycompressitusing the Apert random extremely easy, For previous random number generator asafile password and send it to. user For theirnew password, det randospassword() An interesting aspectto this code the ability to introduce a loop rr lowercase + string digits and rin ass amee alistof SO users for a company and you'e in charge of generating _—seturm “join(random.choice(chars) for x in arandom password fr them each month, ange(size,20)) 'sassume you have 1y number ofr no white n>>>po>>>>Awasome Advanturecccceeccee\n") print("\n" * 3) time. sleep(3) rint(*\nA long time ago, a warrior strode forth from ‘the frozen north.") tine,sleep (2) print(‘Does this warrior have a nane?") ame=inpat ("> *) print (name, “the barbarian, sword in hand and locking for adventure!”) ‘ine, sleep(t) print(‘However, evil i lurking nearby....”) ‘ime. sleep(1) print(’A pair of bulbous eyes regards the hero...”) tine,sleep (2) print(Will", name, “prevail, and win great fortune...”) tine. sleep(t) print(‘Or die by the hands of great evil...2") ‘time. sleep(1) print("\n" *3) print(‘Only time will tell...”) ‘time. sleep(1) Print(’.') ‘time.aleep(2) print...) tine,sleep() print(’..!) ‘time. sleep(1) print(*..") ‘ime. aleep(S) rint("\n" +200) print("” You find yourself at a small inn. There's Little gold in your purse but your sword is sharp, land you're ready for adventure, With you are three other customers A ragged looking man, and a pair of dangerous looking guards.””) det start() peint(*\n ~ PEint(‘Do you approach the...”) Print (*\n") rint(“I. Ragged looking man") Eint (‘2 Dangerous looking guards") endlist=['2", °2"1 cendzgetond(endlist) Af ond == "Y: xagged() elie end == °2 guards() det ragged Prine("\n’ * 200) Print(""'You walk up to the ragged looking man and greet. him, He smiles a toothless grin and, with a strange accent, says, “Buy me a cup of wine, and I'll tell you of great treasure...””) time. sleep(2) def guards() eint(*\n” #200) print(”"You walk up to the dangerous looking guards and greet then. ‘The guards look up from their drinks and ‘anazl at you. What do you want, barbarian?” One guard reaches for the hilt of his sword...”"") time. sleep (2) Adventure Time This, as you can se, isjust the beginning ofthe adventure and takes up afar few lines of code. When you expand, and weave the story along, youll Find that you can repeat certain instances such asa chance meeting with an enemy or the ike. We've created each of the two encounters as adefined set CF Functions, along with alist of possible choices under the cmdlist ist, and cmd variable, oF which s also a defined Function. Expanding on thisis quite easy, just map out each encounter and choice and create a defined Function around it. Providing the user doesnt enter quit into the adventure, they can keep playing, There's also room the adventure for a set of varables designed For combat, luck, health, endurance and even an inventory oF amount of gold earned. Each successful combat situation can Feduce the main character's health but increase their combat skills, cr endurance. Plus, they could loot the body and gain gold, or earn {gold through quests Finally, how about introducing the Random module. Ths wil tenable you to include an element of chance in the game. For example, in combat, when you strike an enemy you willdo a random amount of damage as will they. You could even work out the maths behind improving the chance of abetter hitbased on your or your opponent's combat skis, current health, strength and endurance, You could create a game of dice the inn to seeiFyou win or lose gold (again, improve the chances of winning by working ‘ut your luck factor int the equation) Needless to say, your text adventure can grow exponentially and prove ta be a work of wonder. Gaod luck, and have Fun with your adventure. ora bmpublcations com ( Text Adventure Script def getond{endlist) ‘cad = input(nane+">") Af ond in endlise: return ond elif end = “help” rint("\ntnter your choices as detailed in ‘the gane.’ Print(‘or enter ‘quit’ to leave the game”) return getond(endlist) = elif ond eine (*\ ‘ime.eleep(2) print("Sadly you return to your homeland without fame oF fortune...") ‘ime.leep(5) exit) Python & C+ ForBesinners Tmt Et) ae aya) aT aie ee eed pene en EE en Bae eo conceal a o> re rey eres ee a S; Meer ee ou ea rN a eae We've made Hangman game board (he glows) ot of Ceol Cums CNM tel characters that can be displayed in the IDLE Shell, along with mae et RRM] SPusetoctwcrstorindony cose tom eas nox eit Be eee teu import randon Pin Res untetctlan ig CO Geals caf. board = [" Sih tater te Bee Mier Cea Ae) Deter 1 AG. Ue be! oWe og bf 7 HANGMAN.PY >psppoopootangmancceceeceee co ail Dy class Hangman: def __ init _ (self,word): Eword = word self.nissed letters = [] self guessed letters = () def quess(celt, letter): AE letter in selfword and letter not in self, guessed _ letters: ‘self.guessed _ letters append(letter) elif letter not Zn self.word and letter not in self.nissed letters: self.missed_ letters.append(letter) else: ‘return False return True def hangman _over(sel£): return self-hangman__won() or (len(self.missed _ letters) = 6) ef hangman _won(sei¥) Ae‘ not in self-hide_ word() return True return False def hide _word(sel£): SS for letter in self.word: Af letter not in self.guessed letters: rin 42"! else: = tn 4= letter return ren ef print _gane_ status(sel£): print (board{ien(self.missed _letters)]) print (Word: ' + self.hide word()) Print (Letters Missed: ',) for letter in self.miseed _ letters: Print (letter,) print () Print (Letters Guessed: *) for letter in self.quessed letters: print (letter,) print 0) def rand _ word) bank ="‘ability about above absolute accessible ‘accommodation accounting beautiful bookstore calculator clever engaged engineer enough handsone refrigerator opposite socks interested strawberry backgammon anniversary confused dangerous entertainment exhausted impossible overweight temperature vacation scissors acconnodation appointment decrease development earthquake environnent brand environment necessary ora bmpublcations com ( Hangman Game Script luggage responsible ambassador circunstance congratulate frequent’.split() return bank{randon.randint(0,len(bank))] dot main): game = Hangnan(rand_word()) while not game.hangnan _over() game print _gane _ status() User. input = input(\nenter @ letter: ") game Guess(user _ input) game.print _game _status() Sf gane.hangman _won() Bint ("\aCongzatulations! You have won!) lee: print (\nSorry, you have lost.’) Print (‘The word was ' + game.word) Print ("\nGoodbye!\n") if __name__ == main QuiT() Since this the last example in our Python code repository, we thought we'd go out witha bang and feature the hangman gallons being drawn with each incorrect quess of the word, Don't worry fit looks misaligned in the text her, this is merely due to the differences between using the Python IDLE editor and pasting the code into a word processor (which Formats things cifferently) “There's plenty you can dotoimprove, enhance and expand on ‘what we've presented here, You caninclude a routine that returns an error the user enters a number or character. You can include extra points For someone who guesses the entire wordin one go rather than one letter atatime and you could perhaps add Chopin's Funeral March should you lose the game; Dorsomething celebratory ifyou win. Consider replacing the bank of words too. They/re Found under the bank ist, and could easly be swapped out for something ‘more dificult. you download www.github.com/dwyVenglish- ‘words you can find a text document with over 466,000 words. Perhaps you could swap the words n the bank to instead read the contents ofthe text file: et rand _word(): ‘with open('/home/pi/Downloads/words.txt”, “rt") as £: bankef.readlinea() return bank[random.randint(0,1en(bank))} Python & C+ ForBesinners Black Dog Media Master Your Tech To continue learning more about your tech visit us at: www.bdmpublications.com NT a ae areas eeu ese ae ree Mee Print & digital editions a ne Featuring the very latest updates ‘GuideBook Step-by-step tutorials and guides ®@ Created by BDM experts ® it Check out our latest titles today! Special Deals and Bonus Content Ae ee eee eal com Buy our Photoshop guides and download and get the latest updates, offers Uli Ie oR Om tril and news from BDM. We are here SS et eRe to help you Master Your Tech! Sign up to our monthly newsletter FNencal ual | Nanuet) Mine cn The Complet Tela Ts GoPro 10512 Manual fl as, Manua ey Manual am Windows 10 ff Photosho Photography | Google & Internet For Seniors ff For Seniors If For Seniorg pooge Safety For Seniors for Ser «Photoshop Black & White Smartphones Lightroom ff Photography & Tablets For Seniors [J For Seniors For Seniors ¥ BDM's Definit Pythons.C: for Beginners Python and C++ are two of the most powerful and feature-rich programming languages available to learn. Being able to understand and use either enables you to understand today’s technologies better and how they interact with us and our environment. Suide Series Python is a fantastic beginner's programming language that enables you to create tools, utilities, games and hardware controlled projects. C++ isan extremely powerful, high level language that's used to create everything from the latest games, to mobile apps and even the operating system on your computer or mobile device. Want to learn more? Dig in and read. Python Python's ease of use, while still being powerful enough to control hardware and execute complex algorithms, is what makes it such a great choice of programming language for the beginner. In this book we show you how to set up Python on your computer and how to get started with simple tutorials and guides. Python Power Within, you can leam how to use the core selection of Python's many commands and routines and create your own code that you can expand and improve on for use in the real world, We look at using variables, user input, loops, Python Modules and even Python graphics. C++ What do Windows, macOS, Linux, Android, i0S, and thousands of programs and apps used daily have in common? They're all created using custom libraries, software development kits, and C++. G++ isan incredibly versatile and powerful language, and while it can be complex, once you've mastered it, you'll be able to create amazing code, and greatly improve your job prospects. Working With C++ Discover how to install a C++ IDE and compiler, how to start coding in C++ and get to grips with elements such as strings, data types, user interaction, file input and output, loops and decision ‘making concepts. This bookis here to help you with your first steps into C+. Code Repository We've also included a selection of the ten most utilised Python programs from our code repository. These programs are freely available for you to use, alter and insert into your own code. There's code for creating random passwords, the beginnings ofa text adventure, a hangman game and graphical utilities.

You might also like