You are on page 1of 165
100% INDEPENDENT hints & tips inside Take Your Code:to the Next Level Discover how to create adventure games, graphics, animation and more Get to grips with the world’s Use our Code Repository to Top tutorials and guides to most powerful progamming enhance your own programs improve your coding skills language and more quickly and efficiently Discover more of our guides today... Seo ocd Py eT i" uild You Se eo ad H fxs nS uild Your aso Dead) Maciel eet Manua Metal i ») | \ iN a ‘odine odin SN tn EM con Ceres Cc att FRITZIBox} | Google Computing Manual Mantal (VE TaTOr-T Capen) Seo io told ee GoPro Instagram! |WhatsApp! | Internet Manual Manual Ra Manual” § s Fy mes am Phon reer eer o ie fee ie) | latelal=y Labeled Tale) Manual | Weta Maer te Manual ‘a i} BDM's Definitive Guide Series THE COMPLETE GUIDE Our modern digital world is made up of code. The Internet, our phones, TVs, games consoles, banking and virtually anything else you can think of, that’s connected in some way to the wider world, has some form of code behind it, driving it and telling it how to behave and what to do. That code can come in different forms, called programming languages. Some offer better stability, speed and complex algorithms. Others are designed for use with minimal system resources, in places that are impossible for an engineer to access and repair; the entire space and satellite communications industry runs off clever coding. In short, code surrounds and helps us in virtually every aspect of our lives. What a brilliant time then, to learn how to code; to see how a few simple lines of code can create something amazing and can interact with you and your technology. Python and C++ are two of the most popular and powerful languages to learn and with the help of this book plus a little imagination, you will soon be able to create amazing code. Now, turn the page and let's start learning how to code. www.bdmpublications.com ON due keel 8 Common Coding Mistakes 10 Python Beginner's Mistakes 12 C++ Beginner's Mistakes 14 Where Next? 18 WhyPython? 20 Equipment You Will Need 22 _ Getting to know Python 24 How to Set Up Python in Windows 26 How to Set Up Python in Linux PED ede cA) 30 Starting Python for the First Time 32 Your First Code 34 Saving and Executing Your Code 36 Executing Code from the Command Line 38 _ Numbers and Expressions 40, Using Comments 42 Working with Variables 44 User Input 46 Creating Functions 48 Conditions and Loops 50 Python Modules 54 Lists 56 Tuples ‘80M Definitive Guide Seris- Volume 24 res ee Raediak aretipietary 58 Dictionaries 60 Splitting and Joining Strings 62 Formatting Strings 64 Dateand Time 66 Opening Files 68 Writing to Files 70 Exceptions T2__ Python Graphics 76 Calendar Module 78 OSModule 80 Random Module 82 Tkinter Module 84 Pygame Module 88 Basic Animation 90 Create Your Own Modules Cy Tokens 94 Why CH? 96 Equipment You will Need 98 Howto Set Up C++ in Windows 100 Howto Set Up C++ on a Mac 102 How to Set Up C++ in Linux 104 Other C++ IDEs to install CTF aaa UCU lcd 108 Your First C++ Program 110 Structure of @ C++ Program 112 Compile and Execute exxe 152 Python File Manager aware tients 154 Number Guessing Game 156 _ Random Number Generator 157 _ Random Password Generator 126 User Interaction 128 Character Literals, 130 Defining Constants 132 _ File Input/Output 158 Text Adventure Script 160 Hangman Game Script @ “Good code is short, simple, and symmetrical; the challenge is = oe a Figuring out how to get there.” or Loop eas ~ Sean Parent (Developer and author) Working | with Code | aa ag . ed / WY 4 — 4 2 a | It’s always worth looking at the common pitfalls of coding before you start hitting away at the keyboard; after all, bad habits are often formed at the start of a process. IF you're aware of how to structure your code before you begin, then you will learn to avoid most of the mistakes that usually accompany poorly developed code. This section starts your coding journey by examining those common mistakes, as well as investigating where your coding skills can take you as your experience grows. “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) mmon Coding Mistakes Co UN tReoeeneneUa Te NRT MME Aue emery sg Cele crea iene ore ar een can Veo neu one Relea Sn MUN eM Cod CMO MMS occa Col es] 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 variables is @ must to eliminate common coding mistakes. Having letters ofthe alphabet isfine but what happens when the code states there's. a problem with x variable. t's not too difficult to name variables tives, money, playert and soon. Ie would be wonderful to be able to ‘work lke 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 cant do that. The First ‘major pitfallis someone trying to learn too much, too quickly. So take coding in small pieces and take your time. points = 1023; points); totalscore = //COMMENTS write("Your total Score is: “+totalscore); Use comments t's simple concept but commenting on our code saves so many problems when you next come to took overt Inserting comment nes helps you quick sift PLAN AHEAD through the sections of code that are causing problems; atzo useful if vounced to review an older piece of code: While its great to wake up one morning and decide to code 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 in depth cade requires a good working plan to stickto and help iron out the bugs. LON) aS site) a) BACKUPS RE-INVENTING WHEELS SECURE DATA Python Beginner's Mistakes Python isa relatively easy language to get started in where there's plenty of room for Reel coe Mr eM Rae eer) 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 ‘To1add to the confusion that most beginners already face when Python uses precise indentations when displaying ts code. The coming into programming, Python has two live versions oF its indents mean that the code in that section sa part ofthe previous language available to download and use. There'isPython version _statement, and not something linked with another part ofthe code. 2.T-xand Python 3.6.x. The 3.6.x version isthe most recent, and Use four spaces to create an indent, nt the Tab key. the one we'd recommend stating. But, version 2.7xcode doesn't always work with 3.6.x code and vice versa, python THE INTERNET COMMENTING Every programmer has and does at same point goon the Internet Again we mention commenting. l’s a hugely important factor {and copy some code to insertnta their own routines. There's programming, even ifyou'e the only one who is ever going to view ‘nothing wrong with using others’ code, but you need to knowhow the code, you need to add comments as to what's ging on. Is this the code warks and what it daes before you go blindly runningiton function where you lose life? Write a comment and help you, or your own computer. anyone else, see what's going on, Creatldlete fle na pynon program EID om eFintve Gude series-Volume 4 COUNTING LOOPS Remember thatn Python 3 loop doesn't count the last number you specfy ina range. Soif you wanted the loop to count from 1 to 10, then you will need to user n= ListCrange(i, 119) which will return 1 to 10. Breet =e x CASE SENSITIVE Python is a case sensitive programming language, so you will need to.check any variables you assign For example, LiV@S=1O is 2 different variable to lives=10, calling the wrong variable in your code can have unexpected results [TW enon 362 shen Fle_ESt_Shell_Debug Options Window Hep Fython 3.6.2 (¥3-6.2:5843305, Jul © 2017, 04 ‘on wind Type "copyzight", >> Laves=10 35> asvesns D> print (Lives, Lives) nt 3 Nczedite” or "License()" for mor BRACKETS Everyone forgets ta include that extra bracket they should have ‘added to the end ofthe statement. Python relies onthe routine having an equal amount of closed brackets ta open brackets, so any errors in your code could be due to you forgetting to count your brackets including square brackets. def print_game_status(se1f): print (board[len(self.missed_letters)]) Print ("Word: ' + self-hide word()) print (‘Letcers Missed: ',) for letter in self.missed letter: print (letcer,) print () print ("Letters Guessed: *,) for letter in self.guessed letter: print (letcer,) print () C Python Beginner's Mistakes Cl COLONS It’s common for beginners to forget to add a colon tothe end of a structural statement, such as ‘And Soon. The colonis what separates the code, and creates the indents to which the Following code belongs to. OPERATORS Using the wrong operator is also common mistake to make. When you're performing a comparison between two values, for example, you need to use the equality operator (a double equals, ==). Using 23 single equal =) isan assignment operator that places a value to 3 variable (such as, Ives=10). OPERATING SYSTEMS ‘writing code For multiple platforms is dificult, especially when you start to utilise the external commands ofthe operating system, For ‘example, iF your code cals forthe screen to be cleared, then For Windows you would use €LS. Whereas, for Linux you need to use ‘Elear. Youneed to solve thisby capturing the error and issuing it with an alternative command. 4 code to detect exror for using a airterent 05 ‘esayetem(‘eieas") print s\nssosooopooByzhon 3 File Managerceecececce\n') ———— z= Working with Code ) C++ Beginner's Mistakes There are many pitfalls the C++ developer can encounter, especially as this is a more CoMCeu eeu elec escme sc imeenachel tc cere rac) pene eh ats al Coil core foa VOID(C++, MISTAKES) ‘Admittedly’ 's not just C++ beginners that make the kinds of errors we outline on these pages, even hardened coders are prone to the odd mishap here and there. Here are some common issues to try and avoid. UNDECLARED IDENTIFIERS ‘Acommon C++ mistake, andto be honest a common mistake with ‘most programming languages, s when youtry and output a variable that doesnt exist. Displaying the value of x onscreen isfine but not ifyouhaver't told the compiler what the value of xis to begin with File Edit View Search Tools Documents Help SE Orns | Ou (citesttcpp x #include int main() I eeerrteercreetsy + SEMICOLONS Remember that each line of a C++ program must end with a semicolon ft doesn't then the compiler treats the line withthe ‘missing semicolon asthe same line with the next semicolon on. This ‘eates all manner of problems when trying to compile, so don’t Forget those semicolons. i#include int main() { int a, b, ¢, di 2-10; be20; 030) da20; std::cout << a, b,c, di EDD cows eFintive Gude Series -Volume 4 STD NAMESPACE Referencing the Standard Library is common For beginners throughout their code, but if you miss the std: element of 8 statement, your code errors out when compiling, You can combat this by adding: using namespace std; Under the #include part and simply using cout, cin and so on from then on. include Uelng namespace sta; ant main() < int a, by ea GCC OR G++ IF you're compiling in Linux then you willno doubt come across gecand g++. Inshart, gccis the Gnu Compiler Collection (or Gnu C Compiler as it used to be called) and get isthe Gnu ++ (the Cr+ version) ofthe compiler. IFyou're compiling C++ then you need to Use g++, asthe incorrect compiler drivers willbe used. a davidermint mate Documents Fle Edt view Search Terminal Help COMMENTS (AGAIN) Indeed the mistake of never making any comments on code is back ‘once more. As we've previously bemoaned, the lack oF readable identifies throughout the cade makesit vey difficult to look backat hawt worked, for both you and someone else, Use more comments. QUOTES ‘Missing quotes is @ common mistake to make, for every level of user Remember that quotes need to encase strings and anything that's {going tobe outputted to the screen or into a file, For example, Most compilers errors are due to missing quotes in the code, EXTRA SEMICOLONS \while 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 cade aren't complete statements. Such as include if lines switch Lines Fit sounds confusing don't worry, the compiler lets you know where you went wrong, TOO MANY BRACES ‘The braces, or curly brackets, are beginning and ending markers ‘around blocks of code, So for every {you must have a}. Often it'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 you. include using namespace > 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 difficult to include in an equation. When creating a variable, give it the value of zero to begin with: X=. include using namespace std; dint main() € int x: cout << xi » A.OUT ‘A common mistake when compiling in Linux is Forgetting to name your C++ code post compiling. When you compile Fram the Terminal, you enter: G+ code:cpp ‘This compiles the code in the File code.cpp and create an aut file that can be executed with a.out. However, iFyou already have code in acoutthenit's overwritten, Use: ‘gt+ ‘code.cpp =o! nameofprogram Fe Ede Vow Search Teri| tip C++ Beginner's Mistakes Cl z= Working with Code ) Where Next? Coding, like most subjects, is a continual learning experience. You may not class yourself ENed else aaa et Molen otal Mae co lcm olt meee MoT eee ecto} Dae M CoA age nee RCD Ue ener t= 1are NCCE ea im cere EAM Ne Ue Ue #INCLUDE What can you do to Further your skills, learn new coding practises, experiment and present your code and even begin to help, ‘thers using what you've experienced so far? TWITTER ‘Twitter srt all rolls and antagonists, among the well publicised vitriol are some genuine people who are more than wing to spread their coding knowledge. We recommend you find afew who you can ‘relate to and follow them. Often they post area tips, hacks and Fixes Forcommon cading problems. Oz KEEP CODING I you've mastered Python fairly well, then turn your attention to C+toreven CH. Sillkeep your Python sis going butlearing anew cading language keeps the old bran ticking over nicely and give youa view into another community, and how they do things differently OPEN PROJECTS Look for open source projects that you lke the sound of and offer to.contibute tothe code to keep it alive and up to date. There are millons of projects to choose From, so contact a few and see where they need help. It ay only be a minor code update butit’s a noble ‘occupation for codersto getinto SHARE SKILLS Become more active on coding and development knowledge sites, ssuch as StackExchange. If you have the skills to start and help others cut, not only wil you Feel really good for doing so but you can also learn alot yourself by interacting with other members. ( Where Next? Cl GOING MOBILE PORTFOLIOS The mobile market sa great place to test your coding skills and IF you've learned how to code with an eye For a developer jab in present any games or apps you've created. Fyour app is good, then the Future, then t's worth starting to build up an online portfolio ‘who knows, it could be the next great thing to appearon the app _of code Look t jab postings and see what skills they require, stores. t's a good learning experience nevertheless, and something then learn and code something with those skills and adit to the worth considering portfolio when it comes to applying, include a link to the portfolio, D cows = ee aa iz cronicedorg ONLINE LEARNING TEACH CODE ‘Online courses are good examples of where to take your coding _—_Can you teach? IFyour coding skills are spot on, consider skills next, even if you start from the beginner level again. Often, approaching a college or university to see ifthey have need for a an online course follows a strict coding convention, soif you're self-_ programming language teacher, perhaps a part-time or evening taught then it might be worth seeing how other developers ay out course. IF not teaching, then consider creating your own YouTube their code, and what's considered acceptable. how to code channel Learn to code interactively, for free me SHARE CODE HARDWARE PROJECTS Get sharing, even if you think your code isnt very good. The Contributing to hardware projects isa great resource For proving your criticism, advice and comments you receive back help you iron out code with others and learning fram other contributors. Many ofthe = 0) ‘Bef reshow cursor) centTrchildtestrocust) ‘TIMING Paine} Getsizet)s Sram) witeta < catcoune() ¢ f top = eateinev i) bottom 00 tn ieee oun 4 Sl[vrecnct oe) @| B/E ae eC #|>|/7@ oid arraycert::childLostrocus() : void Arraycerl::Paint(Oramt ) ( sip < column. catcount(); jase) ( F-Getabwadth tye); APT gel ee vartgrad Lj = cotum.catcount() - 1) = 0) , : Golor fe = lend scolordissbled, scolorPaper): fi(ePeop o sizeccy) breaks Pop t cata over an overheating heap of circuitry to create something akin to magic. All those aforementioned digital devices need instructions to tell. them what to do, and allow them to be interacted with, These instructions Form the programming core ofthe device and that core ‘canbe built using a variety of programming languages. ‘The languages in use today differ depending on the situation, the platform, the device's use and how the device wil interact wth ts ‘environment or users. Operating systems, such as Windows, macOS ‘and such are usually a combination of C+, CH, assembly and some Form of visuat-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and so on. More general-purpose programming is used to create programs, _apps, software or whatever else you want to cal them. They're widely used across all hardware platforms and suit virtually every ‘conceivable application. Some operate Faster than others and some >a ob: {are easier to lear and use than others. Python is one such genera: purpose language. Python is what's known as a High-Level Language in that 'tlks! to the hardware and operating system using avarety of arrays, variables, objects, arithmetic, subroutines, loops and countless ‘more interactions. Whilst it's not as streamlined asa Low-Level Language, which can deal directly with memory addresses, cal stacks and registers, ts benefits that it’ universally accessible {and easy to lear, Python was created over twenty six years ago and has evolved to became an ideal beginners language fr learning how to programa computer.’ perfect for the hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves or a piece of external hardvare and the computer tse Python i Free to download, install and use and is availabe For Linux, \windows, macOS, MS-DOS, 05/2, BeOS, IBM iseries machines, and ‘even RISC OS. Ithas been voted one of the top five programming languages in the world and fs continually evolving ahead of the hardware and internet development curve Soto answerthe question: why python? Simply pt, it's free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational tool. [/7FiTe: invoke. java. Fimport java. lang.reflect.*; class rnvoke { public static void main¢ string [] args ) ¢ ryt Glass = class. fornane( args[0) 9; hethod'n = c-getmethodt args{l}, new Class 00) 3 Object ret = _m.invokeC mul1, null 9; Systen.out prineInc “Tnvoked static method: " + args{1] + of class: © # args(o] tm with no args\nnesults: " + ret); 3 catch ( Classnotroundexception e 5 { 77 Clags.fornane(.). can't find the class } Catch C NosuchMethodexception 2") { Javaisa powerful language that’s used in web —_ ‘pages, set-top boxes, TVs and even cars. Python isa more modern take on BASIG, it's easy to learn and makes for an ideal beginner's programming language. ce Why Python? py=35, §2i°Fo 10 Trt) ase ea see EGG AHES OO Ve a 88 Eri ne HEN LET s=s41 pnscores ss NeXT y. BASIC was once the starter language that early B-bit home computer users learned. na bempuplcatons = y Say Hello to Python ) Equipment You Will Need ole TaN Tae RUHR BA UL e CUNT ICL 1k Rel TIO 1aCe = ee na ol) 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. 00 ti ie Ses oun COMPUTER Obviously you're going to need a computer in order to learn how to program in Python and to test your code, You can use Windows (from XP onward) on elther a 32 or 64-bit processor, an Apple Mac or Linux installed c. [_] AN IDE AniDE (Integrated Developer Environment) is used to enter and execute Python code. It enables you to inspect your program code and the values within the code, as wells ofering advanced Features. There are many different IDEs availabe, 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, you need to ensure that you're running the latest version of Python, Windows users need to download and install Python, which well cover shorty [_] TEXT EDITOR Whilst a text editors an ideal ervironmentto enter cade into, it's not an absolute necessity. You can enter and execute code cirecty From the IDLEbuta text editor, such as Sublime Text or Notepad++, offers more advanced features and colour coding when entering code. INTERNET ACCESS Python isan ever evolving environment and as such new versions often introduce new concepts or change existing commands and code structure to makeitta more efficient language. Having accessto the Internet wil kep you up:to-date, help you out when you get stuck and sive access to Python's immense number of modules. L] TIME AND PATIENCE Despite what other books may lead you to believe, you won't become a programmerin 24-hours. Learing to code in Python takes ime, and patience. You may become stuckat times and ther times the code wll Flow Uke water, Understand you're learning something entirely new, and ‘you wil get there. ( 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 fantasticlearning platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many modules and extras. Saag) he Raspberry I 3 the latest version, incorporating a more powerful CPU, more memory, Wifi and Bluetooth suppor. You can pick up a Pi for around €32 or as apart of kit for £50+ fepending on the kit you're interested in. FUZE PROJECT he FUZE isa learning enwironment built on the latest model ofthe Raspberry Pi. You can purchase the workstations that came with an electronics kit and even a robot arm for you to build and program. ‘You can find more information on the FUZE at wwwaFuze.co.uk Coding for” inu We have several great E Raspberry Pititles available via wwwbdmpublications. he Raspberry P's main operating system isa Debian based Linux distribution that comes with everything you need in simple to use package. t's streamlined forthe Piand is an ideal platform for hardware and software projects, Python programming and even asa desktop computer. Raspberry Pi she Beginners’ Guide G z= Say Hello to Python Getting to Know Python Ma ieeccecceet catered earl Rumer cite ears So UECoM AUR en oe mee Reo Leelee (Ure ent Leda (EO) one 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. ‘A programming language isa listof instructions that a computer Follows. These instructions can be as simple as displaying your name orplaying a music ile, or ascomplexas building a ‘hole virtual world. Python isa programming language conceivedin the late 19805 by Guido van Rossum Eat Centrum Wiskunde & Informatica (OW) in the Netherlands asa successor to the ABClanguage. PROGRAMMING RECIPES "SASS Programs are lke recipes For computers. A recipe to bake a cake could go like this: Put 100 grams of selfraising flourin a bow ‘Add 100 grams of butter tothe bowl, ‘Add 100 mliitres of milk. Bake for half an hour. CODE Just lke a recipe, @ program consists of instructions that you follow in order. A program that describes acake might run like ths: bon = flour = 100 I butter = 50 milk = 100 ‘bon .append( [flour butter mic] If cake. cookCbonl) Guido van Rossum, the Father of Python. PROGRAM COMMANDS You might not understand some of the Python commands, lke bowl. append and cake.cook(bowl) The firsts alist, the second an object; we'l look at both inthis book. The main thing to know is that it’ easy to read commands in Python. Once you learn what the commands do, it's easy to Figure out how a program works, 00 tn ie Ses oun HIGH-LEVEL LANGUAGES Computer languages that are easy to rea Thisis because they fly high above the hard re know 25 highevel re (also referred to as ‘the metal’), Languages that fly close to the metal lke Assembly, Low-level languages commands read abit ike thisimsg db ,@xa len equ $ = msg ‘are known 3s low-level a PYTHON 3 VS PYTHON 2 Pca eur ec at ieee aT es eee Lene! eee WORLD OF PYTHON ete ee erie Paes te tet! PYTHON 2. eee ions ect Plone Cr Siero tee peers eee) (cetingtoroonxinon CE ZEN OF PYTHON Python lets you access all the power of a computer ina language. that humans can understand, Behind all this isan ethos called "The Zen of Python.” Thisis collection of 20 software principles that influences the design ofthe language. Principles include “Beautiful isbetter than ualy" and "simple i better than complex." Type import: this into Python and it wil dsplay al the principles. Ce Ce eg td PYTHON 3.X geaoisiuene eames Rae einen Pen te ett more stable, effective and efficient programming Tne tae ee go etd pose oer te ea Peete Pee ted Seca 3.X WINS eeiemeeereein este erated auoh ththe in to phase out the previous Cee eer De Python 3 For snippets of important code, z= Say Hello to Python) How to Set Up Python in Windows Windows users can easily install the latest version of Python via the main Python Downloads page. While most seasoned Python developers may shun Windows as the 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, 's an easy process to follow. ESTEE 2"tby opening your web browser to www.python, ‘ra/downloads/. Look fr the button detailing the download link for Python 3.x. The latest version atthe time of \weiting i 3.7.0 but as Python is frequently updated this may bea different version for you. Click the Download button for version 3x, and save the file to your Downloads folder. When the fle is dawnloaded, double-lick the executable and the Python installation wizard wil launch, From here you have two choices Install Now and Customise Installation. We recommend opting for the Customise Installation link. Siar Install Python 3.7.0 (32-bit) pyth wind EZ) 2007's vetnine uid Series- volume 34 BRTEREDD Choosing the Customise option allows you to specify certain parameters, and whilst you may stay with the defaults, i’ a good habit to adopt as sometimes (not ‘with Python, thankfully) installers can include unwanted additional Features. On the fist screen available, ensure all boxes are ticked and click the Next button, IP So peers ® —_ yar ra a es rn) eh ebb . wind eee a Come The next page of aptions include some interesting additions to Python. Ensure the Associate file with Python, Create Shortcuts, Add Python to Environment Variables, recompile Standard Library and Install for All Users options are ticked. These make using Python later much easier. lick install when you're ready to continue. | putl winds ‘Advanced Options (anna wth fn fi gy) hasbeen oemeent rane [eget eae How to Set Up Python in Windows Cl ‘Youmayneedto confirm the installation withthe uae ‘Windows authentication notification. Simply click SUES Yes and Python wil begin to instal, Once the installation is con the Final Python wizard page will allow you to notes, and Follow some online tutorials. icking on the IDLE Python launch the Python Shel, where you can b ete _ your Python programmin the latest release aslong asit'sPython Python 3 interface, sin worry if your version is ‘our code works inside your Setup was successful | e =-— pythdn windows. om 1 this time type: CMD, you'll be presented with the Command Prompt ink. Click it to get to the Windows command ine environment. To enter Python within the command line, you need ements totype: python and press Ente can Close the shield detalled Disable Path Length Limit This will allow Python '0 bypass the Windows 260 character limitation, enabling you to ‘execute Python programs stored in deep folders arra ‘Again, click Yes to authenticate the pracess; then installation wine © Disable pathlength mit close moe EERE te command tine version of Python worksin much the sare way asthe Shell you opened in = Step 8; note the three leftfacing arrows (>>>). whilst it's a perfect Fine environment, it's not tao user-friendly, so leave the command line For now. Enter: EKUEO to leave and close the Command Prompt window te tale Phen onan ty sed econ (32-bit) will launch the bom I Python when clicked (more ‘on that in a moment), To ‘open the IDLE, type IDLE into Windows start 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, but for this particular tutorial, we will stick to Linux Mint. First you need to ascertain which version of Python eu?) is currently installed in your Linux system. To begin ‘with, drop into a Terminal session from your distro's menu, or hitthe CtrlsaltsT keys dovide david atine ~ come with both Python 2 and 3, as there's plenty of code out there stil available For Python 2. Now enter: python3.==versien. avidodavidine:~ Inour ase we have both Python 2 and installed Sue) = AS long as Python 3.x.xis installed, then the coc cur tutors wl work es aways worth checking tose the dstro hasbeen updated with the latest version, enter: sud apt-get Update 8E sudo apt-get upgrade to update the system envidedsv ine ‘8DMs Definitive Guide Seris- Volume 24 ‘Once the update and upgrade is complete, enter: ED ytnona version santoseeifPytion 3x isupdated or even installed. As long as you have Python 3%, running the most recent major version, The numbers after the 3. indicate patches and Further updates. Often they/re unnecessary, but can contain vital new elements. owever, iF you want the latest, cutting edge version, oul need to build Python from source. Start by entering these commands into the Terminal: sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev Libncursesn5-dev libssl-dev libsqlite3-dev tk-dev Libgdom-dev Libc6-dev Libbz2-dev How to Set Up Python in Linux (Open up your Linux web browser and go to th { step ) the GUIIDLE, you'll need to enter the following SUED eon dovnload page:hetpsy/wwwpython.ora/ Maal mmandnto the Terina downloads. Clickon the Downloads followed by the button under the Python Source window. Thisopensa download dialogue box, SHdO-apt=get “install idles choose a location and start the download process. ‘The IDLE can then be started with the command: ULB. Note that IDLE runsa different version from the one you installed from source, “dv avi ain.-/oowmloa/Pyhon 372 you've downloaded), To access the new unzipped folder enter Cd) saesesssesssnessssseeeecececesenevnnnnnnsennsgetsseansnnenne Python-3.Y.¥/ FEET ou'latso need PP (ip installs Packages), whichis atool to help you install ore modhles and extras, Enter: sudo apt-get install. python3-pip IPs then installed, check For the latest update with pip3 install --upgrade pip When complete, close the Terminal and Python 3x willbe available via the Programming section in your distro's menus widen Dominion 72 - ESTED) Within the Python folder, enter: “/configure sudo make altinstall This could takea while, depending on the speed of your computer. Once finished, enter: python3.7 ==version to check the latest installed version. You should now have Python 3,7 installed ‘alongside older Python 3.xx and Python 2. PYTHON ON COS Installation of Python on mac0S can be done in much the ‘same way as the Windows instalation, Simply go tothe Python webpage, hover your mouse pointer over the Downloads link and select Mac 0S x from the options. You will then be guided tothe Python releases For Mac\versions and the necessary installers for macOS 64-bit, For 05 X 10. and later. wor bmpublcations com Index ) — Bjarne Stroustrup (Developer and creator of C++) i | BOM Definitive Gide Series Volume 34 ( Getting Started with Python Learning how to code may seem a little daunting at First. Thankfully, the Python language has been designed with simplicity in mind. Like most things, you need to start slow, learn how to get a result and how to get what you want from the code. In this section, we will cover the core concepts: saving and executing your code, variables, numbers and expressions, user input, conditions and loops. 30 Starting Python for the First Time 32 Your First Code 34 Saving and Executing Your Code 36 Executing Code From the Command Line 38 Numbers and Expressions 40 Using Comments 42 Working with Variables 44 User Input 46 Creating Functions 48 Conditions and Loops 50 Python Modules wor bmpublcations com Zz Getting Started with Python Starting Python for My the First Time The Raspberry Pi offers one of the best all-round solutions For learning and coding on, Meneame eons enatieracnmuca ekenehut cence ce hte latest stable version of Python 3, which makes it a superb coding platform. 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 for coding, PETER with the Raspbian desktop loaded, cick onthe FETTER for cxample, inthe Shell enter: 242 "Menu button followed by Programming > Python 3 After pressing Enter, the next line will display the (OLE), This will open the Python 3 Shel, 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. ‘meni and via Finder. mm PRPTP BD The shellis where youcan enter cade andsee the — ESAFB the Python shall acts very much ke a calculator, responses and output of code you've programmed since cade i basically a series of mathematical into Python. This is akind of sandbox, where you're ableto try out interactions with the system. Integers, which ae the infinite some simple cade and processes sequence of whole numbers can easily be added, subtracted, multiplied and so on. Shoe SapyrgpeSereaies or “Bicwmae" for nore sntarntic. Starting Python for the First Time E mm ESR While thats very interesting i's not particularly exciting, Instead, try this printC*Hello everyone!”) Just enter it nto the IDLE as you id in the previous steps. clicking on the Highlighting tab. However, we don't recommend that _asyou won't be seeing the same as our screenshots, pe emer «uae as vo = case the Hello everyone! bt. >>> print(“Hello everyone!™) Hello everyone! >>| EeTeeEAD You may have noticed the colour coding within the Python IDLE. The colours represent different elements of Python code. They ae: Black— Data and Variables, Green~Strings Purple Functions (Orenge-Commands Blue — User Functions Dark Red Comments Light Red ~ Error Messages, IDLE Colour Coding aekred | Comments | naneaber VAR awtres[Erermoseote | syntanteror FETED ust lke most programs avaliable, regardless of the ‘operating system, there are numerous shortcut keys avallable. We don’t have room for them all here but within the Options > Configure IDLE and under the Keys tab, you can see alist ofthe current bindings. The Python IDLE s a power interface, and one that's actually been written in Pythan using ane ofthe available GUI toolkits. you want to know the many ins and cuts forthe Shell, we recommend you take a few moments to view ‘www.docs.python.org/3/library/idte.html, which details many oF the IDLE’ Features E) ceinsteatnaenn Your FirsE Code Essentially, you've already written your First piece of code with the ‘print(“Hello OVA Mit ae efor N eS KS ot T et Cotes OA eT Lear Le LiTel ole 1a entering your code and playing around with some other Python examples. PLAYING WITH PYTHON wi most languages, computer or human, it’s all about remembering and applying the right words to the right situation, You're not born knowing these words, so you need to learn them. STEERED you've closed Python 3 IDLE, reopen itin whichever operating system version you prefer. In the Shell enter the Familiar Following: print (“Hello”) ESTeeE RD vst as predicted, the word Hello appearsin the Shellas blue text, indicating output from a string 'sfally straightforward and doesnt require too much explanation, Now try print(*2+2") ETD 200i vole PETER You can 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 tothe IDLE Shell to print the total of 2+2 you need to remove the quotes: print(2+2) pets, BATeEE MD You can continue as such, printing 242, 46442343 and s0.0n ta the Shell. An easier way is touse a variable, which is something we wil cover in more depth later. For row, enter: ir ( Your First Cod (Your First Code Cl \What you have done heres assign the letters and b two values: 2 and 2, These are now variables, \which can be called upon by Python to output, add, subtract, divide {and soon for as long as their numbers stay the same. Try ths: printCa) print(b) (eB Sn) oy Otene o_ PRED Now let's add a surname: ‘surnane="Hayward” print(surnane) ‘You now have two variables containing a frst name and a surname ‘and you can print them independently, “a em sh pty om nts wen Ss eerie ereits” oe “Lcesay” for ere eformation. Fe BETTE 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 use the folowing print(a+b) ‘This cade simply takes the values of a and b, adds them together, and outputs the result Se cen sen em Peasy or a TT eal BETS AD You can play around with different kinds of variables and the Print Function. For example, you could ‘assign variables for someone's name: nane="David” print(name) STEEED ve were to apply the same routine as before, Using the + symbol, the name wouldn't appear correctly in the output inthe Shell. Ty it print (Cname+surname) You need a space between the two, defining them as two separate values and not something you mathematically lay around with, print(name, surname) In Python 3 you can separate the two variables with aspace using a comma ‘Alternatively, you can add the space ourselves: printCnane+” “#surnane) ‘The use of the comma is much neater, as you can see, ‘Congratulations, you've ust taken your First steps into the wide ‘world of Python, worm mpublcatonscom Na AVAXHOME? nee cd providing you various content: LC eC a Ee ee eS mea eas ces Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction PRE Uys ETC emer ol Tei AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu C3 Getting Started with Python Saving and Executing Your Code VCR ten esas tert ren eee Cele Ea ee eto Cena cnc ca acceil cicero otha intel ele 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. ESTEE F'st-open the Python IDLE shell and when it’s up, JESISESSEMM You can see that the same colour coding isin place dlickon File > New Fie. This will open a new window Inthe IDLE Editor asitisin the Shel, enabling you ‘with Untitied as its name. Thisis the Python IDLE Editor and within it vo better understand what's going on with your code. However, to you can enter the code needed to create your Future programs. _ execute the code you need to first save it. Press FS and you get a Save...Check box open, TheoLe eaters ferateensng pens TRIAS cikonthe atone Sve boxandseets Sue simple text editor with Python features, colour cue? destination where you'll save all your Python code. cading and so on; much inthe same vein as Sublime. You enter ‘The destination can be a dedicated Folder called Pythan or you code as you would within the Shell so taking an example from the _canjust dump it wherever you lke, Remember to keep a tidy drive previous tutorial, enter: though, to help you out inthe Future. printC*Hello everyone!”) GET 220.4 C Saving and Executing Your Code Cl Enter name for our ode print hel for Susp ‘example, and click on the Save button. Once the Python codeissavedi's ected andthe output wil be detaled in thelDLE Shell ntiscase the words Helo everyone! FETTER Thisishow the vast majorty of your Python code willbe conducted. Enter it into the Editor, hit F5, save the code and look atthe output inthe Shell. Sometimes things will fer, depending on whether you've requested a separate window, but essentially that’s the process.’ the process we will Use throughout tis book, unless otherwise stated Let's extend the code and enter afew examples From the previous tutoriat 2 be2 name="David” surname="Hayward” printCname, surname) print (a+b) IF you press FS now youll be asked to save the file, again, s t's been modified from before. IF you click the OK button, the File willbe ‘overwritten with the new code entries, and Siar ‘executed, withthe output in the Shell. I’s not a problem with just these Few tines butf you weretto edt a larger file, overwriting can become an issue. Instead, use File > Save As from within the Editor tocreatea backup, muvee Fe Sie Nn Ifyou open the file location ofthe saved Python code, youcan see that it ends in apy extension. Thisis the default Python file name. Any code you create will be whatever py and any code downloaded from the many Internet Python resource sites willbe oy. Just ensure that the code is written for Python 3 Now creates new fle. Close the Eto, and open Sue ily a new instance (File > New File from the Shell). Enter the following and save tas hello. py: ‘a="Python” be"is? c="cool!” print(a, b, ¢) ‘You will use this code in the next tutorial Talay. aaplbommanaihyhon Conhalony Oa ie Se Fart in Spore aro bee seine ation 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. BEER °th00, in Linux, comes with two pot ‘executing code via the command line, One of the with Python 2, whilst the other uses the Python 3 libraries smmand python3 and press ‘on. First though, drap into the command line or Terminal on command lie version of the Shell acing aroy cursor (22>) ourre atthe command line we can start n, For Python 3 you need to enter the I!putyou into the familar three right iter. This witht Yyour operating system, fore, aan EED sm here you're able to enter the code you've reusing a - io such as il nc ana he Start button and printca) You can see that it works exactly the same. 9 their command line by clicking > Utilities > Terminal ‘8DMs Definitive Guide Seris- Volume 24 Executing Code from the Command Line Cl FEPTID Now enter: exit toleave the commandline Python EMIMM The result of running Python 3 cade From the session and return you back tothe command thon 2 command line is quite obvious, Whilst it mpt. Enter the Folder where you saved the code from the doesn't error out in any way, due to the differences between the ious tutorial and list the available files within; hopefully vou way Python 3 handles the Print command over Python 2, the result should see the hello.py ile, isn’t as we expected, Using Sublime For the moment, open the hellopy file Jom thn the same folder asthe code youte sine SublieText sit avaiable forthe Raspbery SAD trun cncer the alowngintothe EME 0 gongtoteroorary tease the Pierce need to use the Python IDLE. with the hello. file open alter itto the Following that you don’t necessarily python3 hello. py inclu his will execute the code we created, which to remind you is: ” “ " “ “ name=input¢“What is your name? “) ‘o="Python” print(*Hello,”, name) brig? c="cool!” 2 print(a, b, <) ktothe Natural since hs i Python 3 code, sng he Save the logy le and ro eur syntax and layout that’s unique to Python 3, it only Sua) command line. Now execute the newly saved works when you use the python3 command. iFyoulike,trythe same code with with Python 2 by entering python3 hello. py python hello.py illbe the orginal Python is New Fle) and create a simple variable and print command: 10 print(“The value of A is,”, a) ‘Save the file and execute the code, Running the code will return the line: The value of A is, 10into 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) ST) 220 cates vole PSTIIEDD Resave the code and execute it, You can see that the ‘outputin the IDLE Shells stil the same as before, despite the extra lines being added, Simply put, the hash symbol (#) {denotes aline of text the programmer can insert to inform them, ‘and others, oF what's going on without the user being aware. Ler’s assume thatthe variable A that we've created Is the number of lvesina game. Every time the player dies, the value is decreased by 1. The programmer could insert aroutine along the lines of ona=1 print(*You’ve just lost a life!”) printC*You now have”, a, “Lives left!”) ye (Us Ce ts, (Using Comment Cl Whit ve now that th variable Ais ves, and Susp that the player has just lost one, a casual viewer or someone checking the code ay nat now, Imagine foré moment thatthe code twenty thousand lneslong, stead of st ur seven Youcan se hwhandy comments ar Essentially, the new code together with comments STEP 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! ana # Inform player, and display current value of A lives) print(*You’ve just lost a life!”) printC*You now have”, a, “Lives teft!”) You can use comments in different ways, For example, Black Comments are a large section of text that details what's going on in the code, suchas telling the code reader what variables you're planning on using # This is the best game ever, and has been developed by a crack squad of Python experts 4 who haven’t slept or washed in weeks. Despite being very smelly, the code at Least # works really well. nin comments ar comments that follow a section Burg) 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 A to 10 printC*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!”) printC*You now have”, a, “Lives left!) # Inform player, and display current value of A (lives) Fa SST son FATED “he 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) intc"The value layer ost a 1ife! ]# Inform player. and display current value of A (Lives) Jorane(“vou've just lost a. ifel") Print(-You non have", a, “lives Left!*) aise", a You also use three single quotes to comment. ‘uta Black Comment ar multiline section of ‘comments. Place them before and after the areas you want to ‘comment for them ta work: This is the best game ever, and has been developed by a crack squad of Python experts who haven’ slept or washed in weeks. Despite being very smelly, the code at least works really well. wmvinccccoson CE C3 Getting Started with Python Working with Variables SVE TE Col noc) LLIN 1M Role aaron Reole|-F-1K--[eh AN eel S remanence annotate es enteciet} NU TON CUT oe 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 pr IDLE Shell to clear up any old code. In some programming languages you're required tose a dollar sign to denote a string, which is 2 variable made up of multiple characters, uch asa name ofa person. In Python this isnt necessary. For example, inthe Shell enter: nane="David Hayward” (or use your own name, unless you're also called David Hayward). ‘ue Ea Oo) Cas ies ro ln Girard the variable inside the brackets. In our example, tis would be: type name). Adda new string variable: titles*Descended from Vikings". You can check the type of variable in use by issuing the type () command, placing the name of D220. cites voles PEPER Youve seen previously that variables can be concatenated using the plus symbol between the variable names. n our example we can use: print: Cname +": + title), The middle part between the quotations allows us to ‘add a colon andaa space, as variables are connected without spaces, ‘so weneed to add them manually. 1 ES) oy Ets om Em vou can also combine variables within another variable. For ‘example, to combine both name and tile variables into anew variable we use: charactersnane +: + title ‘Then output the content of the new variable as: print character) Numbers are stored as different variables: o9e=44 Type Cage) Wich are integers as we know. (wor ing with Variables Cl However youcantcombine both stings and Susp integer type variables in the same command, as you ‘would a set of similar variables. You need to either turn one into the ‘other oF vice versa. When you do try to combine both, you get an error message: print Cname + age) PEPEED This presents bit of aproblem when you want to work with @ 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. ESTEEM 1's is process known as TypeCasting. The Python code is print (character +“ is “+ strCage) +“ years: old.”) oryoucan use: print (character, “is, age, “years old.”) Notice again thatin the last example, you don’t need the spaces between the wordsin quotes asthe commas treat each argument toprint separately >>> print (name + age) Traceback (most recent call last): File “". line 1, in ‘brant’ (none + 36) Typetrror: Can't convert “int object to str inplicitly SbSGrane (characters ° as" satr(age) 4 years el") David Hayward: descended from Vikings is 44 years old. SSSlorine (character, sis", age, sears 014.0) David Hayward: Descended from Vikings is 44 years olé. BL Another example of TypeCasting when yous for Sure input From the user, such as a name. for example, enter age= input (“How old are you? “) Alda stored othe iputconmandisstored asa string arabe le at shel eb Oars Windows He eyehon 3.2 Ceefot, Get 1 BONE, T3TTY eae eee ae BRTEREDD the use of typecasting is also important when dealing with floating point arithmetic; remember: numbers that have a decimal point in them. For example, enter: shirt=19.99 Now enter type(shiint) and you'llsee that Python has allocated the number as a float’, because the value contains a decimal point. Z (Getaule, Ot 18 2014, THRTTD (ee s.9:4) on Linus type Sepprigye™ "eresite or “Liens for mare information 35 Gpetansee) clas "float ‘When combining integers and floats Python Usually converts the integer to a loat, but should the reverse ever be applied i's worth remembering that Python doesn't return the exact value, When converting afloat to an integer, Python will always round down to the nearest integer, ‘aed truncating; in our case instead of 19.99 t becomes 19, | Ble at Sel_Debug Options window ly ae risa as erie ae Bere, Tasty ye “License()* for more information. ———— C3 Getting Started with Python User Input WATE TE Co) uae ee Len ep ea Aeole iceman eel oy earlier, so now would be a good time to Focus solely on how you would get information Tee mance aetna 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. ESTED it’s not already, open the Python 3 IDLE Shell, FATED Xow that we have the user's name stored ina and tart a New Fie inthe Editor. Let's begin with couple of variables we can call them up whenever something rally simple, enter we want printC*Hello”) printC*Welcone”, firstname, surname, “. T hope firstname=input¢“What is your first: name? “) you're well. today.") print(*Thanks.") surnane=input(“And what is your surname? “) BRTeERD See and execute the code, and asyoualreadyno EPI Run the code and you can see a slight issue, the doubt suspected, in the IDLE Shel the program will full stop after the surname Follows a blank space. ask for your first name, storing itas the variable firstname, followed To eliminate that we can add a plus sign instead of the comma in by your surname; also stored ints own variable (surname). the code: printC‘Welcone”, firstname, surnames. I hope you're well today.”) eee yor sent ed GT 220s vole 3 (User input Cl ‘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?”) ‘nane=inputC) useringut py - home/pi/Documents/Python Code/is) BETTER) The code rom the previous step is often regarded asbeing alittle neater than having a lenathy ‘amount of text in the input command, butt’s not arule that's setin stone, so do as you lke in these situations. Expanding an the code, tay this print(“Halt! Who goes there?”) names input© what you've created here sa condition, which we will over soon. In short, we're using the input from the user and measuring it against a condition, So, the user enters, David as their name, the guard will allow them to pass unhindered. Else, iF they enter aname other than David, the guard challenges, them toa fight, Just. as you learned previously, any input from a Users automatically string, o you need to apply 2 Siar ‘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 printC“Input a rate and a distance”) Fate = floatCinput(“Rate: “)) PRPIIED |: 2 g000 star to atext adventure game, perhaps? Now you can expand on it and use the raw input from the user to flesh out the gamea little: ‘if name=="David”: printC*Welcome, good sir. You may pass.”) else: print(*I know you not. Prepare for battle!’ SS ie Set Fart in Sts nde ee BRTSET DD 1 finalise the rate and distance code, we can ade distance = floatinput(“Distance: “)) print(“Time:”, (distance / rate)) Save and execute the code and enter some numbers. Using the flost{input element, we've told Python that anything entered isa Floating point number rather than astring, seine ation C3 Getting Started with Python Creating Functions Now that you've mastered the use of variables and user input, the next step is to tackle (itten (oe UALS te RCM red eee AS eco Te Dol aa esTe.A) enables you to define your own functions. FUNKY FUNCTIONS ‘A function is a command that you enter into Python to do something. It's alittle piece of selF-contained code that takes data, ‘works on it and then returns the result, ESTEE isnot just data that a Function works on. They can do all manner of useful things in Python, such as sort data, change items From one format to another and check the Length or type of tems. Basically, a function isa short word that’s Followed by brackets, For example, len0, list or typeO). FETED function takes data, usually a variable, works on it depending on what the Function is programmed todo and,eturnsthe end value. The data being worked an goes Inside the brackets, so if you wanted to know how many letters are in the word antidisestablishmentarianism, then you'd enter: ‘Len¢“antidisestablishmentarianisn’) and the nurnber 28, would return, NT 220i sees vole BATERE RD You con pass variables through Functions in much number of letters ina person's surname, you could use the following code (enter the text editor For this example): ame=input (“Enter your surname: “) count=Len(name) print C*Your surname has“, count, “Letters in ima Press FS and save the code to execute it. Python hastens of functions built nt it, Fartoo ‘mary to getintin the limited space available here. However, o view thelist of bultin functions available to Python 3, navigate to wwww.docs.python.org/3/library/Functions.html, These are the predefined Functions, butsince users have created many ‘more, they're nat the only ones availabe. ( Creating Functions Cl They add Functions and c example, to use adv be imported as and when required. For _justimportedit into sed mathematics Functions enter Todo so, enter ‘import math math. sqrt(i6) ‘nce entered, you have access tall the Math module Functions. n, you can utilise the square root Function can see thatthe code is presented as module function(data. FORGING FUNCTIONS Ree nse en ee Cee Ren aoc iad pee eu ae eeu eet eM ce Cong no eee ecg n called Hello, that greets a user. 5 in the script and press CtrisSto sav i Press F5 to save and run the script. You can see Hello inthe Shell, en ea hance ee ceed PEPPER 10: now expand the function to accept: BETeEE RD What you've just done is import the Hello Fu variable, the user's name for example, Edit from the saved Hello.py program and then used it rere to-say hello to David. This is how modules and Functions work: you Z A dul then use the Function, Try this one, and modify print C*Helto” nae) it HelloC“David”)| accept the variable name, otherwise it prints Hello eee Same Cet Peete C3 Getting Started with Python Conditions and Loops (eon CO Se AFSC ee eur seed Sen e TCL elenrimeolol eas OWA OUR Men Tu Ke oLine elk CN RNA Ane Cele ERK} achieve; they could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking if something is TRUE, then doing something else if it is't. ESEGRED ct's create 2 new Python program that will ask EATER Xow y0u can use anifstatementto checkif the the user to input a word, then check it to see iit's word length variable is equal to Four and print 3 afourletter word or not, Start with File > NewFile, and begin wth Friendly conformation fit applies tothe ule: ae word-input(*Please enter a four-letter word: *) word=input(“Please enter a four-letter word: “) —_word_length=LenCword) if word_length == 4: print (word, “is a four-letter word. Well done. means checkif something is equal to ‘The double equal sign ( something else. BST ow we can create anew variable then use the len EESMFBM The colon atthe end of IF tells Python that if this Function and pass the word variable through it to statements true do everything after the colon get the total number of letters the user has just entered: that's indented. Next, move the cursor backto the beginning of es = the Editor wordsinput(“Please enter a four-letter word: “) word_lengthelen(nord) wordsinput(“Please enter a four-letter word: “) word_Length=LenCword) if word_length == 4: print (word, “is a four-letter word. Well TF) done”) else: print (word, “is not a four-letter word.”) 220. cite sees vores Press and save the cade to execute it. Ente a fourletter word in the Shel to begin with, you should have the returned message that’s the word is four letter, he program but ths time enter a display thatit'snotaFourletter word Now press F5 again and rerur Fiveetter word. The Shell wil LOOPS (Conditions and Loops Cl FETT ow expand the code to include another conditions. Eventually, it could become quite complex. We've added a condition for threeletter words: word=input(“Please enter a four-letter word: “) word_Length=lencword) if word_tength = 4: print (nord, “is a four-letter word. Welt done.) elif word length print (Word, “is a three-letter word. Try again.”) else: print (nord, “is not a four-letter word.") eee er nae ene eee Ne ern eed block of code a number of times, usually with the support of a condition FRPP 00: start witha simple while statement. Like I Errore altri peemeretts = i fwriTe x < 103 print} te at Fmt i Gos Yrs tp PEPER The citference between if and while is when while Peg einer Persea teat Eo acme et arate a Rens EERE 1 For loop is anoth eee tert een frords=f*Cat™. “Dog, “Unicorn for word 1n words STEP 4 ue me ete ecg Come terseee tcs ffor x in range (1, 10):) print Go) Bees ry ee eee eet ett 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, Atvoughsoed.thebutnfunensuthin thon ERR re ets an eon te LE Sel. the na?) are limited. The use of modules, however, allows us Pygame module isn’t recognised or installed in 20 make more sophisticated programs, As you are aware, modules Python, To install a module we can use PIP (Pip lstalls Packages) ‘are Python scripts that are imported, such as import math. Close down the IDLE Shell and drop into a command prompt oF erminal session, At an elevated admin command prompt, enter pip install pygane res an elevated status nts at different locations. Fight: SED mere cyeceresten ns ER reve amin n-P platforms isthe Pygame mo jeate games. Ty: import pygame. 3 use the Sudo command, with sudo pip install package. example on many funeti ‘8DMs Definitive Guide Seris- Volume 24 7 (Python Modules Cl Close the command prompt or Terminal and relaunch the IDLE Shell when you now enter: ‘import pygamie, the module will be imported into the code without any problems. Youll ind that most code downloaded or copied from the Internet will contain a module, mainstream of nique, these are usually the source of errorsin execution due to them being missing, ‘The madules contain the extra code needed to achieve a certain esult within your own code, as Siar we've previously experimented with. For example: ‘import random Brings in the code from the Random Number Generator module. You can then use this module to create something like: for i in range(10). printCrandom.randint(l, 25)) a PPM This code, when saved and executed, will display ten random numbers from 1 to 25. You can play around with the code to display more or less, nd from a great or lesser range. For example: ‘import random for i in rangeces): printCrandom.randint(1, 100)) ‘Multiple modules can be imported within your code. Burg) To extend our example, use: import. random import math for I in range(s): printCrandom.randint(1, 25)) print (math. pi) Bre inate ‘The result isa string of random numbers followed by the value of Pas pulled from the Math module Siar using the print(math.pi) Function. You can also pullin certain Functions from a module by using the From and import commands, such as: from random import: randint for i in range(s): print(randint(L, 25)) Lo — > ERTSET DD This helos create a more streamlined approach to programming. You an also use import module ‘which wilimport everything defined within the named module. However, it's often regarded as a waste of resources but it works nonetheless. Finally, modules can be imported as aliases: import math asm print(m.pid ‘Of course, adding comments helps to tell others what's going on. tatty Citevittoarehenttinbe D5 - a x ——— “It's OK to figure out murder mysteries, but you shouldn’t need to Figure out code. You should be able to read it.” ~ Steve McConnell (Software Engineer and Author) (- 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 and multi-dimensional lists. then how you can use them to forge exciting and useful programs. It's little wonder that data is now valued more than gold or oil. You will also learn how you can use the date and time Functions, write to Files in your system and even create graphical user interfaces that will take your coding skills to new levels and into new projectideas. Lists Tuples 54 56 58 _ Dictionaries 60 Splitting and Joining Strings, 62 Formatting Strings 64 Date and Time 66 Opening Files Writing to Files 70 Exceptions Python Graphics wetinosicioncn CE eer eens toe e Rete ah Concerti} 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 variables. You can even include Functions in lists, and lists within lists. FETED A listise 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”] eee veg gen re ori ESTEE (ce you've defined your list you can call each by referencing ts name, followed by anumber. Lists start the frst item entry as 0, Followed by 1,2, 3 and so on. For example: unbers To call up the entire contents ofthe lst. unbers[3] To call the third From zero item in the list (21 in this case), GET 220. recite sees vole You can also access, or index, the lastitem in alist by using the minus sign before the item number [-], ‘or the second to last item with [2] and Soon. Trying to reference an iter that isa in the ist, such as [10] wil return an exrox: unbers[=1] mmythical_creatures[~4] Slicing is similar to indexing but you can retrieve ‘multiple temsin alist by separating tem numbers with a colon. For example: unbers[1:3] vill 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[1:3] to return 4,7 and 21). ES eERD You can update items within an existing list, remove. items and even join lists together. For example, to Join two lists you can use: everything = nunbers + mythical_creatures. ‘Then view the combined list with: everything Youcanview hat can be done wth ists by entering sure dir(list) into the Shell. The output is the available Tuntons for example, ser nd po are se toad and remove items at certain postions. To insert the number 62 at item index 4 punbers-insert(4, 62) Toremove ‘nunbers .pop(4) ae ESTED ers can be added toa lst by entering nunbers=nunbers+[201] Or for strings: mythical_creatres=mythical_creatures+[“Griffin”] (Or by using the append Function: mythical_creatures.append(“Nessie”) ‘nunbers .append(278) a Removal a tems can be dane in two ways. The first Sure is by the item number: del nunbers{7] Alternatively, by item name: mythical_creatures. renoveC“Nessie”) ESTED You 50 use the lst Function to breaka string down intoits components For example: Listc*Davia”y Breaks the name David into, a, V toanewiist: ane=1ist*David Hayward”) rane oge=[44] User = none + age user ‘dThiscan then be passed BITE 22sec on that, ou can create a program to store someone'snameand age as alist: ame=inputC“hat"s your nae? “) ‘name=ListCname) ‘age=intCinput “How old are you: “*)) Lage=Lage] user = Inane + lage ‘The combined name and age lists called user, which can be called byentering user into the Shel. Experiment and see what you can do, a Tuples are very much identical to lists. However, where lists can be updated, deleted or changed in some way, a tuple remains a constant. This is called immutable and they're perfect for storing fixed data items. THE IMMUTABLE TUPLE Reasons for having tuples vary deper 19 on what the program is intended to do. Normally, a tuple is reserved for something special but they're also used for example, in an adventure game, where non-playing character names are stored. PEPER tvvicis created thesamewayasalistbutin this EFM voucencreate grouped tuples into lists that contain instance you use curved brackets instead of square ‘multiple sets of data. For instance, here's tuple brackets. For example: ‘called NPC (Non-Playable Characters) containing the character name tronths=C*January"po"February"si*Marehmsesapet ngs 2nd thelrcombat rating or an adventure game “May”, “June”) NPC=[C"Conan”, 100), (“Belit”, 80), (“Valeria”, months 95)] Pee, ESTED st aswith ists, the tems within named tuple can [ESM Each of these data items can be accessed asa be indexed according to their position inthe data \whole by entering NPCinto the Shell or they canbe range, ie. indexed according to their position NPC[0 You can also index the ee individual tuples within the NPC lst: months['5] Necte} 1) However, any attempt at deleting or adding tothe tuple wil result will display 100. inan errorin the Shel. SE SE ey ET 220i sees vole Iesworth noting that when referencing mle Susp tuples within a list, the indexing is slightly different from the norm. You would expect the 95 combat rating of the character Valeria to be NPCId][S] but t's not. k's actually: Npc(2]E1) ue eet oat tee gare uso we PPT) Thismeans of course that the indexing Follows thus: @ uu ae 2 at 20 1 2a we \which as you canimagine, getsa tle confusing when you've got a (otof tuple data to deal wit. PEPER Tuples though utilise a feature called unpacking, where the data items stored within atuple are assigned variables First create the tuple with two items (name and combat rating) NPC=C*Conan”, 100) i 9 ton ee Hn Now unpack the tuple into two Burg) corresponding variables: Chane, conbat_rating)=NPC ‘You can now check the values by entering name and combat. rating, ESTEE Remember, as with lists, you can also 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 NPcrz]£-0) ‘oucanuse the max and min functions to find the Sued highest and lowest values of a tuple composed of numbers. For example: nunbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) ‘The numbers can be integers and floats. To output the highest and lowest, use print CmaxCnunbers)) print (minCnunbers)) ——— Dictionaries ert eee eet eu Ee NAC aaueartete eA of dealing with data items, They can be tricky to get to grips with at first but you'll soon ITED eo ncn oll meee oa KEY PAIRS. re jonary is ike a list but instead each data item comes asa pai 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. Let’ say 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 a colon Key:Value. For example: phonebook={“Enna”: 1234, “Daniel”: 3456, “Hannah”: 6789} ESSER estas with most sts, tuples and so on, strings need be enclosed in quotes (single or double), ‘whilst integers can be left open. Remember thatthe value can be either a string or an integer, you just need to enclose the relevant fone in quotes: phonebook2={"David”: “0987 654 321”} FED cows eFintive aude series-Volume 24 BITERE DD swith lists and tuples, you can check the contents, of a dictionary by giving the dictionary a name: phonebook, in this example, Ths will display the data tems you've entered ina similar Fashion to alist, which you're no doubt Familiar with by now. EATER 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 [“Enma) phonebook “Hannah"™) “ie Et Se ig tere Yoo He ‘Adding toa dictionary is easy too. You can include SMD ys dtsiter entry by ading the new key and value items ike: phonebook{“David"] = “0987 654 321” phonebook Next youneed to define the user inputs and Burg) variables: one for the person's name, the other Torthel phone number let’ keep simple to avid egy Python code): ame=inputC“Enter name: “) hunber=intCinputC“Enter phone nunber: *)) BETTER You can also remove items from a dictionary by Issuing the del command followed by the tems key; the value will be removed as wel, since both work as a pai of data items: del phonebook[“David"] [eee ee magne key and value items? Create a new Editar instance and start by coding in a new, blank dictionary: phonebook={} ERTIES Note we've kept the number as an integer instead (of astring, 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 as in Step 5, you can enter: phonebook{nane] = nunber fesse = mer Now when you save and execute the code, Python will ask fora name and a number. fewill then insert those entries into the phonebook dictionary, which you can test by entering nto the Shel phonebook phonebook[“David"] IF the number needs to contain spaces you need to makeita string, so remove the int part of the input. wurmbampubicatonscom Gy Splitting and Joining Strings Weak cour Tnl eines sec ute ete Tc] come across long sets of strings. A useful skill to learn in Python programming is being 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) the main tootin the string Function arsenal s spt. With ityou'e able to split aparta string of data, based onthe argument within the brackets. For example, here's2 string with three items, each separated by a space: ‘text="Daniel Hannah Emma” eee Now let's turn the string into a list and splitthe Sue content accordingly: nanesstext-split(* ) Then enter the name of the new list; names, to see the three items IT) 220. cite sees vole 4 able to split those long strings For better readability. BRTERE DD Note that the text split parthas the brackets, uotes, then a space followed by closing quotes ‘and brackets. The space isthe separator, indicating that each lst iter entry is separated by a space. Likewise, CSV (Comma Separated Value) content has a comma, so you'd use: ‘text="January, February,March, April May, June” monthsstext.split(",”) You've previously seen how you can splita string into individual letters asa list, using aname: namesList(“David”) name ‘Vi,’ Whilst may seem alittle useless under ordinary ccumstances, t could be handy for creating _3speling game for example. (-soliting and Joining Strings Cl PEPER) The opposite ofthe split Functionis join, where -you will have separate items n a string and can join themall together to Form a word or ust 8 combination of tems, depending on the program you're writing. For instance alphabet="”. join([“a”,"b”,"<”,"d","e"]) alphabet ‘This ill display ‘abcde’ in the Shell. ESTEE You can theretore apply join to the separated name ‘you made in Step 4, combining the letters again to Form the name: ‘nane="". joinCname) name ‘we've joined the string back together, and retained the list called ‘name, passing it through the Join Function, PEPIEM) cod example of using the join function is when ‘you have alist of words you want to combine into a sentence: List=[“Conan”, “raised” “and”, “struck”, “the”, texte” “.join(list) text, “his”, “mighty”, “sword”, ‘demon™] [Note the space between the quotes before the join Function (where there were no quotes in Step 6's join) Aswith the spt function, the separator does, Burg) have to bea space, it can also be acomma, a full ‘stop, a hyphen or whatever you like: colours=[“Red”, “Green”, “Blue”] +” JoinCcolours) ERTESERD there's some interesting Functions you apply toa string, suchas. capitalize and title. For example: ‘title="conan the cimmerian” title.copitalize() title.titleQ ‘oucan abo ute osc operators onstrngs, Sued ‘with the ‘in’ and ‘not in’ functions. These enable ‘you to check if a string contains (or does not contain) a sequence (of characters: message="Have a nice day” “nice” in message "bad" not in message “day” not in message “night” in message He EO Soh GE eH ae When you work with data, creating lists, dictionaries and objects you may often want to print out the results. Merging strings with data is easy especially with Python 3, as Cann oa Tana ce Koel ces STRING FORMATTING Since Python 3, string Formatting has become a much neater process, using the format Function combined It’s a more logical and better formed approach than previous versions. ‘curly brackets. PEPE The basic formatting in Python sto calleach variable into the string using the curly brackets ‘nane="Conan” printC*The barbarian hero of the Hyborian Age is: 10”. formatCnane)) ES TeeE RD Remember to close the print Function with two sets of brackets, as you've encased the variable in one, and the print Function in another. You can include multiple cases oF string formatting ina single print Function: ‘name=""Conan” place="Cinmeria” printC*{} hailed from the North, in a cold land known as {}".format(name, place)) ERTTSERD You can of course also include integers into the mix nunber=10000 printC*{} of {} was a skilled mercenary, ‘nd thief too. He once stole {} gold from a merchant.”.format(nane, place, nunber)) Oia ‘There are many different ways to apply string formatting, some are quite simple, as we've shown you here; others can be significantly more complex. Itall depends, ‘on what you want from your program. A good place to reference Frequently regarding string Formatting isthe Python Docs webpage, Found at wwrw.docs-python.org/3.1/ibrary/string. html Here, you vill Find tons of help IT 200. cite sees vole rc (. Formatting S| Cl (_ Formatting Strings Interestinaly you can reference alist using the tring HEED You can also print outthe content ofa user's input Susp Formatting Function. You need to place an asterisk in Burg) in the same Fashion: front ofthe lst name: hame=inputC*What’s your none? *) nunbers=1, 3, 45, 567546, 3425346345 print(“Hello {}.”.format (name) print(*Some numbers: {}, {}, fh, {, (". format (*nunbers)) ESTED Withindexingin ists, the same appliestocalinga Ea You can extend this simple code example to display list using string formatting. You can index each item the first letter in a person's entered name: ‘cording to its position (from 0 to however many are present} nome=inputC*What's your none? “) nunbers=1, 4, 7,9 printC*Hello {}.”.format(name)) print(*More numbers: {3}, {0}, {2b, Iname=List(name) {1}.”. format C*nunbers)) printCThe first Letter of your nae is a {0}". format(*Lname)) sogsyeu prety sec yovcnritnse ERE von es calsponaparaf sane refrenee Sure and integers in a single list to be called in the Sue ily them individually within the same print Function. format function Looking back he coe from Step 7, you can alter Rit characters=[“Conan”, “Belit”, “Valeria”, 19, 27, ‘names=[“Conan”, “Belit”, “Valeria”] 20) ages=[25, 21, 22] print (“{0} is {3} years old. Whereas {1} is {4} an ae eating wo lists Now you can called stand indivi tems printC*{0[0}} is {1(0]} years old. Whereas {0[1]} is {1[1]} years old.”.format(nanes, ages) seine ation Date and Time PRR eneCoien ru med recto acCR TT Eo eu erates Oe inna esc uur For how long. Luckily acquiring the date and time is easy, thanks to the Time module. TIME LORDS The Time module contains Functions that help you retrieve the current system time, reads the date From strings, Formats the time and date and much more. ESTEGRED Fistyounced to import the Time module. ’s one that’s builtin to Python 3 so you shouldn't need to drop into a command prompt and pip instalt, Once it’s imported, you can call the current time and date with a simple command: ‘import time time.asctimeC) BEER Thetime Function s spit into nine tuples, these are divided up into indexed items, a with any other tuple, and shown in the screen shot below. Indexed values © an yar ane 2 oy res 5 second 0 to 6 (0 61 ae hap sents) 6 bay ot week (020601 Hondoy) 7 Daye year 1 t 366 (uta dy) 01,1 means ery determines OST STi sees vole 4 PRPED vou can see the structure of how time's presented byentering: ‘time. local timec) ‘The outputs displayed as such: “time, structtimeCtm. year=2017, tmmon=9, tmmday=7, tmhour=9, ‘tmmin=6, tmsecs13, tmuday-3, tmyday=250, tm isdst=0)’; obviously dependent on your current time as opposed tothe time this book was written. EERE there are numerous functions butt into the Time ‘module. One of the mast common of theses strftime0. With it, you'e able to present a wide range of arguments ‘as it converts the time tuple into a string For example, to display the ‘current day of the week you can use: ‘time. strftimeC“KA") ( (So ( Date and Ti (Date and Time Tisnualyneinsyoucn nevoneteerons EERE vous tte endothe presse te Susp functions into your own code, such as: Burg) code to calculate Pi to however many decimal places — the users wanted, you can time a particular event in Python. Take tine. strFtimeC*Ka”) Seeetnecieceeney the code rom above and alte it slighty by including time. strFtimeC*Xb") start_time=time.timeC) tine. strFtimeC*MH") acer time. strftime C0") Then there's endtime=time.timeC)-stort_time TeprrepyoelpiDonmarsihyiencomfegranesy(o4) == > FETED Note thelasttwo entries, with %H and HM, a5 EIB the output will look similar to the screenshot below. {you can see these are the hours and minutes and as ‘The timer Function needs tobe either side of the the last entry indicates, entering them as %H¥6M doesnt display the inputstatement, as that’s when the variable name is being created, Lume correctly in the Shell. You can easily rectify this with: ‘depending on how long the user took to login. The length of time is a then displayed on the last tine ofthe code asthe endtiime variable. ESTeEE AD Thismeans you're going to be able to display BEET Theresa lot that can be done with the Time either the current time or the time when module; some of tis quite complex too, such as. something occurred, suchas a user entering theirname. Trythis displaying the numberof seconds since January 1st 1970. \Fyou code in the Editor: ‘want to dill down further into the Time module, then in the Shel, o_o center: hel pCtime) to cisplay the current Python version help Fle nanesinputC“Enter Login name: “) ‘orthe Time medic printC*Hlelcone”, name, “\d”) print(*User:”, name, “logged in at”, time. strftimeC*RH:3M")) Try to extendit Further to include day, month, yea and so on seine ation In Python you can read text and binary files in your programs. You can also write to file, eeu R en lel esta ect lac ene Mat nrel llc nel ckvelc) Eien rere red ounce ees OPEN, READ AND WRITE In Python you create a file object, similar to creating a variable, only pass ‘categorised as text or binary. ESTEGRED Se2ttbyentering some text into your system’stext EITM IF you now enter poem tothe Shell, you wll get editor. The text editors best, not a word processor, some information regarding the text file you've just ‘8s word processors include background formatting and other ‘asked to be opened. You can now use the poem variable to read the elements, In our example, we have the poem The Cimmerian, by __ contents of the file Robert E Howard. You need to save the file as poem.txt, poem. readC) Note than a /n entry inthe text represents a new tine, a you used previously. ESTER You ese the opend functionto passtherileintoa EISEN iryou enter poem ead a second time you will variable as an object. You can name the file object ‘notice thatthe text has been removed from the fle. anything you like, but you will need to tell Python the name and —-—_-Youwill eed to enter: poem=openC“/home/pi/Docunents/ location of the text file you're opening: Poem. txt”) again to recreate the ile. This time, however, enter: oemsopen("/home/pi/Docunents/Poem.txt”) printCpoem.read()) This time, the n entries are removed in Favour of new lines and readable text. Resi pe Sly Seas ge “ema” for ere atarnain GT 220 cate sees vole ica aiesesal nessa poem. read(S) poem.read(5) \will display the next five. Entering (1) wil display one character at atime. Extending this Further, you can use readtines() to BALD gran ines oF the tex ond store them os multiple lists. These can then be stored as a variable: poen=open("/home/pi/Documents/Poem. txt”) ‘Tines=poem.readlines() Lines[0] Vines {2] Vines (2] FETED Sirilary youcan display one tine of text at atime by Using the readiine() Function. For example: oem=open“/home/pi/Docunents/Poem.txt") poem. readlineC) ‘wil display the first tine ofthe text with: poen.readlineC) Displaying the next line of text once more. BATESERD You can also use the or statement to read the lines of text backto us: for Lines in Lines: printClines) ‘Since this 's Python, there are other ways to produce the same output: poemsopen("'/home/pi/Documents/Poem. txt”) for Lines in poem: print(Lines) oes orto You may have guested that you can pas the Sure readline() Function into a variable, thus allowing you tocalleagain when needed poem=open(“/home/pi/Documents/Poem. txt”) Line=poem. readLine() Line Let's imagine that you want to print the text one character ata time, like an old dat matrix printer ‘would, You can use the Time module mixed with what you've looked athere. Try this: import time oen=open("/hone/pi/Documents/Poem. txt”) ‘Tines=poen.read() for Lines in lines: printClines, end="") time. sleepC.15) ‘The outputis un to view, and easly incorporated into your own code. a The ability to read external files within Python is certainly handy but writing to a file is eee Mec AUN aC mitr eos teet feild) afile, that you can then read() back into Python. WRITE AND CLOSE The write() Function is slightly more complex than read(). Along with the filename you must als determines whether the file in question isin read or write mode. BPR ry opering OE and enter the lowing However te austell Dank Goucan teopent*/ -/pi /Documents/text. ‘check by opening it up). This is because you've | cxenw Prone : wen hein oent tee bject bt rt conmied tothe : Tens Pao he wre funcion atone acne change the destination rom onefp/Documentstoyour own ehnges tote you can dts yen system. This code will create a text file called text.txt.in write mode Using the variable VI there's no file ofthat name inthe location, it will create one. Fone already exits, it will overwrite it, so be careful ticloseQ) BETES RD You can now wrtetothetext fle using the write) — EISEN iryou now open the text file witha text editor, Function. This works opposite to read, writing lines you can see that the line you created has been Instead of reading them. Try this: ‘written tothe file. This ives us the foundation for some interesting possiblities: perhaps the creation of your own logfile or even the beginning of an adventure game. ‘t.write(“You awake in a small, square room. A single table stands to one side, there is a locked door in front of you.") "Note the 109. [t's the number of characters you've entered. ryten342Sret| IT) 220s vole 4 ‘To expand this code, you can reopen the file using EED Youcan pass variables toa file that you've created Susp ‘a’, For access or append mode. This will add any text Burg) in Python. Perhaps you want the value of Pito be atthe end ofthe original ine instead of wiping the Fle and creating written to fie. You can call P from the Math module, create anew ‘anew one, For example: File and pass the output of Pinto the new file: ‘teopen(/home/pi/Documents/text .txt”,"a") import math tenritteC*\n") printC*Value of Pi is: “,math.pi) ‘tuwrite(* You stand and survey your surroundings. print(“\nliriting to a file now..”) On top of the table is some meat, and a cup of water.\n”) FETTER You can keep extending the text ine by line, a Now lets create a variable called pi and assign tthe tending each with a new line (\n), When you're value of Pi done, finish the code with tclose() and open the file inatext . : editor to see the results: cn tawritec“The'door is made/of soLid/oakewithiiron) Yous: need to create anew filein which to write Pit: strips. It’s bolted from the outside, Locking you t=open(““/home/pi/Documents/pi-txt”,"w") in. You are a prisoner!.\n") ticloseO Remember to change your file location to your awn particular system setup, PEPER There are various types of ile access to concider BEER 1 finish, you can use string formatting to call the Using the open() function. Each depends on how the variable and write itto the fil, then commit the file is accessed and even the position ofthe cursor. For example,r+ changes and close the file: apensafleinreadand wie andplacesthecusoratthestartof wt eecnveluRrOfi PSTN} Format) fie ticloseQ, ‘You can see from the results that you're able to pass any variable to afile seine ation Manet Mot Greece at re Sea Reo cree Let’s assume you ask a user to divide two numbers and they try to divide by zero. This Milter cr urcurnlraretineat os EXCEPTIONAL OBJECTS Rather than stop the Flow of your cot , Python includes exception objects which handle unexpected errors in the code. You ‘ean combat errors by creating conditions where exceptions may occur. ‘You can create an exception error by simply trying Yu can use the Function ase exception to create todivide a number by zero. This will report back ‘our own error handling code within Python. Let's with the ZeroDivision€rror: Division by zero message, as seen in the assume your code has you warping around the cosmos, too much screenshot. The ZeroDivsionError partis the exception clas, of _however results ina warp core breach, To stop the game from which there are many. ‘exiting due tothe warp core going supernova, ou can create a = ‘esto exception: raise Exception(*warp core breach”) Most exceptions Totrap any errors in the code you can encase the are raised potential errar within a try: block, Ths block consists ‘automatically when Python ‘of try, except, else, where the code is held within try, then if there's ‘comes across something that's ‘an exception do something, else do something else, inherently wrong with the code. However, you can create your ‘own exceptions that are designed to.contain the potential error and react tot, as opposed to letting the code fail. 00 tn ie Ses ole 4 ( ( Cl (_ Exceptions For example, use the divide by zea ert. Youcan Susp create an exception where the code can handle the error without Python uiting due tothe problem: try: a=intCinputC“Enter the first number: beintCinputC*Enter the second nunber print(a/b) except ZereDivisionError: rint¢*You have tried to divide by zero!”) else: print(*You didn’t divide by zero, Well done!”) » » You can use exceptions to handle a variety of useful tasks. Using an example from our previous tutorials, let's assume you want to openafile and write to it Bisa try: ‘txt = opent“/home/pi/Documents/textfile.txt”, ““r”) txt.nriteC“This is a test. Normal service will shortly resume!) except I0Erro print (“Error: unable to write the file. Check permissions”) else: print (“Content written to file successfully. Have nice day.") ‘txt-closeQ) Obviously this won't work due tothe file textile. tt being opened as read only (the “” part). Soin this, case rather than Python telling you that you're doing something wrong, you've created an exception using the |OErrar class informing the user that the permissions are incorrect ‘Naturally, you can quickly fix the issue by changing Burg) the “r* read only instance with a “w” For write. This, asyoualeady now, wl cese the fle andunte the content then Committe changes to thee, The end est wl report ferent setof ccumstances, nts cite, asvcesfulexecton othe code You can also use a finaly: block, which works ina similar Fashion but you cant use else with it. To use Siar ‘our example rom Step 6: tr ‘txt = open(“/home/pi/Documents/textfile.txt”, “n”) try: txtawriteC“This is @ test. Normal service will shortly resume!) finally: print (“Content written to file successfully. Have @ nice day.”) ‘txt.closeQ, except I0Error: print “Error: unable to write the file. Check permissions”) ‘As before an error willaccur as you've used the "read-only permission. Fyou change itto aw", then the cade will execute without the error being displayed in the IDLE Shell, Needless to say, it can be a tricky getting the exception code right the First time, Practise though, and you will get the hang oft. MCR ete Rant ere eae ue Nera ey acl cnet elmer Mien N Nar dtdee siete taht tee ie oon) Pee Meee nen Lae tisnrla cattle GOING GRAPHICAL You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available, to bring out some spectacular effects. FETED (2 ofthe best graphical modules to begin learning Python graphics is Turtle, The Turtle modules, as the name suggests, based on the turtle robots used in many schools, that can be programmed to draw something ona large piece (of paper on the Floor. The Turtle madule can be imported with: ‘import turtle. FERED {he command turtle crcle(S0) is what draws the circle on the screen, with 50 being the size, You ‘an play around with the sizes you like, going up to 100, 150 and beyond: you can draw an ac by entering: tuntLevcincleCSOs 180), where the sizeis 50, but you'e telling Python to only draw 180" ofthe cle. Let’s begin by drawing a simple circle. Start a New Girard File, then enter the following cade: ‘import turtle turtle. circle(sa) turtle. getscreen()._root.mainloop() ‘As usual pressF5 to save the code and execute it A new window will, ‘now open up and the Turtle’ will draw a circle {80M Definitive Guide Series- Volume 24 ‘The last part of the circle code tells Python to keep Oia the window where the drawing is taking place to remain open, sothe user can cckto closet. Now let's make a square: import turtle print(*Drawing @ square.) for t in rangeca): ‘turtle. forward(100) turtle. leFt(90) turtle. getscreen()._root.mainloop() ‘You can see that we've inserted a loop to draw the sides of the square, (_ Python Graphics ‘SC PEPTID You can add anew line ta the square code to add some colour: turtle.colorc*Red”) ‘Then you can even change the character to an actual turtle by entering: turtle.shopeC“turtle”) You can also use the command tuntlesbegin-AlLO, and turtLe.end_flLO tofillin the square withthe chosen colours; ed outline, yellow fil inthis case, from turtle import * color(‘red’, ‘yellow’) begin ALLC) while True: forward(200) Left (170) if abs(pos()) < 1: break end ALO done W’sa different method, butvery effective @ FETE EAD 22other way in which you can display graphicsis by using the Pygame module. There are numerous ‘ways in which pygame can help you output graphics to the screen but for nowlet’s loka displaying a predefined image. Start by ‘opening a browser and finding an image, then save itt the Folder Where you save your Python code. Nowlet' get the code by importing the Pygarne madul ‘import pygane pygane. init) {ng = pygane. nage. loadc*RPi..prg”) white = (255, 255, 255) w= 900 h= 450 screen = pygane. display. set _mode((n, h)) screen.fill((white)) screen. fll (white) screen. blitCing, (0,0)) ygane.display.fiipO Sis while True: for event in pygane.event.get(): if event.type = pyoane.QUIT: Pygane.quit() ESTEE 2 the previous step you imported pygame, initiated the pygame engine and asked to import our saved Raspberry P logo image, saved as RPi.png. Next you defined the background colour of the window to display the image and the ‘window size as per the actual image dimensions. Finally youhavea loop to clase the window. w = 900 h = 450 screen = pygame .display.set_mode((w, h)) screen. fill((white)) screen. fill((white)) screen. blit(img,(0,0)) pygame. display. #lip() while True: for event in pygame.event.get(): if event. type == pygame. QUIT: pygame.quit() PRPISPTBD Press F5 to save and execute the code and your image willbe displayedin a new window. Have a play around with the colours, sizes and so on and take time to look tp the many functions within the Pygame module too. RaspberryPi Index ) “First, solve the problem. Then, write the code.” — John Johnson (Developer and author) FA) cows detnkive Guide Series: Volume 34 Using Modules Python module is simply a Python- created source file which contains the necessary and unique code for custom classes, Functions and global variables. You can bind and reference modules to extend Functionality and create even more spectacular Python programs. Want to see how to better use these modules to adda little something extra to your code? Then read on and learn how they can be used to fashion fantastic code. There’s even some basic animations in this section, to help you get more from the Python modules. 76 Calendar Module 78 OSModule 80 Random Module 82 Tkinter Module 84 — Pygame Module 88 Basic Animal n 90 Create Your Own Modules wonabdmpubicatonscom — @) Using Modules ) Calendar Module WORKING Muu DATES into Python 3. However, if For some reason it's not installed, you can add it using pip install calendar as a Windows administrator, or sudo pip install calendar for Linux and macos. TEP 1 ee itis loaded into memory, start by entering: ‘sep=calendar. TextCalendar(calendar.. SUNDAY) ssep.prmonth(2019, 9) *Pyihen 353 Shel fle Eat shel Debug Options wow Help Python 3.5.3 3728538) 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 tine to any year and ‘month you want, a birthday for example (1973, 6).The first-line configures TextCalendar to start its weeks an a Sunday, you can opt for Monday if you prefer. (ie tat Sh tn oton nbn FE) 201 re cites leap years between two specific years: Leaps=calendar. leapdays(1900, 2019) printCleaps) The resultis29, starting from 1904 onward. You could even fashion that particular example into apiece of working, user interactive Python code import calendar print(*>>>>>>>>>>Leap Year Calculator< Using Modules ) OS Module INTO THE SYSTEM (One of the primary Features of the OS module i the ability to list, move, create, delete and otherwise interact with files stored on the system, making it the perfect module For backup code. You can start the OS madule with some simple functions to see howit interacts withthe operating system environment that Python is running on, IF you're using Linux Cr the Raspberry Pi, try this: ‘import os home=os.getcwd() print (home) The returned result from printing the variable home isthe current user's home folder on the system. in our example that’s home/pi; twill be different depending on the user name you lag in as and the operating system you use. For example, Windows 10 will output: C:\Program Files x86)\, Python36-32. FSEED The windows outputs different as that’s the current working directory of Python, as determined by the system: as you might suspect, the os getcwal Function is ‘asking Python to retrieve the Current Working Directory, Linux users will see something along the same lines asthe Raspberry Fi, as ill, macs users, Yet another interesting element tothe OS module, 'sits abilty to launch programs that are installed in the host system. For instance, i you wanted to launch the Chromium browser from within a Python program you can use the command import os bronser=os. system(*/usr/bin/chromiun-browser”) BERD) The 0s.ystem) function is what allows interaction with external programs; you can even call up previous Python programs using this method. You will obviously ‘need to know the Ful path and program fle name For itto work successfully, However, you can use the Following: ‘import os os.system(‘start chrome “https://nww. youtube. com/ feed/music”") FETTER For Step 5's example we used Windows, to show that the OS module works roughly the same across. all platforms. n that case, we opened YouTube's music Feed page, so itis therefore possible to open specific pages: ‘import os os. system(‘chromiun-browser “http:// bbdmpubl ications.con/””) the entire command and launching Chromium, whereas the double {quotes open the specified page. You can even use variables to call ‘multiple tabs inthe same browser: Note in the previous step’s example the use of single and double-quotes. The single quotes encase inport 0s a=(‘chromium-browser “http: //bdmpublications. cony”") beC'chromium-bronser “htt os.system(a + b) ‘Jum. google co.uk”? The abi o orp decors or folders alli you prefer, is one of the OS module's best features. For example, to create anew directory you can use import os (0s .mkdirC*NEW") ‘This creates a new directory within the Current Working Directory, named according to the objectin the mkair Function, You can also rename any directories you've created byentering: import os os.renameC*NEW", “OLD”) Todelete ther: import os os.rmdir(“OLD") Te import os, shutil, time root_src_dir = r’/hone/pi/Documents? root dst_dir = ‘/home/pi/backup/” + time.asctimeC) for srcdir, dirs, files in os.walk(root_src_dir): dst_dir = src_dir.replace(root_sre_dir, root. dst_dir, D if not os.path.exists(dst_dir): os.makedirs(dst_dir) for file_ in files: sre_file = os.path.join(sre_dir, file_) dst_file = 0s.path. join(dst_dir, file_) if os.path.exists(dst_file): 0s. renoveCdst_file) shutil.copy(srefile, dst_dir) print(ssssssss>>Backup completeccecccceee”) (_ 0S Module Cl @) Using Modules ) Random Module RANDOM NUMBERS There are numerous Functions: Python programs. in the Random module, which when applied can create some interesting and very useful RE vvonerosiswcrcesomesn BR ows wcmeonrosscantsccy ‘import random random. choice¢{*Conan”, “Valeria”, “Belit”]) GLTEOTMACMETE CRS) This will play one of the names of our adventurers at random, which isa great addition toa text adventure game. Ton as Suave the number four [eit Shab Gobug Sperm down ee was returned. However, enter fae tati etme ee ON the pine funciona ew more times anditwil pay diferent integer valves romthe et of tumbers given zeroto ive. The Gera effect, sthough pseudo tandom, sadequate forthe tverage programmer touts in thetreode beta cle BRIM vou can extend the previous example somewhat by having random.choice( select from a list of mixed eetemtesretet variables. For instance: import random Lst=[“David", 44, “BOM Publications”, 3245.23, “pi”, True, 3.14, “Python”] nd=random. choiceCIst) PEPER Fora bigger set of numbers, including floating aninecend) point values, you can extend the range by using the ‘multiplication sign: import random printCrandom.random() *100) Will display a Floating point number between 0 and 100, tothe tune ‘of around Fifteen decimal points. ED) 201 re cite sees ere Interesting, you can ao ea funtion thin he Suz Random module to shuffle the items in the list, thus ‘adding aittle more randomness into the equation random, shuffleClst) print(lst) ‘This way, you can keep shuffling the list before displaying a random item from it Using shuffle, you can create an entirely random lst ‘of numbers. For example, within a given range: Gis ‘import random Ast=[[i] for I in range(20)] random. shuffle(lst) print(Lst) Keep shuffling the ist and you can havea different selection of items from 0to 20 every time. ‘import random for i in range(10): printCrandom.randrange(@, 200, 7)) You can also select a random number from a given range in steps, using the start, stop, step loop: Results will vary but you get the general idea as to how it works C Random Module Cl Letsuse an example pec of code whch ipsa Bue) virtual coin ten thousand times and counts how many times i wil land on heads o tails: import random ‘output={*Heads”:0, “Tails”:0} coin-listCoutput. keys()) for i in rangec1e000): ‘output[random. choice(coin)]+=1 print(‘Heads:”, output{“Heads”]) print(“Tails:”, output[“Tails”]) Here's an interesting piece of code. Using atext file containing 466 thousand words, you can pluck ‘user generated number of words from the file (text file Found at: ‘www. github.com/dwyl/english-words} import random print(>ss>5ss>5>Random Word Finder>>>s>>59>Your adventure rolecceceece File) and create a True/False while loop: import pygame From pygane. locals import * pygane. init) ‘gamewindon=pygane.di splay. set_mode((800,600)) pygane.display.set_caption(“Adventure Gane”) runniingsTrue while running: for event in pygane.event .get(): if event..type==QUIT: running=False pygame.quitO fle EMR Famat Bin pens Wndons Heb fron prgueer locals inport * {gunenindonepygae displays Prasve.cicplay-setcoption( 1 (800.600)) rare tame’) eunningetrue or event in pygane. event. etc): unningeraise pramerguito) ESTEE the Pyaame window stil won't close don't worry it's just a discrepancy between the IDLE (whichis written with Tkinter) and the Pygame module. IFyou ‘un your code via the command tine it closes perfectly well. BETEER You're going to shift the code around abit now, running the main Pygame code within a while loop; tmakes it neater and easier to fallow. We've downloaded a graphic to-use and we need to set some parameters for pygame: ‘import pygame pygane. initO running=True while running: ‘gamnewindow=pygane. display. set_nodeC(800, 600)) Pygane. display. set_caption(“Adventure Gane”) black=0,0,0) white=(255, 255,255) ESTEE L=600 or pos[t] <0: ya = -ya if pos[2] >=800 or pos[0] <0: gui -updateQ) time.sleep(.025) FETEEED Remove the code you entered in Step 2 andinsert the code From Step 5 ints place; again, between the ball1 = convas.create_oval(5,5,60,60, fill=’red”) and the gui .mainL.oopQ) tines. Save the code and Run it as normal you've entered the code correctly, then you wil se the red ball unce off the edges ofthe window until you close the program. While True loon st wehave the values Ohi andy bear th oon bath of Send 10. The pos=canvas.. coords(bal 11) line, takes the value ofthe bls cation inthe window When teachesthelimits ofthe window 800 or 60, el make the values negative: moving theballaoundthe screen. PEPER Pycame, however, isa much better module at producing higher-end animations, Begin by creating ‘New File and entering ‘import pygame from random import randrange MAX_STARS = 250 ‘STAR_SPEED = 2 def init_stars(screen): “© Create the starfield “” global stars stars = for i in range(MAX_STARS): # A star is represented as a list with this format: X,Y] star = [randrange(®, screen.getwidth©) = 1), andrange@, screen.get_height© - 1)] stars.append(star} def move_and_draw_stars(screen): “Move and draw the stars “™* global stars for star in stars: star[1] += STAR_SPEED if star[1] >= screen.get_height©: star[i] = 0 star[@] = randrange(@,639) screen. set_at(star, (255,255,255)) if __name__ == FETED ow ads the Following: def main(: ygane. init© screen = pygane.display. set _mode((640,480)) pygane.display.set_coptionC*Starfeld Simulation”) clock = pygame.time.Clock() init_stars(screen) while True: # Lock the franerate at 50 FPS clock. tick(S0) # Handle events for event in pygane.event.get(): if event.type == pygame.QUIT: return screen. fl1C(0,0,0)) move_and_draw_stars(screen) pygame.display.flip() “_nain_ main) et masn() yoane:dnse() Prgune. display set mode (640, 80)) iuaptay et. caption("Star! sels’ simulation") apyoane tines clock) anit stars(sereen) ‘hock: eiek(S0) * handle events event. get): ramet screen. £511((0,9,9)) erates) Prasee.sisplay- 300), ‘sin PEPETR Seve and Run the code. You will agree that the simulated starfel looks quite impressive Imagine this as the beginning of some game code, or even the start toa presentation? Using a combination of Pygame and Tkinte, you Python animations wil look fantastic. @) Using Modules ) Create Your Own Modules BUILDING MODULES ‘Modules are Python files, containing code, that you save using a py extension. These are then i ‘now far ported into Python using the FRR ccipocnnyosucrose nates def timestnoCx): return x * 2 def timesthree(x): return x * 3 def square(x): aid return x * x def power(x,y): return x ** y print Ctimestwo(2)) print Ctimesthree(3)) print Csquare(4)) print Cpower(5,3)) Save the program as basic_math.py and execute itto get the results. Under the above code, enter Functions to call the code: ND) 201. ore cite sees olan BETIRED ow youre goingto take the Function definitions ‘out of the program and into a separate file Highlight the Function definitions and choose Edit > Cut. Choose File > New File and use Edit > Paste in the new window. You now have two separate files, one with the Function definitions, the other with the Function calls IF you now try and execute the basic math.py code ‘again, the error’ NameError: name timestwo' is not defined! willbe displayed, This is due to the code no longer having accessto the Function definitions, Returnto Ba thenewly created window containing the Function definitions, and lick File > Save As. Name this minimath.py and save itin the same location asthe original basic_math.py program. Now lose the minimath.py window, so the basic_math.py window fs left open PPT G2ck tothe basic_math.py window: at the top ofthe code enter: from minimath import * ‘Thiswill import the Function definitions as a module, Press F5 to save and execute the program to see itn action, FEPTIED You can now use the code Further to make the program alittle more advanced, utilising the newly created module to its Full Include some user interaction. Start by creating a basic menu the user can choose from: print¢“Select operation.\n”) print¢1.Times by tno”) print¢2.Times by Three”) print¢3. Square”) print¢“4.Poner of”) choice = input¢“\nénter choice (1/2/3/4):”) ‘nun = intCinput(“\nEnter number: “)) Thiswillsave the user-entered number as the variable num Now we can add the user inputto get the number the code will work on: Ble Edt Format Bun Options Windows Help ‘fron minimath inport * print("Select operation.\n") fae by two"! irint("2.Tames by Thr choice = input("\nénter choice (1/2/3/4: » punt = int(input("\nenter number: P ( Create Your Own Modules ( CG Finally, you can now create a range of ifstatements Bue) to determine what to do with the number and utilise the newly created function definitions: if choice == ‘1’: printCtimestwo(numt)) elif choice == ‘2 printCtimesthreeCnunt)) elif choice == ‘3’: print(squareCnuml)) elif choice == <4": ‘und = intCinputC“Enter second number print(poner(numl, nun2)) else: printC*Invalid input”) =D ‘he Est Frat Bn pore sone tp Note that forthe ast valable options, the Power Susi of choice, we've added a second variable, num2. This pases asecond number trough the function definition cle power. Sve and execute the program seein action, Index Ste “The most important papery of a program whether it accomplishes the intention of its user.” = CAR, Hoare “Say Hello to C++ Cl C++ isan excellent, high-level programming language that's used in a multitude of technologies. Everything From your favourite mobile app, console and PC game to entire operating systems are developed with C++ as the core, together with a collection of software development kits and custom libraries. C++ is the driving force behind most of what you use on a daily basis, which makes it a complex and extraordinarily powerful language to get to grips with. In this section, we look at how to install a C++ IDE and compiler on your computer. 94 Why CH? 96 Equipment You Will Need 98 Howto Set Up C++ in Windows 100 How to Set Up C++ on a Mac 102 How to Set Up C++ in Linux Other C++ IDEs to Install . Say Helloto C++ ) eens eC Cc eateries cet MCHC called C with Classes, the language was renamed C++ in 1983. It’s an extension of the original C language and is a general purpose object-oriented (OOP) environment. C EVERYTHING Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs, device drivers and even entire operating systems. GB nett Dating backto 1979, the start ofthe golden ere of home computing, C++, oF rather C with Clases, was the brainchild of Danish computer scientist Bjame Stroustrup while working on his PhO thesis. Stroustrup’s plan was to Further the original C language, which was widely used since the early seventies. C++ proved to be popular among the developers ofthe 80s, since it was a much easier environment to get to grips with and ‘more importantly, it was 99% compatible with the orginal C language. This meant that i could be used beyond the mainstream ET 200 cite sees vole ‘computing labs and by regular people who didn't have access tothe mainframes and large computing data centres. C+4's impact inthe caital world is immense, Many ofthe programs, applications, games and even operating systems are coded using Cr+. For example, all of Adobe's major applications, such as Photoshop, InDesign and so on, are developed in C++. You will find that the browser you surf the internet with is written in C++, as ‘well as Windows 10, Microsoft Office and the backbone to Google's search engine. Apple's macOS i written largely in C++ (with some. Worlds Ici components Language packs aes Seay SS Pe a epatesutyee a es |= SS eed Microsoft's Visual Studio is a great, Free environment to learn C++ in. ‘other languages mixed in depending on the function) andthe likes begin with Python and spend some time getting to grips with ‘of NASA, SpaceX and even CERN use C++ For various applications, _programming structure and the many ways and means in which ‘programs, controls and umpteen other computing task. you Find a solution to a problem through programming, Once you can happily power up your computer and whip ‘outa Python program with one hand ted behind your back, then move on to C++. OF course, there's nothing stopping you from jumping straight into C+ if you Feel up tothe task, go forit. C++ isalso extremely efficent and performs well across the board as well as being an easier addition tothe core C language. This higher level of performance over ‘other languages, such as Python, BASIC {and such, makes it an ideal development environment For modern computing, hence the aforementioned companies Using itso widely Getting to use C++ is as easy as Python, all you need isthe right set of tools in which to-communicate with the computer in C++ and you can start your journey. A C++ IDE sFree of charge, even the immensely powerful Visual Studio from Microsoft 's freely available to download and use. You can get into C++ from any operating system, be it macOS, Linux, Windows or even mobile platforms. While Python sa great programming language to learn, C++ puts the developer ina much wider world of coding. By ‘mastering C++, you can find yourself developing code forthe likes of Microsoft, Apple {and so.0n. Generally, C++ developers enjoy a higher salary than programmers of some other languages and due toits versatility, the C++ programmer can move between Justlke Python, to answer the question of Why C++ isthe jobs and companies without the need to relearn anything specific. answer is because it’s fast, efficient and developed by most ofthe However, Python san easier language to begin with. f you're ‘applications you regularly use l's cutting edge anda fantastic completely new to programming then we would recommend you language to master. mae c @ Windows10 Mac debian ubuntu GS Indeed, the operating system you're seine ation . z= Say Helloto C++ ) Equipment You Will Need NCTE ola oho Cea el E-Ten AOS 1 Cod = E Ce-U holt] don’t need an entire computing lab at your disposal either. Providing you have a fairly modern computer, everything else is Freely available. C++ SETUPS. ‘not all, operating systems have C++ in their code, so it stands to reason that you can learn to program in C++ no matter what OS you're currently using. COMPUTER Unless you Fancy writing out your C++ code by hand on a sheet of paper (whichis something many older coders used to do), 2 computer isan absolute must have component, PC users can have any recent Linux distro or Windows 05, Macusers the latest macOS. AN IDE -_ code. Many IDEs come with extensions and plugins that help make = provides enhancements depending on the core OS being used, such as being enhanced for Windows 10. COMPILER ‘compiler isa program that converts the C++ language into binary, so thatthe computer can understand, While some IDEs come with 3 compiler builtin, others don't. Code: Blockss our Favourite IDE that comes ith a C++ compiler as part ofthe package. More on this late. TEXT EDITOR Some programmers much prefer to use atext editor to assemble thelr C++ code before running it through a compiler Essentially you can Use any text editor to write code, just save it with a.cpp extension. However, Notepad++ is one ofthe best code text editors available. INTERNET ACCESS. While it’s entirely possible to learn how to code on a computer that's rot attached tothe Internet, it’s extraordinarily difficult. Youneed to install relevant software, keep it up to date install any extras or extensions and look for help when coding, ll of these require access to the internet TIME AND PATIENCE Yes, as with Python, you're going to need to set aside significant time tospend on learning how to cade in C++. Sadly, unless you're a genius, isnot going to happen overnight, or even a week. A good C++ coder has spent many years honing their craft, so be patient, stat small and keep learning BET 200 cine sees ole ( Equipment You Will Need cl OS SPECIFIC NEEDS ‘C++ will work in any operating system but getting all the necessary pieces together can be confusing to a newcomer. Here are some OS specifics For C++. Linux users are lucky in that they already have a compiler and We have mentioned previously that a good IDE is Microsoft's text editor built into their operating system. Any text editor Visual Studio. However, a better IDE and compiler is i allows you to type out your C++ code, when i's saved with a CodeBlocks, which is regularly kept up to date with a new extension, use g++ to compile it. release twice a year. Otherwise Windows users can enter their code in Notepad++, then compile it with MinGW as used by Code:B RASPBERRY PI MAC The Raspberry P's operating systems Raspbian, which isLinux based, Therefore, you're able to write your code ‘out using a text editor, then compile twith g++ as you would in any other Linux distro. Mac owners will need to download and install Xcode tobe able tocompile their C++ code natively, Other ‘options For the macoS include Netbeans, Eclipse or Code:Blocks. Note: the latest CodeBlocks isnt available For Mac due toa lack ‘of Mac developers. . @) Say Helloto C++ ) How to Set Up C++ in Windows Tate MR eae R Wl eae lRe ne ec AO aN ol CoP Tee eM Gea 1K are plenty of IDEs and compilers available, including Visual Studio from Microsoft. However, in our opinion, the best C++ IDE to begin with is Code::Blocks. CODE::BLOCKS Code:Blocks is a free C++, C and Fortran IDE that’s Feature rich and easily extendible with plug-ins. It's easy to use, comes with a compiler and has a vibrant community behind it Start by visting the Code:Blocks download site, at ww codeblocks.org/downloads. From there, click (on the ‘Download the binary releases’ nk tobe taken to the latest downloadable version for Windows. Bison PEPER) You can see that there are several Windows versions available. The one you want to download has ‘mingw-setup.exe' atthe end of the current version number. At the time of writing thsi: codeblocks-17.12mingwsetup.exe, The differenceis that the mingw-setup version includes a C++ compiler and debugger from TDM-GCC (a compiler suite). BET 220: cate sees vole ‘when you've located the file, click on the Sourceforge.net link atthe end of the line and a ‘download notification window appears; click on Save File to start the download and save the executable to your PC. Locate the downloaded CodeBlocks installer and double-click ta start. Follow the on-screen instructions to begin the installation @ Welcome to CodeBlocks Setup Seu geo trough eaten Cate Rgreomneded lyase sot sete ‘hucsarg Sunray aoane ‘Seeder teneang wr BEE re you've agreed to the licencing terms, there isa choice of installation options avalable. You can opt fora smaller install, missing out on some of the components but we ‘would recommend you opt for the Full option as default. @ ‘reared: 25408 ( How to Set Up C++ in Windows Cl you click Next, the install begins; when's finished a notification ops up asking you iF you want to start CodeBlocks now, so click Yes. Pes hile Cin uber ea eae rts Cs sta oan Mewar at ar 70s) cae g a Sec ofa? Sec ume ce Cnet = z Ona foe bute Gene pat Cesar ease col rear ee | Before youstart using Code: Blas i's worth Sus ‘explaining exactly why you need the added complet rst, acomplerise separate program tht reads throughyour Cos code and cheds agaist the atest acceptable programing standards why youneed te mest recent Evatable comple Ts caren Cor, wth C20 under ene ———_$§_ 2 oa ae Se aan a —r BETTER The Fisttime Code:locks loadsitruns an auto detect for any C++ compilers you may already have installed on you system. you don’t have any, click on the first detected option, GNU GCC Compiler, and click the Default button to set it as the systems C++ compiler. Clik OK when you're ready to continve. SER STE certs oes aoe BETTER Wen the program starts another message appears, informing you that Code:lacks is currently not the default application For C++ files. You a couple of options: to leave everything ast sor allow Code:Blacks to associate all C++ file types. Again, we would recommend you opt forthe last choice to ‘associate CodeBlocks with every supported file type. BTID Essentially, computers work and understand only binary, ones and zeros, or Machine Language. Programming in binary isn't effective For human beings. For ‘example, to outputthe words "Hello World!” tothe screen in C++ ‘would appear in binary as: e1100011 01101111 @1110101 2111010 e0100000 00111100 0111100 @0100000 00100010 01001000 1100101 01101100 01101100 e1101111 e0100000 1010111 91101111 01110010 e1101100 21100100 00100001 00100010 o0111011 Select TERRE the compiler therefore takes what youve entered as C++ code and translates that to Machine Language. To execute C++ code the IDE builds the code, ‘checking for errors, then pass it through the compiler to check standardisation and convert it to ones and zeros For the computer toact upon. It's rather clever stuff, when you stop to think about it. . @) Say Helloto C++ ) How to Set Up C++ ona Mac To begin C++ coding on a Mac you first need to install Apple’s Xcode. This is a Free, Full featured IDE that’s designed to create native Apple apps. However, you can also use it to create C++ code relatively easily. XCODE Apple's Xcode is primarily designed for users to develop apps For macOS, iOS, tvOS and watchOS applications in Swift or ‘Objective-C but you can use it for C++ too. PETER S21tbyopening the App Store on your Mac, Apple ERMINE when you're ready, click on the Get button which "Menu > App Store. inthe Search box enter Xcode’ then tums into install App. Enter your Apple ID and press Return There are many suggestions filing the App Store and Xcode begins to download and install It may take some time ‘window butts the Fist option, Xcode, that youneed toclickon. depending on the speed of your internet connection PEPE BD) Take amoment to browse through the app's EEPEPD when the installation is 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.126 or later to install and work. changes tothe system. When that is done, Xcode begins to install, ‘additional components FEED cores etre Guide series-votume 24 ( How to Set Up C++ ona Mac Cl Wh everything now instaled, ung the Susp additional components, Xcode launches, displaying the version number along with three choices and any recent projects that you've worked on; with afresh install though, ths is blank Start by clicking on Create New Xcode Project; this ‘opens a template window to choose which platform you're developing code For. Clck the macOS tab, then click the ‘Command Line Tool option. Click Next to continue. Bisa 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 Fields, ‘and made sure that C++ isthe chosen language, click an the Next button to continue, Thenes step seks here tocreate aGitRepostony sure for all your Future code. Choose a location on your Mac, ora networkocaton, andthe Create button, When Youve doneal that you canstartto code. The efthend pane Geta the sured nthe Ce program yore coding, Clckon the maincpp fein thet ESTEE You can see that Xcode has automatically completed a basic Hello World program For you ‘While it may not make much sense at present, you wil dscover more as you progress, the content is ust Xcode utlising what's ‘available on the Mac. ETS oe When you want to run the code, cick on Product > un, You may be asked to enable Developer Mode ‘on the Mac; thisis to authorise Xcode to perform functions without needing your password every session. When the program executes, the output is displayed at the bottom of the Xcode window. z= Say Helloto C++ ) How to Set Up C++ in Linux ae endo Can ne eeu etc ect Conn oN ey el re ane Reel | MN Aconex Cole E LK aa (naked 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. he commands used below work just Fine and for this example we're using Linux Mint. IF you have a Raspberry Pi ESTEE Te fist step isto ensure Linux is ready For your C++ code, so check the system and software are up to 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. le Edt vew Sear Terminal Hb FETED srazinaly thats. Everything is already for you 0 start cading, Here's how to get your Fist C rogram up and running, In Linux Mint the main text editor s Xe, which you can launch by clicking on the Menu and typing Xed into, the search bar. Click on the Text Editor button inthe right-hand pane toopen it. y "Most Linux distros come preinstalled with all the necessary components to start coding in however, its always worth checking to see if everything sent. Still within the Terminal, enter: sudo apt-get install build-essential and press Return. you have the right components nothing is installed; iF you're missing some then are installed by the command, 102 ‘8DMs Definitive Guide Seris- Volume 24 PPP M 10 Xed, or any other text editor you may be usin, enter the lines of code that make up your C++ Hello Nord program. t's alte different to what the Mac produced: include int main) i My frst C++ program std::cout << “Hello World!\n”; ¥ poaln~ xeon ag Howtostvncrninn CR PEPER Wrenyouveenteredyourcode,cickFile>Saveas fore you can execute the C+ fileyou need to and choose a folder in which to save your program. compile. In Linux t's common to use g++, an open file as helloworld.cpp (iecan be any name as ong asit has source C++ compiler; as you're now in the same folder as the C++ tension), Click Save to continue, file, enter: g++ helloworld.cpp in the Terminal and press Return. Fie 66 Vow fwch Tee Te frst thing to notice that Xed has takes ashortime wile the code compiled by SUE automatically recognised this as a C++ file, since the Sa?) g++ but providing there are no mistakes or errors in le extension fs now set to cpp. The colour codingis present in the the code you are returned tothe command prompt. The compiling code and iF you open up the ile manager you can also.see that file's of the code has created a new file. If you enter into the Terminal ni has C++ stamped onit. you can see that alongside your C++ ile is aout. pesis> see 88 ie 66t Wow Seach Temi He BETES With your code now saved, drop into the Terminal ESET The aout fileis the compiled C++ code. Torun again. You need to navigate to the location of the code enter: fa.out and press Return. The the C++ fileyou'veust saved. Qur examples inthe Documents words ‘Hello World appear on the screen. However, a.out isnt folder, so we can navigate to i by entering: ed Documents, very Friendly. Ta name it something else past-compling, yo Remember, the Linux Terminals case sensitive, so any capitals recompile with: g++ helloworld.cpp-o helloworld, This creates an ered correctly. output file called helloworld which can be run with: fhelloworld, must be e Fett View Seach Temi Hep Fe it Yon Sach Tri He Other C++ IDEs to Install IFyou want to try a different approach to working with your C++ code, then there are Meusokesteact icin ota aro Ueit tuts teil ceceuulion cad [>= but there are plenty for Mac and Linux users too. DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but Find the one that works best For you. ren Se Eclnseisahugely popular C++ IDE that offers FRSTEMTTER odelite isa free and open source IDE that's the programmer a wealth of Features, has a regularly updated and available for Windows, ‘reat, clean interface, is easy to use and available For Windows, Linux and macOS. t's lightweight, uncomplicated and extremely Linux and Mac. Head over to wwwelipse.org/downloads/ to powerful. You can find out more information as well as how to download the latest version. If you're stuck, click the Need Help link download and instalit at www.codelite.ora/. for more information, FANT The CNAT Programming Studio (GPS)isapowerful — INPEMSNNER Another popular choice is NetBeans. This ‘and intuitive IDE that supports testing, debugging is another excellent IDE that’s packed with and code analysis. The Community Edition is Free, whereas the Features and a pleasure to use. NetBeans IDE includes project based ro version costs; however, the Community Editionis available for templates for C++ that give you the ability to build applications with \windows, Mac, Linux and even the Raspberry PiYoucanfinditat dynamic and statc libraries. Find aut more at www.netbeans.org/ wwrwadacore.com/downtoad. Features/cpp/index.htm. FEED sorts etn cide seris-votume 34 C X Other C++ IDEs to Install Cl RTE Microsoft's Visual studioisa mammoth C++ IDE that allows you to.create applications for Windows, Android, iOS and the web. The Community version s Free to download and install but the other versions allow 2 ree tral period, Go to www.visualstudio.com/ to see what itcan do For you. ESSER 1h ross platform IDE is designed to create C+ applications For desktop and ‘mobile environments. Itcomes 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 sa trial period an offer before s-apistools- equiring purchasing: www. io/@t-Features-ib and-ide/. PRE he Aniuts Devstudio is a Linux-only DE that Features some of the more advanced Features you ‘would normally Find in paid software development studio, There's _3GUI designer, source ecitor, app wizard, interactive debugger and much more, Go to wwwanjuta.ora/ For more information Ca eRe Ts excellent IDE allows developers towrite C++ code For desktop and ‘web applications across all the major platforms. There's an advanced text editor, integrated debugger and a configurable workbench to help you create your code. I's available for Windows, Mac and Linux andi free to download and use: www.monodevelop com. Bloodshed Dev C++, despite its colourful name, isan older IDE that is for Windows systems only. However, many users praise it clean interface and uncomplicated \way of coding and compiling. Although there's not been much updating for some time, i's certainly one to consider if you want something cifferent: www.bloodshed.net/devcpp html i | Ultimate++ isa cross-platform Cr+ IDE that boasts a rapid development of code through the smart and ‘aggressive use of C++. For the novice, t's a beast of an IDE but behind its complexity isa beauty that would make a developers knees go ‘wobbly. Find out more at www.ultimatepp.org/index.html omnociccoson CT (C+ Fundamentals \ Within this section, you will begin to understand the structure of C++ code and how you can compile and execute that code. These are the core Fundamentals of C++, which 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 will be able to Form your own code, produce an output tothe screen, store and retrieve data and be well on your way to creating your own custom code. 108 Your First C++ Program 110 Structure of a C++ Program 142 Compile and Execute 114 Using Comments 116 Variables 118 Data Types 120. Strings C++ Maths, “| didn't, it eT fei ely Spree a ae Ly) Puen Oe | worm mpublcatonscom

You might also like