You are on page 1of 149
” LEARN PYTHON & C++ CODING oom C++ & Python Manual The essential coding off manual for C++ & Python ry pee programming _ A www.pdpublicationscom 6) Papercut 100% INDEPENDENT Exclusive to Readly Readers! This amazing publication is packed with expert reviews covering everything you need to know about the latest consumer technology. From the very best games, to the latest hardware and software. This fantastic publication is for users of all major hardware platforms, including Microsoft, Apple, Apple Mac, Android, Samsung and more. Don't miss out on this incredible offer and of course to save yourself £9.99! For details on how to claim this awesome and completely FREE gift here on Readly and follow the simple instructions. Enjoy. The Complete C++ & Python Manual Unleash the power of Python and C++ Having a basic knowledge of programming can open many different doors for the newcomer to explore. You can gain a better understanding ‘of how hardware and software work together, how your computer or device functions and how incredible open-world gaming environments are converted from ones and zeros to what's on your monitor or TV. Technology is everywhere and it's all connected through programming. Your TV, microwave, in-car entertainment and the Internet itself are all reliant on good programming to make them work the way you want them, to. Within these pages are the building blocks to help you take your first steps into the world of programming. We've taken two of the most powerful and versatile programming languages available, Python and C++ ‘and broken them down into bite-sized tutorials and guides to help you learn how they work, and how to make them work for you. £3) Papercut www.pclpublications.com Ces ») woe Contents © SNe LORCA aTe) Cia Ceca) Pees oni an Sooke A ean Coie a eau CCM ose aren FS ood aa Fyn geet PE eet gee 28 Executing Code from the Command Line ET eee ses EPCS ESO Ru eae a Ermer ian PT eon ene ey Crocs nS Cea s Esco 52 _ Splitting and Joining Strings Pca) Cer) eee MT 58 Opening Files Cac eo ee es Using Modules 68 Calendar Module EOC LM oot Lace CMe cue Cee hota gece Aaa hc @neg ercd ea ena es How to Set Up C+ in Windows Deora Xen nes Coen sa Sesser Other C++ IDEs to Install Contents ae eee) Tete reetor eu) SMe me ceted Using Comments Nec? Pray Cag errno C++ Input/Output User interaction erceegnor a Peiameteaen File Input/Outp ry ary 130 132 cer 138 140 cd 144 Pere) For Loop emery enon (aeeeseccns Working with Code eae Gees co mp eco Cormeen aed eens cone ea Say Hello to Python (Say Hello to Python CH L There are many different programming languages available to learn and use. Some are complex and incredibly powerful and some are extremely basic and used as minor utilities For operating systems. Python sits somewhere in the middle, combining ease of use with a generous helping of power that allows the user to create minor utilities, a range of excellent games and performance- heavy computational tasks. However, there's more to Python than simply being another programming language. It has vibrant and lively community behind it that shares knowledge, code and project ideas; as well as bug fixes for Future releases. It’s thanks to this community that the language has grown and thrived and now it’syour turn to take the plunge and learn how to program in Python. The first half of this book helps you get started with the latest version of Python and from there guide you on how to.use some of the most common and interesting functions and Features of the language. Before long, you will be able to code your own helpful system tools, text adventures and even control character as they move around the screen. 8 Why Python? 10 Equipment You will Need 12 Getting to Know Python 14 Howto Set Up Python in Windows 16 Howto Set Up Python on a Mac How to Set Up Python in Linux maicicinen CE ER 0 ) Say Hello to Python Why Python? SERUM crea ee cM eM eee Cem amu caren en and some still available for older 8 and 16-bit computers too. Some of these languages ETeeKelocsela-te Rom sal ne AAU oe Ronee CN) Clee Teagan UY eg Tele Python out of all the rest: PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. “These pioneers of programming carved their way into a new Frontier, Forging small routines that enabled the letter A to scroll ‘across the screen. It may not sound terribly exciting toa generation that's used to ultra-high definition graphics and open world, multi- player online gaming. However, forty-something years ago it was, blindingly brillant. Naturally these bedsoom coders helped form the foundations for ‘every piece of digital technology we use today, Some went on to become chief developers for top software companies, whereas ‘thers pushed the available hardware to its limits and founded the billion pound gaming empire that continually amazes us. Regardless of whether you use an Android device, 10S device, PC, ‘Mac, Linux, Smart TV, games console, MP3 playet, GPS device builtin to. car set-top box ora thousand other connected and ‘smart’ appliances, behind them allis programming. Allthose aforementioned caital devices need instructions to tell them what to do, and allow them to be interacted with, These instructions Form the programming core of the device and that core can be 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 will interact with its Fe EH yoo Fo OA] GHD AS SD ow lar V vnc @ > Beet > 0@ gone 05 jon Bore Beovet sans =] =< Atteurgor >= 0} Pel resirowt cursor): certitehttdbostrocus0 Setcursor(p cerlsschitscotFocust eee Sead oe i rescse fe tence Sweat fe oma ss 8 soos fe ste 8 resarcns Gresser aren Smrorcricn [8 Deedee [Ebene JS oene.6 [S oeier op [Souder HB sae je arene Bee oe [Sanco ce SFCTemtte) wisle(a © catcoune()) Fstop © coteaney (2) Steric Sect 4 reco tecele Seigcaue Fact peas a ford Siena. co E daweet cs C++ is usually reserved for more complex programs, operating systems, games and so on. eid Arrayctrl::childLostrecus() column. setceune() = 1)) == 0) , Galor fe = Blend(scatoroasabled, scolorPeper): by Liftreap > stzecey) breek: fsbottom = Frtep + Gettinecy(i)s ‘environment or users, Operating systems, such as Windows, macOS ‘and such are usually a combination of C++, Cit, assembly and some Foim of visualbased language. Games generally use C++ whist web pages an use a plethora of avaiable 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 vitually every conceivable application. Some operate aster than others and some {are easier to learn and use than others. Python is one such general- purpose language. Python is what's known asa High-Level Language, in that t'talks tothe hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless more interactions. Whilst its nat as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefitis that it's universally accessible ‘and easy to learn (/#TTe: invoke java import java. lang-reflect.*; iclass invoke { public static void main( string [] args ) { "Lass ¢ = class.forvane( args(o] 9; hethod'g = e-getsethod( argslll, new class Qiked Be = sm. tnyokec mutt, utd 9; Tee mca, * arts) b egedh c Sebatmeabenlmmesereas ¢ § grt Ds 2 IGS Tee a dace Fas Nenncasner eae 2 > Guat ( Fegeracensbraption 3 9 ¢ ee Seiepanes eerste es Sad chat } Gen C tmvocattonrargetexception e4 ) { Py citeccapeion Seer roarente 1efee Sa foe Pen ysrtethod chren an: " +64, pencoient Y Java's a powerful language that's used in web pages, set-top boxes, TVsand Why Python? CH Python was created over twenty sixyears ago and has evolved to become an ideal beginner's language for learning how to program @ computer. t's perfect for the hobbyist, enthusiast, student, teacher and those who simaly need to create their own unique interaction between either themselves ora piece of external hardware and the computer itself Pythonis free to download, install and use ands available for Linux, Windows, macOS, MS-DOS, 05/2, BeOS, IBM i-series machines, and even RISC OS. Ithas been voted one ofthe top five programming languagesin the world ands continually evolving ahead of the hardware and internet development curve Soto answer the question: why python? Simply put, i's Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational tool BASIC was once the starter language that early ‘bit home computer users learned. pen etre pipe n) Python isa more modern take on BASIC, it’s easyto learn ‘and makes for an ideal beginner's programming language. ————— > ®) Say Hello to Python ) Equipment You Will Need Noe LMR CN Aes MeN Rom nee CU en colt) CefeyaMen t-te TaM ents] Ware AU Reed oll Ima R- Tae Aa 1M Mr eRe Tela Te RT Freely available. ‘WHAT WE'RE USING ‘Thankfully, Python is a multi-platform programming language available For Windows, macOS, Linux, Raspberry Pi and more. IF you have one of those systems, then you can easily start using Python. (| computer Obviously you're going to need a computer in order to learn how to program in Python and totest your code You can use Windows (rom XP onward) on ether 332 ‘or 6ebit processor, an ple Mac or Linux installed PC |_| AN IDE ‘AnIDE (Integrated Developer Environment) is used to enter and execute Python ‘ode. It enables you to inspect your program code and the values within the code, as. ‘well as offering advanced features. There are many different IDEs available, so Find the one that works for you and gives the best results. PYTHON SOFTWARE macOS and Linux already come with Python preinstalled as part ofthe 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 we'll cover shortly. [_] TEXT EDITOR whist ext edo sande envionment to enter code ino. not an absolute neces, You can enter and execute coe det from the OLE buta text eto, Suchessbbine Text or Notepads, offers more advanced Features and colour coding when entering code |_| INTERNET ACCESS. Python isan ever evolving environment and as such new versions often introduce new concepts or change existing commands and code structure to make ita more «efficient language. Having access to the Internet will keep you up-to-date, help you ‘out when you get stuck and give access to Python's immense number of modules. TIME AND PATIENCE Despite what other books may lead you to believe, you won't become a programmer in 24-hours. Learning to code in Python takes time, and patience. Youmay become stuck at times and other times the code willow lke water. Understand youre learning ‘something entirely new, and you will get there. THE RASPBERRY PI (_ Equipment You will Need cH Why use a Raspberry Pi? The Raspberry Pi isa tiny computer that's very cheap to purchase but offers the user a fantastic learning platform. ts main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras. aaa The Raspberry Pi isthe latest version, incorporating a more powerful CPU, more memory, Wi-Fi and Bluetooth support. You can pick up a Pi for around £32 or as@ part oFkt For £50, depending on the kit you're interes The Raspberry P's main aperating system isa Debian-baced Linux distribution that comes with everything you need in 2 simple to use package. I's streamlined for the Pi and isan idea platform for hardware and software projects, Python. programming and even as.a desktop computer. Tl. eN sep ‘The FUZE isa learning environment builton the latest model of the Raspberry Pl. You can purchase the workstations that ‘come with an electronics kit and even a robot arm For you to build and program. You can Find more information on the FUZE atwwrwefuze.co.uk, (We have several great coding titles avalable via wow. pelpublications.com. Qur Pi books caver how to buy your first Raspberry Pi, setitup and seit there are some great step-by-step project examples and guides to get the most from the Raspberry Pi to. swoupdpbletncon ®) Say Hello to Python Getting to Know Python Python is the greatest computer programming language ever created. It enables you to fully harness the power of a computer, in a language that’s clean and easy RoR Uae] Ieee WHAT IS PROGRAMMING? Ithelps to understand what 2 programming language is before you try to learn one, and Python is no different. Let's take 2 look at how Python came about and how it relates to other languages. PROGRAMMING RECIPES ene Carel} Programs ae lke recipes For computers. A Aprogramminglanguage recipe to bake a cake could go tke this: isa list of instructions that ‘a computer follows. These ut 100 grams of selFraising flourin a bowl. instructions can be assimple Add 100 grams of butter to the bowl. 2s displaying your name ‘Add 100 mililtres of milk, ‘7 playing a music file, or Bake for halFan hour, as complexas building a re whole virtual world. Python CODE isa programming language ecovcties Ste ee, eos Just Uke a recipe, a program consists of instructions that you Follow a9 siiiiaitres oF mi: Poe ee inocer a orgram hat desebes 8 cake mghtrnthe the a Informatica (CW) in the i bont = 0 Netarandsorasccesoto if fur = 10 TheARClanguage [butter «50 milk = 100 bow! .append(Cflour buttermilk] ee -ake..cook(bowL) PROGRAM COMMANDS You might not understand some of the Python commands, lke bowl append and cake.cook(bow). ‘The firsts list, the second an object; we'll Look at both inthis book. The main thing to know is that it’s easy to read commands in Python. Once you learn what the commands do, I's easy to figure out how a program works. Guido van Rossum, the Father of Python. HIGH-LEVEL LANGUAGES Computer languas snown as “high-level “This is because they ly high above the hardware (also referred to as the metal’). Languages that “ly close to the meta’ lke Assembly, are known as “low-level”. Low-level languages commands read a bit lkethis:msg db ,@xa Len equ $ - msg PYTHON 3 VS PYTHON 2 ( Getting to Know Python cH ZEN OF PYTHON Python lets you access al the power ofa computer in a language that humans can understand. Behind all thisis an ethos called "The Zen of Python." This isa collection of 20 software principles that influences the design of the language. Principles include “Beautiful Is better than ugly” and “Simple isbetter than complex.” Type ‘import this into Python and it wil display all the principles. Ina typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language: rane ac aes WORLD OF PYTHON Wagemetiena pc) Peneeecseges td een ee aed eRe iy a a ferent te etn DC Rosco ena ar PYTHON 2.X ore nent eee eae Crass Be ey ly, most (iF not all ue Poco need acaels eee eres Se eee features and begin to phase out the previous version. Seema eae! i snippets of important code, er ene taint aetna eet Cree eae ®) Say Hello to Python How to Set Up Python in Windows Nelo NAD Ee) Mend cleo MEMES een} Downloads page. Whilst 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, it’s an easy process to follow. ED Succ orvcivonsowmmansion [RBBB cones cents con soya ERD oi cae esr caer Sear sonnet chert on tat, samuaeadae cremate ene et Features. On the frst screen available, ensure all boxes are ticked and click the Next button, covers teaures a en se eum tn puthi wind oy = co FETED ick the download button for version 3.x, and ESTeRED The next page of options include some interesting save the file to your Downloads folder. When the daltons to Python. Ensure the Associate File with Fite is downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables, installation wizerd wil launch. From here youhave two choices: recompile Standard Library and install fr All Users options are Install Now and Customise Installation. We recommend opting for ticked. These make using Python later much easier. Click Install when the Customise installation link you're ready to continue. = Install Python 3.6.2 (32-bit) | ‘Advanced Options se tat rn ph th lh ge oe eet orate c= == canes (Goepents canyon |ce puth Be pyth wind Gainynensecnn amy | wind cs re et FEED You mayneed to confirm the installation with the Windows authentication notification. simply click ‘Yesand Python will begin to install. Once the installation is comple the final Python wizard page will allow you to view the latest release notes, and Follow some online tutorials. oS python a windows PEEP cefore you close the instal wizard window, however, it's best to cick on the link next to the shield detailed Disable Path Lenath Limit. This will alow Python to bypass the Windows 260 character imitation, enabling you to execute Python programs stored in deep Folders arrangements, Setup was successful ‘Again, click Yes to authenticate the process; then you can Close the installation window Close Windows 10 users will now = Find the installed Python an 3.xwithin the Start button Recently Added section, The Firstlink, Python 3.6 (32-bit) sm will aunch the command line version of Python when clicked (more on thatina moment). To open the IDLE, type DLE into Windows start How to Set Up Python in Windows (CE PPD licking on the 1OLe (Python 3.6 32-bit) tink wil launch the Python Shell, where you can begin your Python programming journey. Don't worry iF your version er, a5 long as it's Python 3.x our cade will work inside your Python 3 interface PEPER) you now click on the windows Start button again and this time type: CMD, you'llbe presented with the ‘Command Prompt link. Click t to get tothe Windows command line environment. To enter Python within the command tne, you need to ype: python and press Enter The commande version of Python works in Sue much the same way as the Shell you opened in Step 8 noe the three lftfacng arrows (o>) hist perfectly fe envionment Ks rot too userfiendly so leave the command line fornon Ente eX to leave and cose the Command Prompt window z= Say Hello to Python) How to Set Up Python on a Mac IF you're running an Apple Mac, then setting up Python is incredibly easy. In Fact a esol Med mae nM EEL UrLeN Alara (creme [ely ALR eLURSaCeLe) MTL cer R OlUM CMEC) aE le tae ola INSTALLING PYTHON, Apple's operating system comes with Python installed, so you don’t need to install it separately, However, Apple doesn't update Python very often and you're probably running an older version. So it makes sense to check and update First PEPE open anew Terminal window by clicking Go> FERED) ickon the latest version of Python 3%, in our Utes, then double-click the Terminal icon, Now (se this isthe download button for Python 3.6.2. enter: python =-version. You should see"Python 2.1" and This will automatically download the latest version of Python and even later, iF Apple has updated the OS and Python installation, depending on how you've got your Mac configured, t automaticaly Either way, it's best to check forthe latest version. starts the installation wizard, FEE Oren Safari and heed over to www.python.ora/ FETED With the Python instalation wizard open, click on downloads. Just 2s with the Windows setup the Continue button to begin the installation. I's procedure on the previous pages, you can see two yellow download worth taking a moment to read through the Important information buttons: one for Python 3.6.2, andthe other for Python 2.7.13, section, in case it references something that applies to your version Note, that version numbers maybe different due tothe Frequent of macOS, When reads, click Continue again, releases of Python. 1 ee DOC Rute ana Tb ‘The next section details the Software License Agreement, and whilst not particularly interesting tomost Folks, it’s probably worth a read, When you're ready, click on the Continue button once again (How to Set Up Python on a Mac ¢ CE ‘There's nothing much ee (eto doin the Python Sure installation wizard so you can click the Close button. Ifyou now drop backinto Terminal session and reenter the command: python3 =-version, you can seethe nev version's now listed. To enter the command line version of Python, youneed toenter: python3, To exit, it's: exit, ESTEE inallyyou're be presented with the amount of space Python wil take up on your system and an Insta button, which you need to click to start the actual installation ‘oF Python 32xon to your Mac. You may need to enter your password toauthenticate the instalation proces. The installation shouldn't take too long; the older STEP7 ‘Mac Mini we used inthis sectionisa lite slower than more modern Mac machines andit only took around thirty seconds forthe Installation Successful prompt to be displayed, PPI You nced to searchin Finder for the Python IDLE; ‘when you've Found it cickit to launch and it should look similar to that of the Windows IDLE version shown on the previous page. The only difference being the Mac detected hardware platform it’s running on. eee Pytnon 9.6.8 (od 6.8 (e221 Cate ines ud Tipe earyeant's “cred ara Dien seria a" far ore infermaton ACU) in ae tay be eatavie (Older Mac versions may have trouble with the ewer versions of Python, in which case you will need to revert toa previous Python 3.x build; as long as you're using Python 33, the code in this book will work or you. ‘Python 3-12 (z312:79260M, Mar 24 2010, 0 [6cc 4.0-1" (apple Inc. build $493)] on’ darwin 33:18) ‘type "copyright", re incormation, SCreaite” or “licens }" fer mo wmode Say Hello to Python_) How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it’s often difficult to nail down just one way of doing something. Different distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 For this particular tutorial PEPE Fics:younced to ascertain which version of Python 's currently installed in your Linuxsystemy, as we mentioned, we'fe going to be using Linux Mint 18.1 for this section. ‘Aswith macOS, drop into a Terminal by pressing CUrt+Atl+T ‘davidedavid-mint File Edt View Search Terminal Help eee ext enter: python ==version into the Terminal screen. You should have the output relating to version 2.x f Python inthe display. Ours in this particular case is Python 2.7.12. davidedavid-mint ~ Fle Edit View Search Terminal Help fytnan & + Coding FETED) some tinux cists will automatically update the instalation of Python to the latest versions whenever the system is updated. To check, first doa system update and upgrade with: sudo apt-get update && sudo apt-get upgrade Enter your password and let the system do any updates. ESTEE Once the update and upgrade is complete, you may need to answer '' to authorise any upgrades, enter: python. =-Verssion to see if Python 3.xis updated or even installed. n the case of Linux Mint, the version we have is Python 3.5.2, which sine For our purposes. PETESIDD However, you want the latest version, 3.6.2 as per the Python website atthe time of writing, you 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 Libgdbn-dev libc6-dev libbz2-dev i ee oe PEPE open upyour Linux web browser and go to the Python download page: www.pythen.org/ ‘downloads. lick on the Download Python 3.6.2 (or whichever version t's on when you look) to download the source Python: 3.62tarxeflle Inthe Terminal, go the Downloads folder by entering: ed Downiloads/. Then unzip the contents of the downloaded Python source code with: tar =xvF Python-3.6.2. tar.xz. Now enter the newly unzipped folder with ed Python-3.6.2/. How to Set Up Python in Linux PED within the python folder, enter: Zeonfigure sudo make altinstall ‘This coulda ite wile depending on the speed of your computer. Once finished, enter python3.6 =-version to check the Installed latest version. FeTSEIE DD or the GUIIDLE, you need to enter the following ‘command into the Terminal: sudo apt-get install idle} The IDLE can then be started with the command: idLe3. Note, that IDLE runs a different version fram the one you installed from source. Gnadedend mint WDomiendutyner a2 FETED DD You atsoneed Pip (Pip installs Packages) which isa tool to help you install more modules and extras. Enter: sudo apt-get install python3-pip PIP is then installed; check For the latest update with: pip3 install --upgrade pip When complete, close the Terminal and Python 3.x willbe available via the Programming section in your dstro's menu, wompepubtiaionscan ( Getting Started with Python CH Getting started with Python may seem a little daunting at first but the language has been designed with simplicity in mind. Like most things, you need to start slowly, learn how to get a result and how to get what you want from the code. Inthis section, we cover variables, numbers and expressions, user input, conditions and loops; and the types of errors you may well come across in your time with Python. Starting Python for the First Time 24 YourFirst Code 26 Saving and Executing Your Code 28 Executing Code from the Command Line Numbers and Expressions Using Comments Working with Variables User Input Creating Functions Conditions and Loops Python Modules BseRERS =) Getting Started with Python e) Starting Python For the First Time War eerie ReoM LAUR UN AOL OMe ee Cece Le lecro meee m chy] Ree a Celene a Ee aod ol Toc laat oF ela ER OLR ERTS Be BS)a1 OE] Rell lm aele RT Bela STARTING PYTHON We're not going to 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 FETE RID With the Raspbian desktop loaded, cick on the SEED (or example, inthe shell enter: 242 ‘Menu button followed by Programming » Python After pressing Enter, the nex¢ line displays the 3 (DLE). Ths opens the Python 3 Shall. Windows and Mac users can answer: 4. Basically, Python has taken the ‘code’ and produced the Find the Python 3IOLE Shell from within the Windows Start button relevant output. menu and via Finder sepa an eae een or “cna” far mre itr BEER Thesheliswhereyou canentercode andseethe — JESTEEIARB the Python shel acts very much ikea calculator, responses and output of code you ve programmed since cade is basically aseries of mathematical into Python. Thisisakind of sandbox, where youre ableto try out interactions wth the system. Integers, which arethe infinite ‘some simple code and processes. sequence of whole numbers can easily be added, subtracted, ‘multiplied and so on, ie Sereaits™ of “Lcens()” fer nore information While that’s very interesting, i's not particularly exciting. Instead, try this: = print(“Hello everyone!”) Just ike the code we entered in Sublime inthe Installing a Text Editor section ofthis book, PEP This isa lctie more ike t, since you've just produced Your first bit of code. The Print command is fairly self-explanatory, it prints things. Python 3 requires the brackets as ‘well as quote marks in order to output content to the screen, in this ‘ease the ‘Hello everyone! bit >>> print(“Hello everyone! *) Hello everyone! >>| ( Starting Python for the First Time CH ise) The Python IDLE isa configurable environment. IF you don’t lke the way the colours ae represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don't recommend that, as you won't be seeing the same as our screenshots. Ear par tee nce = =m stke most programs avalable, regardless of the ‘operating system, there are numerous shortcut keysavallable. We don't have room for them all here but within the (Options > Configure IDLE and under the Keys tab, you can see a list of the current bindings. PEPEED You mayhave noticed the colour coding within the Python IDLE, The colours represent different ‘elements of Python code, They are: Black —Data and Variables Green—Strings Purple— Functions range Commands Blue — User Functions Dark Red Comments Light Red Error Messages IDLE Colour Coding [-eeteur [user] exampies | Purple | netene | ent)_peint 0) The Python IDLE isa power interface and one that’s actually been written in Python using one of the available GU! toolkits. IF you want to know the many ins and ‘outs of the Shel, we recommend you take afew moments to view ‘wwnw.docs.python.org/3/library/idle.html, which detais many of the IDLE's Features. womgeipbtiationscon — QE] ED) cain saresisten) Your First Code UCT cM cuN Mga setomet Meee ass) everyone!”)’ Function from the previous tutorial, However, let's expand that and look at Nee h Vol meee ET eM LCCC RMR o Kel Tene Coe PLAYING WITH PYTHON ‘With most Languages, computer or human, it’s all about remembering and applying the right words to the right situation. ‘You're not born knowing these words, so you need to learn them. ESTeEEDD you've closed Python 31DLE, reopen itn BETES) ou cansee that instead of the number 4 the whichever operating system version you prefer. In ‘output isthe 2+2 you asked to be printed to the the Shel, enter the Famiiar Follows screen. The quotation marks are defining whats being outputted aon tothe IDLE Shelto print the total oF 2+2 you need to remove print¢“Helto”) aaa print(2+2) Justas predicted, the word Hello appears in the You can continue as such, printing 242, 46442343 Shell as bive text, indicating output From a string. 3nd Soon to the Shell An easier ways tousea Its Fairly straightforward and doesn't require too much explanation. variable, whichis something we will coverin more depth later. For Now try now, enter: printcr2+2") ae ESTEEM) what you have done here isassign the letters and b two values: 2 and 2. These are now variables, ‘hich can be called upon by Python to output, add, subtract, divide ‘and so on For as ong as their numbers stay the same. Ty this: printca) print) er The output ofthe as step dpaythe current SUEDE values of both a and 0 individually, as you've asked them to be printed separately. If you want to add them up, you can use the following: print(atb) ‘This code simply takes the values of @ and b, adds them together, ‘and outputs the result, ‘Ea She big ure Bent Eee Ege SP a TT BETA 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” printCname) y ( Your First Code NS CH PPT Nowlet’s adda surname: surnane="Hayward” print(surname) ‘You now have two variables containing a first name and a surname and you can print them independently FIED we were to apply the same routine as before, using the + symbol, the name wouldn't appear correctlyinthe outputin the Shell. Tr it print(namessuenane) You need a space between the two, defining ther as two separate values and not something you mathematically play around with. eG od Bon ne we i In Python 3 you can separate the two variables Sia with a space using a comma printCname, surname) ‘Alternatively, you can add the space yourself printCname+” “+surname) ‘The use of the comma is much neater, as you can see. Congratulations, you've just taken your First steps into the wide ‘weld of Python. swoelpbeationscom EX 0 ) Getting Started with Python Saving and Executing Your Code Whilst working in the IDLE Shell is perfectly fine for small code snippets, it’s not designed For entering longer program listings. In this section you're going to be introduced to the IDLE Editor, where you will be working from now on. EDITING CODE ‘You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the IDLE Editor will allow you to save and execute your Python code. ESTeERED Fi'st open the Python IDLEShell and when t's up, JES tsage You can see that the same colour coding sin place ck on File» New Fle. This willopen anew window in the IDLE Editor as isin the Shell, enabling you ‘with Untitied as es name. Thisis the Python IDLE Editor and within it to better understand what's going on with your code, However, to you can enter the code needed to create your future programs. execute the code you need to first save it. Press FS and you get a Save...Check box open. = ESTEEM The IDLE Editor is, for all intents and purposes, @ ESTeEE DD iickon the Ox button in the Save box nd select a simple text editor with Python Features, colour destination where you" save all your Python code. ‘coding and so on; much inthe same vein as Sublime. You enter ‘The destination can be a dedicated Folder called Python or you ‘code as you would within the Shell, sotaking an example from the can just dump it wherever you lke. Remember to keep a tidy drive previous tutorial, enter: though, to help you out inthe Future. print(“Hello everyone!) Enter aname for your code, ‘print helo’ for ‘example, and ick on the Save button. Once the Python code is saved it's executed and the output will be detailed in the IDLE Shell In this case, the words ‘Hello everyone!” BPI) Thi is how the vast majority of your Python code willbe conducted. Enter itinto the Editar, hit FS, save the code and look atthe output in the Shell. Sometimes things. will differ, depending on whether you've requested a separate window, but essentially thats the process.’ the process we wil use thraughout this book, unless otherwise stated, Ee Eo Set Din ae nso ayer ee ee Saale Ifyou open the fil location ofthe saved Python code, you can see that it endin a.py extension, ‘Thisis the default Python file name. Any code you create will be ‘whatever.py and any code downloaded from the many Internet Pyehon resource sites wil be py, Just ensure that the codes written for Python 3. Saving and Executing Your Code CH Let's extend the code and enter afew examples From the previous tutorial: nane="David” surnane="Hayward” print(nane, surname) print Casb) IF you press F5 now youl be asked to save the ile, again, as it’s been modified from before. Ifyou clckthe OK button, the file willbe ‘overwritten with the new cade entries, and executed, with the outputin the Shell I’s nota problem with just these Few lines but if you were to edita larger ile, overwriting can become an issue. Instead, use File > Save As From within the Editor tocreate abackup. Be eR ED Now create anew file. Close the Editor, and open ‘anew instance (Fle > New File From the ShelD, Enter the Following and save tas helo py a="Python” baris” "cool!" print(a, b, ¢) ‘You will use this code inthe next tutorial | Seabee 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 in the GUL at the command line level. you're atthe command line we can start hon. For Python 3 youneed to enter the waysis with Python 2, whilst the other uses the Python 3 libraries command python3 and press Enter. This will put youinto the and s0 on. First though, drop into the command line or Terminalon command line version ofthe Shel, withthe Familiar three right: ‘your operating system, Facing arrows asthe cursor (>>), asbefore ar EEZD cooneesovreaetoenerinecocsoine reusing Iooked a previousty seh os erty Pi: Windows users wil = click the Start button and i +h For CMD, then click the Command Line returned search and macOS users can get access to their command line by dicking Go> Utlities > Terminal a2 primt(a) You can see that it works exactly the same. fytnan & + Coding Executing Code from the Command Line CH EapD Now enter: exit) to leave the command tine Python The result of running Python 3 code from the session and return you back to the command Python 2 command line is quite obvious, Whilst it prompt. Enter the folder where you saved the code from the previous tuterial and list the available files within; hopefully you should see the hel ferences between the the Print command over Python 2, the result Using Sublime for the moment, open the isn'tas we expecte hellopy file PPD Fromithin thesame folder as the code youre PPED since Sublime Text isnt available for the Raspbe doing to run enter the Following into the P;, you're going to temporarily leave the Pi for the command line: ‘moment and use Sublime as an example that you dor't necessarily a pete tenet thon DLE Withee le open, alr te ane=inputC"What is your name? *) a="Python” printC‘Hello,”, name) beri? c="cool!” print(a, b, ) FETTER) Noturally, since this is Python 3 code, using the PETRET PD Seve the hello.py ile and drop backto the syntax and layout that’s unique to Python 3, it only command line. Now execute the newly saved ‘works when you use the python3 command. Fyou like trythe same code with: ‘with Python 2 by entering python hello.py This will execute the code we created, which to remind you is python3 hello.py The result willbe the original Python is cool! statement, together with the added input command asking you For your name, and displaying it in the command window. C3 Getting Started with Python Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the like. Let's expand on that now and see just how powerful Python is as a calculator. You can work within the IDLE Shell or in the Editor, whichever you like. IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as languages, maths is the driving Force behind the code. EETESEID Pen up the Gu! version of Python 3, as mentioned you can use either the Shell or the Editor. For the time being, you're going to use the Shell ust to warm our maths muscle, which we believe isa small land located atthe beck of the brain or nob. PEPER the shell enter the following 22 '54356+34553245 99867344°27344484221 ‘You can see that Python can handle some quite large numbers. Ieee ee atts ts an, ED vitor a coe cosng ‘most, if notall, programming You can use al the usual mathematical operations: divide, multiply, brackets and so on, Practise with a Few, for example: 1 6/2 24283 2+") You've no doubt noticed, dvsion producesa decimal number. In Python these are called floats, or floating point arithmetic, However, f you need an integer as opposed to a decimal answer, then you can use a double slash we 6/2 ‘Andsoon. (Numbers and Expressions You can also use an operation to see the remainder left over from division, For example: 10/3, wil splay 3333333333, which’s of course 3.3recurting.Fyou now enter: 1053, “This wil dsplay 1, which i the remainder left over from dividing 10, into3. "Next up we have the power operator, or ‘exponentiation if you want to be technical To work ‘out the power of something you can use @ double multiplication ‘symbol or double'star on the keyboard: 203, 10°10 Essentially it's 2x22 but we're sure you already know the basics behind maths operators. Tis is how you would work tout in Python. BRTEGEAD umbersand expressions don't stop there. Python has numerous builtin Functions to work out sets ‘oF numbers, absolute values, complex numbers and a host oF mathematical expressions and Pythagorean tongue-twisters. For ‘example, to convert a number to binary, use: bing) ‘This willbe displayed as ‘0b11", converting the integer into binary and adding the prefix Ob to the Front. you want to remove the Ob prefix, then you can use: format(3, ‘b") “The Format command converts avalue, the number 3,to.2 formatted representation as controlled by the Format specification, the’ par. FETSEE DD /800lean Expression is. logical statement that will tither be true or false, We can use these to compare dataand test to see it's equal to, less than or greater than. Try this Ina New File: a-6 b=7 print, a == 6) print(2, a == 7) print(@3, a == 6 ond b == 7) print(4, a == 7 and b == 7) print(S, not a == 7 and b == 7) print(6, o == 7 or b= 7) print(7, a == 7 or b = 6) print(8, not (a == 7 and b == 6)) print(9, not a= 7 and b = 6) Execute the code from Step 9, and you can see a series of True or False statements, depending on the result ofthe two defining values: 6 and 7. I's an extension of ‘what you've looked at, and an important part of programming. swoelpbeationscom C3 Getting Started with Python Using Comments UNA RATA eae R Voll molec Mend a OMe ml eR Lila cle MN UT12) (Reel aN RON 16-1 0 Percofel EMMI Me LiL EDs eR: UMC Rol aCe Me WaT Klee mere Follow the code line by line but over time, it can become difficult to read. #COMMENTS! Programmers use a method of keeping their code readable by commenting on certain sections. IF a variable is used, the programmer comments on what i's supposed to do, For example. It's just good practise. BETTER St2ttby creating anew instance of theiOLE Editor NBR resave the code and execute it. You can see that the (Fle > New File) and create a simple variable and ‘outputin the DLE Shellisstilthe same as before, print command despite the extra lines being added. Simply put, the hash symbol) cae denotesa line of text the programmer can insert to inform them, DRENECETHAIWOLUAIORIATT ETAT) and others, of what's going on without the user being aware. ‘Save the fle and execute the code. Q yen 42st ie Gm Sn rans op Ses Seti Neti or “Lcmety" for nae iforetin SS ee [Be Git amt Bin tone wa TEED ennina the code willreturn the ine: The value of A RSTSSWPMM Let's assume that the variable A that we've created is, 10 into the IDLE Shell window, which iswhat we isthe number of livesin a game. Everytime the ‘expected. Now, add some ofthe types of comments you'd normally player dies the valve is decreased by 1. The programmer could see within code: insert a routine along the lines of: # Set the start value of A to 10 a=a-1 a=10 printC*You’ve just lost a life!”) # Print the current value of A printC*You now have”, a, “Lives left!") print(‘The value of A is,”, a) Whilst we know thatthe varlable A istves, and that the player has just ost one, a casual viewer or ‘someone checking the code may not know. Imagine for a moment that the code istwenty thousand lines long, instead of ust our seven, You can see how handy comments a. # Set the start value of A to 10 a-10 # Print the current value of A print(*The value of A is,”, a) # Player lost a life! a-a-1 # Inform player, and display current value of A lives) printc“You've just lost a lifel") print¢“You now have”, a, “Lives Left!”) Essentially, the new code together with comments could look ike: You can use commentsin different ways. For example, Block Commentsare 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 Despite # who haven’t slept or washed in weeks. being very smelly, the code at least # works really well. a tu Ce t (Using Comments CH PEED tine comments are comments that followa section Cf code. Take our examples from above, instead oF inserting the code on a separate line, we could use: a=10 # Set the start value of A to 10 print(*The value of A is,", 0) # Print the current value of A a-a-1 # Player Lost a Life! printC*You've just lost a life!”) print(*You now have”, a, “Lives left!") # Inform player, and display current value of A lives) ‘The comment, the hash symbol, can also be used to ‘comment out sections of code you don’t want to be executed in your program. For instance, if you wanted to remove the first print statement, you would use: # print(“The value of A is,”, a) a @ Set the start value of A to 10 10 | Prine the current value of A printc"The value of A is Player lost’ life! inform player. and display current value of A (Lives) rine(“vou've just lost a 1ifel) rine(-Yeu now have", a, “Lives left > FETED ov also use three single quotes to comment ‘out Block Comment or multitine section of ‘comments, Place them before and after the areas you want to ‘comment For them to work: This is the best game ever, and has been developed by a crack squad of Python experts who haven"t slept or washed in weeks. Despite being very smelly, the code at Least works really nell. aaer SE swoelpbeationscom EX 0 ) Getting Started with Python Working with Variables Cece chemi amo anes selec Te eee worth going through the way they operate and how Python creates and assigns certain NEWER 12) oe VARIOUS VARIABLES. ‘You'll be working with the Python 3 IDLE Shell in this tutorial. you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. FETED '2s0me programming languages youre required ESSE You've seen previously that variables can be to use a dollar sign to denate a string, whichis a concatenated using the plus symbol between the variable made up of multiple characters, such as name of a person. variable names. In our example we can use: print name + “: In Python this isn't necessary. For example, inthe Shell enter: 4 title). The midéle part between the quotations allows us to nane="David Hayward” (or use your own name, unless you're _add.acolon and a space, as variables are connected without spaces, also called David Hayward). ‘so we need to add them manually eG Sel oes GENE Wr He You can check the type of variable in use by You can also ssuina the type () command, placing the name of the variable inside the brackets. n our example, this would be: ‘within another variable. For ‘type (name). Add a new string variable: t4tL example, to combine both name From Vikings? and ttle variables into a new a variable we use: character=name +“: + title ‘Then output the content of the new variable as: print (character) Numbers are stored as different variables: age=4 Type Cage) Which, as we know, ae integers. BPR oweves,youcentcombine both strings and Suave integer type variables in the same command, as you woud asetofsniarverables Yu needto ether tun oneinto the Uther orc versa Whenyou dotry tocombine bth you get an error message print (nome + age) < Working with Variables ¢ cH ‘This presents abit ofa problem when you want to work with a number that's been inputted by the User, as age + 10 won't work due to being a string variable and an integer. Instead, you need to enter: Sia} intCage) + 10 ‘This ill TypeCastthe age string into an integer that can be ‘worked with xc rome ine see tr ii BRTTSDD This is 2 process known as TypeCasting. The Python, code is: print (character + “ is old.) ‘or you can use! print (character, “is*, age, “years old.”) Notice again that in the last example, you don't need the spaces between the words in quotes asthe commas treat each argument to print separately is “+ str(age) + “ years >>> print (nane + age) Traceback (most recent call Last) File “™, Line 1, n ‘print’ (name * age) Typetrror: can't convert “int* object to str implicitly BiB prine (character's = se" « str(age) =" years old Savill nbyar a Deacended fron vakine is 4 yhrs ole STEP 7 ‘Another example of TypeCasting is when you ask For input from the user, such asa name. For example, center: ‘age= input (“How old are you? “) ‘All data stored from the Input command is stored asa string variable, ‘le lt shal Debug Options windows He 1 Cetaale, Oct 18014, THT fe PERI the use of Typecasting is also important when dealing with floating point arithmetic; eemember: ‘numbers that have a decimal point in them. For example, enter shirt=19.99 Now enter typeCshirt) and you'lsee that Python as allocated the numbers Toa, becase the value contains a decimal pot. aerate Meredits” or “Hicense()” for more information \when combining integers and Floats Python Usually converts the integer to a iat, but should the reverse ever be applied it's worth remembering that Python doesn't return the exact value. When converting afloat to an integer, Python wil always round down tothe nearest integer, called truncatingin our case instead of 19.99 t becomes 19. le Eét_sheb Rebuy Options wows lp ren ae Cra Be a, TTT tyes Scores! Sretsan or “tscansey* for nore information Soe Eppecenare) so thecanirt) C3 Getting Started with Python User Input WSN oes eon ret merle (NM nan eels cKO nL cna) (ord earlier, so now would be a good time to focus solely on how you would get information emt mec ere cnas USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding. For example, a game may ‘ask For a character's name, whereas a database can ask for personal detail BERD its not aready, open the Python 31DLE shell, and tart aNew Fle in the Editor Lets begin with something really simple, enter: print¢*Hello”) firstname=input(“What is your first name? “) print(“Thanks.”) surnane=inputC“And what is your surname? “) Save and execute the code, and as you already no doubt suspected, in the IDLE Shel the program will ask for your first name, storing it as the variable firstname, followed by your sumame; also stored in its own variable (surname) Eafe Now that we have the user'sname stored in a ‘couple of variables we can call them up whenever ‘we want: print(‘Welcone”, firstname, surname, “ you're well today.”) T hope Fests yeya 8 Run the code and you can see aslightissve, the fullstop after the surname follows a blank space. ‘Tocliminate that we can add a plus sign instead ofthe comma in the code: printC‘Welcone”, firstname, surnames. I hope you're well today.”) ‘You dont always have to include quoted text within the input command, For example, you can askthe user their name, and have the inputin the line below: print(“Hello. What”s your name?) nanesinput() seringutpy - /home/pi/Docurnents/Python Code/us) [Ele Edt Farmat Bun Options Windows Help rant( "Helle, what's your nane?") BTID The code from the previous step i often regarded 2s being a litle neater than having a lengthy ‘amount of text the input command, butit'snata rule that's set in stone, so do as you lke in these situations. Expanding on the code, iy this printC“Halt! Who goes there?”) name=inputQ) It's2 good start toa text adventure game, perhaps? STEP 7 Now you can expand on t and use the raw input from the userto flesh out the game litle: if name=="David”: print(‘Welcone, good sir. You may pass. else: print(“I know you not. Prepare for battle!” - (User input CH hat youve cested here sa condon, which we Sra will cover soon. In short, we're using the input from: the userand measuring kagalnst.acondton So the user enters David astheirname the guard wl low them to pass unhindered Ele they entra name other than David, the guard challenges themtoa Pht. PEPE -ust2s youleamed previously, any input froma User is automatically a string, so you need to apply a “TypeCastin 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”) rate = floatCinputC*Rate: ")) FTE EDD 10 finalise the rate and distance code, we can add: distance = floatCinput(“Distance: “)) printC*Time:”, (distance / rate)) Save and execute the code and enter some numbers. Using the Floattinout element, we've told Python that anything entered isa Floating point number rather than a string EX 0 ) Getting Started with Python Creating Functions Now that you've mastered the use of variables and user input, the next step is to tackle functions. You've already used a few functions, such as the print command but Python enables you to define your own functions. FUNKY FUNCTIONS ‘Afunction is a command that you enter into Python to do something. It's little piece of self-contained code that takes data, ‘works on it and then returns the result. BETERDD (¢snotjust data that a function workson.theycan [NSE You can pass variables through Functions in much do all manner of useful things in Python, such as the same manner. Lets assume you want the sort data, change items fram one formatto anather and checkthe numberof letersina person's surname, you could use the Following length or type of items. Basically, a Function is ashort word that's _code (enter the text editor For this example): followed by brackets. For example, ten), ist() or type(). nane=input (“Enter your surname: “) count=Lencnane) print (“Your surnane has", count, “Letters in itd Press F5 and save the code to execute it. PEPTSPDD function takes data, usuallya variable, works on BWA python hastens of functions built into it, Fartoo ‘depending on what the Functionis programmed ‘many to get into in the Limited space available here. todo and returns the end value. The data being worked on goes However, to view thelist of builtin Functions available to Python 3, inside the brackets so if you wanted to know how many letters navigate to www.docs.python.org/3/library/functions.html These 4are in the word antidisestablishmentarianism, then you'denter. ___are the predefined functions, but since users have created many ‘Jen(“antidisestablishmentarianism™) and the number28 more, they're not the only ones available, ‘would return, EETTSIEDD /dcitional runctions can be added to Python {through modules. Python has a vast range oF ‘modules available that can cover numerous programming duties. “They add Functions and can be imported as and when required. For example, to use advanced mathematics Functions enter: import math (Once entered, you have access to all the math module functions. FORGING FUNCTIONS just imported itinto Python, you can utilise the square root Function, Todoso, enter: math.sqrt(16) You can see that the code is presented as module function(data) ‘There are many different Functions you can import created by other Python programmers and you will undoubtedly come across some excellent examples in the Future; you can also create your own with the deF command, eee oe [def Hello():) Hel Loc) Cees type in Hel eneeeans Belen Perens eters Pee ese Ree arte enous Bob"), then: Hello(name). Your eet eet Perr PEED 10 modity cturther delete the Hello(’David" line, the last line in the script and press CtrlS to save Tee aioe iret oceans ee eee teers Seat ad ay wmociictncn CI creating Functions (CI EX 0 ) Getting Started with Python Conditions and Loops eet een Ce Se arae coe enn Ren eee rather complex. How you use them depends greatly on what the program is trying to Ea ment eel] Coan Ma unmade Rec Lom ies ly ee Reon a ceo 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 isn't. BEER 2's create a new Python program that wil ask TERED) Now you can use an istatement to check ifthe te user to inputa word, then checkit to see iF its word length variable is equal to four and print 3 ‘2 fourletter word or not. Start with Fle> New File, and begin with friendly conformation iit applies to the rule: mee word=input(“Please enter a four-letter word: “) wordsinput(“Please enter a four-letter word: “) word_Length=len(word) if word Length == print (word, “is a four-letter word. Well done.”) “The double equal sign (==) means checkif something is equal to something else. ferrite get ere eT PEPER Nowwecancreatea new variable, then use the ten SEAR The colon at the end of iF tells Python that if this function and pass the word variable through ito statement is true do everything ater the colon ‘get the total numberof letters the user has ust entered: that’s indented. Next, move the cursor back to the beginning of word-inputCPlease enter @ four-letter word: *) —_eFitor word_length=Len(word) word=input(“Please enter a four-letter word: “) word_Length=Len(word) ‘if word_length 4: print (word, “is a four-letter word. Well done." else: print (nord, “is not a four-letter word,”) pen mt et ar Now press FS again and rerun the program but ths time enter a Five-etter word, The Shell wl display that i's nota Fourletter word LOOPS. PEPIID Now expand the codetto include another conditions. Eventually, could become quite complex. We've added a condition for threeletter words: Wordsinput(“Please enter a four-letter word: “) word LengtheLen(word) if word length == 4: print (nord, “is a four-letter word. Well done”) elif word_length print (word, “is a three-letter word. Try again.”) else: print (nord, “is not a four-letter nord.”) loop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same block oF code a number of times, usually with the support of a condition. ee a Sie Ce ee uu RL a ny corres x= 1 wile x < 10; print Go) PEED The cifference between if and while is when while eee eg eet eet ee oe tay ee tee ante ta Cer tean rr cease Eee PETTTED the For loop is another example. Fors used to Usually alist stored as ee ee fords=[#Cat™, “Dog”, “Unicorn™ print Cword)) PPP the Fo: loop can also be used in the co example by using the range Function: Hor x in range (1, 10):) print Go) era art wmode 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 EE Although good, the builtin Functions wihin Python are limited, The use of modules, however, allows us tomake more sophisticated programs. As you are aware, modules are Python scripts that are imported, such as import math BED ‘Some modules, especially on the Raspberry P ‘are included by default, the math module being a prime example. Sadly, other modules aren't always avalable. A good example on noni platformsis the pygeme module, which contains ‘many Functions to help create garmes. Try: import pygame, fytnan & + Coding Ea he resultis an error inthe IDLE Shell asthe ygame module isn’t recognised or installed in Python. To installa module we can use PIP (Pip Installs Packag Close down the IDLE Shell and drop into a command prompt or Terminal session. At an elevated admin command prompt, enter: pip install. pygane BED The PIP installation requires an elevated status due it installing components at cifferent locations. \Windows users can search For CMD via the Start button and right, click the result then click Run as Administrator. Linux and Mac users canuse the Sudo command, with sudo pip install package, Close the command prompt or Terminal and relaunch the IDLE Shell, When you now enter: mport pygane, the module willbe imported into the code ‘without any problems. Youll find that most code downloaded or ‘copied From the internet will contain a module, mainstream of Unique, these are usualy te source of errorsin execution due to them being missing a BPTI The modules contain the extra code needed to ‘achieve acertain result within your own cade, as ‘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 ike for i in range(10): printCrandom.randint(1, 25)) a This code, when saved and executed, wil display ten STEP 7 rendam numbers from 1 to 25. You can play around ith the code to display more or les, and From a great or lesser range. For example import random for i in range(25): printCrandom.randint(1, 100)) (Python Modules CH ~~ "Multiple modules can be imported within your code. ‘To.extend our example, use: ‘import random ‘import math for T in range(s): printCrandom.randint(1, 25)) print(aath.pi) ‘The resultisa string of random numbers followed by the value of Pias pulled from the math module Using the print(math.p}) function. You can also pullin certain Functions from a module by using the from and import commands, such as: fron random import randint for i in range(s): printCrandint(1, 25)) a ESTESEE DD Thishelos create amore streamtined approach to ‘programming, You cn also use import module’, which wllimport 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 as m print(m.pi) OF course, adding comments helps to tell others what's going on, Dinan ciennsiOuanehounatens BA =a x ‘vera elpubliatonscom ql Working with Data 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; and see how to use them to forge exciting and useful programs. Then, you can learn how to use date and time Functions, write to files in your system and even create graphical user interfaces that take your coding skills to new levels and into new project ideas. 46 Lists 48 Tuples 50 Dictionaries 52 Splitting and Joining Strings 54 Formatting Strings 56 Date and Time 58 Opening Files 60 writing to Files 62 -xceptions Python Graphics Lists Lists are one of the most common types of data structures you will comes across in Noe Ma Sn Reo) reco Kem eRe Tm OUP Ota ee Lee oe) 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. BETEEEDD 4 lstisa sequence of data values called items. You REESE You can also access, or index, the last item in alist by eeate the name of your list Followed by an equals using the minus sign before the tem number [-1) sign, then square brackets nd the itemsseparated by commas: _orthe secondo las item with [2] and soon Trying to reference an note that strings use quotes item thats thelist such [10] wll turn an error: numbers = [1, 4, 7, 21, 98, 156) nunibersf-1] nythical_creatures ~ [“Unicorn”, “Balrog”, mythical creatures[-4] “Varpire”, “Dragon”, “Minotour”] PEPER ce you've defined your list you can call each PEPP DD sicingis similar to indexing butyou can retrieve byreferencing its name, Followed by a number. Lists ‘multiple tems ina list by separating iter numbers startthe frsttem entry as 0, followed by 1,2, 3 and soon, witha colon. For example: ae nunbers[1:3] = ‘will output the 4 and 7, being tem numbers 1 and 2. Note thatthe Tocall up the entire contents of thelist. returned values don't include the second index postin (asyou ames ‘would numnbers[:3] to return 4 7 and 21). “To callthe thir From zero itermin thelist (21 in this case) SST You can update items within an existing lis, remove fems and even join lists together. For example, to Join two lists you can use: everything = nunbers + mythical_creatures ‘Then view the combined lis with: everything ‘You can view what can be done with lists by entering Sua8

You might also like