You are on page 1of 150
SS The Complete Manual Series C++ & Python VER The essential coding manual for io) 0 C++ and Python programming PAGEs! Want to master your Code? Then don’t miss our NEW Coding magazine on 5 Readily now! aay ein \ The Complete Manual Series ———$ 7-7 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. Learn how to install them, print simple messages to the screen, ask for user input and manipulate the data to produce amazing results. By the end of this book you will understand how Python and C++ work and what potential lies beyond. Ready? Let's get programming! Contents a So ASN ee lho arate) eo Seu) Pees ear ea) SS ey eu) Mae ua Coed a ened Fe eee nes Pye gates PS eae sta hie 28 Executing Code from the Command Line ET ens Ere ecu EN Noo Eres 38 Creating Functions 40 Conditions and Loops Ce emer cae coma Ceci 52 Splitting and Joining Strings 54 Formatting Strings ee od eee rd Meena Ca gc Cece Cee ed Using Modules Cenc OTS be cue cnne es oe Eee RRO Se chckenes Pend Ena 88 How to Set Up C+ in Windows sd Lees Cea Legare Pye rene aie darel E in feet) eT a9 No etenaes Cul crm ere Sr ees oe entre cot cece eset GE eee ST Cec Sy CE eens ST nied SFr aes ee ve Saar Working with Code keane eee Bee ene Taare ae eens eel reece Mee eed 120 Defining Constants rr meanest ee) Say Hello to Python ( Say Hello to Python Cl 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 a vibrant and lively community behind it that shares knowledge, code and project ideas; as wellas bug fixes for future releases. It’s thanks to this community that the language has grown and thrived and now it’s your turn to take the plunge and learn how to program in Python. The first half of this book helps you get started with 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 a character as they move around the screen. @ _WwhyPython? 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 CJ) Say Hello to Python Why Python? SEEN ins eee TeMe Mee See Ament ukcnstcn Pee eset een kia iecit cece rucia ete nie ees Pech yee Rel ei] Gen arate ic work, others for mobile platforms and such. So why choose PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. “These pioneers of programming carved their way into anew Frontier, Forging smal routines that enabled the letter to scroll across the screen. Itmay not sound terribly exciting toa generation that's used to ultrarhigh definition graphics and open world, multi- Regardless of whether you use an Android device, OS device, PC, Mac, Linux, Smart TV, ames console, MP3 player, GPS device builtin toa car, settop box or athousand other connected and'smart’ appliances, behind them allis programming. player online gaming. However, Fortysomething years ago it was, biindinaly briliant. Allthose aforementioned digital 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 canbe built using a variety of programming languages. Naturally these bedroom coders helped form the Foundations for ‘every piece oF ciital 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. ‘The languagesin use today differ depending on the situation, the platform, the device's use and how the device wil interact with its BS | pte ernetnsoitaentscn — ‘iffeursor >= 0) ee ealariieeetl fa» ret ee | [reid scree; rainetocece) ¢ oo nano! sree eee ele Soom meee \coemmonce Boel Rerfocts = HesFocuseep(); ao a tS ee He Rt te ato: Sit Hiri oy lele eatin otcan ttl elit Sinai 8 tate et Seaaee meee) Sires TCL igttee Steed Ut = coum.catanntl) =) >= 01 enmes ies Somer os eur » Fionn Bator fe = olen sclerbinsbed, sorlerPeperi Stic tile hy emer Tet oxecomet) ¢ aan fliop Start eee Timp TRING) inl Shown aol Hise > EGY atte fe awein Bears pea ja i col oom ie 5 ee oe Sees crime: sama [Seer SOF: C++ is usually reserved for more complex ‘programs, operating systems, games and so on. ED seresictincm ‘environment or users. Operating systems, such as Windows, macOS. ‘and such are usually a combination of C++, Ci, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and 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 Faster than others and some: are easierto learn and use than others. Python isone such general- purpose language, Python is what's known asa High-Level Language, in thatit ‘talks! tothe hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countess more interactions. Whilst ts nat as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that i's universally accessible and easy to learn, Te! Tavoke. java foport javaclangereftect.*; Tass nvoke { OBESE vo%d main string (] args) { Qiass ¢ = class. forname( args0] >; Hethod'g = cagetethodt argp(3], Mew class yject ret =m. nyokeC nut, null 3 Tet 5 ca : : wach rovargs\pneses: yee ee SR La WF that method dosn't exist 3 catch car Hee pe ere ar apet a 3) t Ff Sa EEE 8 thd wn ) Ggtch'C anvocationrargetexception ef ) { 7/ an exception ocurred while invoking that inethod Systen.out print n¢ Swethod threw an: * + ¢ getTargetexeeption( “5°; + args(t] Java isa powerful language that's used in web pages, set-top boxes, TVs and / (Why Python ¢ cH Python was created over twenty six years ago and has evolved to become an ideal beginner's language for learning howto program 2 computer. t's perfect forthe hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves or apiece of external hardware and the computer itself Python i free to download, install and use and is available for Linux, Windows, macOS, MS-D0S, 05/2, 8e0S, IBM series machines, and even RISC OS. Ithas been voted one ofthe top five programming languagesin the world andis continually evolving ahead of the hardware and internet development curve. So to answer the question: why python? Simply put, is Free, easy to learn exceptionally powerful, universally accepted, effective and 2 superb learning and educational too. BASIC was once the starter language that early ‘bit home computer users learned. pace pe Python sa more modern take on BASIC, it's easy to learn ‘and makes for an ideal beginner's programming language. ————> z= Say Hello to Python ) Equipment You Will Need You can learn Python with very little hardware or initial Financial investment. You don’t need an incredibly powerful computer and any software that's required is Freely available. WHAT WE'RE USING ‘Thankfully, Python is a multi-platform programming language available For Windows, macOS, Linux, Raspberry Pi and more. IF ryou have one of those systems, then you can easily start using Python. COMPUTER ‘Obviously you're going to need a computer in orderto learn how to program in Python and to test your code. You can use Windows (from XP onward) on either a 32 Cr 64-bit processor, an Apple Mac or Linuxinstalled PC, AN IDE An DE (Integrated Developer Environment) is used to enter and execute Python code. It enables you to inspect your pragram code and the values within the code, as, ‘wellas offering advanced features. There are many different IDEs available, so Find the one that works for you and gives the best results. PYTHON SOFTWARE 1macOS 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 instal Python, which welll cover shortly. TEXT EDITOR Whilst atext editor is an ideal environment to enter code into, t'snot an absolute necessity. You can enter and execute code directly from the IDLE but atext editor, such as Sublime Text or Notepad++, offers more advanced Features and colour coding ‘when entering code. INTERNET ACCESS. Python is an ever evolving environment and as such new versions often introduce ‘new concepts or change existing commands and code structure to make ita more efficient language. Having access to the Internet will keep you up-to-date, help you ‘out when you get stuck and glve access to Python's immense number of modules. TIME AND PATIENCE Despite what other books may lead you to believe, you won't become a programmer in 24+hours. Learning to code in Python takes time, and patience. You may become stuck t times and other times the code wil flow ike water. Understand you're earning wa something entirely new, and you wil get there. Equipment You Will Need Cl THE RASPBERRY PI Why use a Raspberry Pi? The Raspberry Pi isa tiny computer that’s very cheap to purchase but offers the user a fantastic learning platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras. RASPBERRY PI The Raspberry Pi 3s the latest version, incorporating a more powerful CPU, more memory, WiFi and Bluetooth support. You can pick up 2 Pifor around £32 or asa part oF kt For £504, depending on the kit you're interested in 7g FUZE PROJECT a The FUZE isa learning environment built on the latest model ‘of the Raspberry P. You can purchase the workstations that ‘come with an electronics kit and even 2 robot arm for you to build and program. You can find more information on the FUZE at wwuifuze.co.uk Ceding We have several great coding Beginnei titles available vis www. Pron ey bdmpublications.com. Our Pi RASPBIAN books cover how to buy your First Raspberry Pi, setitup and “The Raspberry P's main operating system is a Debian-based use itsthere are some great Linux distribution that comes with everything you need in step-by-step project examples a simple to use package. t's streamlined for the Piand isan and guides to get the most ideal platform for hardware and software projects, Python programming and even asa desktop computer From the Raspberry Pi too. Manua) ere i se Tricks Hacks &Fixes z= 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 to understand. ‘WHAT IS PROGRAMMING? It helps to understand what a programming language is before you try to learn one, and Python is no different. Let’s take 3 look at how Python came about and how it relates to other languages. ‘A programming language ‘sa list oF instructions that ‘a computer follows. These PROGRAMMING RECIPES Programs are like recipes for computers. A recipe to bake a cake could go lke this: fd 0 grant oF butter to the boul. S00 miiiiieres of mii ut 100 grams ofselFraising flourin a bow, E instructionscan beassimple Add 100 gramsof butter tothe bowl E asdsplayingyourname Add 100-militres of milk. orplaying amusic ile, or Bake Forhalfan hour 3 ascomplexas buidinga J whole virtual world. Python | a programming language conceived in the late 1980s by Guido van Rossum ‘at Centrum Wiskunde & Informatica (CW) in the CODE Just ke a recipe, a program consists oF instructions that you Follow inorder. A program that describes a cake might run lke this: bowl = 0 Netherlands as asuccessor to [I four = 100 the ABC language, [J butter = 50 ops (ete mreeasn) Guido van Rossum, the bon! .append([our butter milk] fect father of Python, sake. cook(bowl) PROGRAM COMMANDS. ‘You might not understand some of the Python commands like bowl append and cake.cook(bowl) The firsts alist, the second an object; well look at both n this 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 outhow a program works. re HIGH-LEVEL LANGUAGES Computer languages that are easy toread are known as “high-level” “hiss because they Fy high above the hardware (also referred to as the metal’). Languages that “fly close to the meta," lke Assembly, ‘are known as“lowrlevel’. Low-level languages commands read abit like this:msg db ,@xa Len equ $ - msg PYTHON 3 VS PYTHON 2 ( Getting to Know Python Cl ZEN OF PYTHON Python lets you access al the power of a computer ina language that humans can understand. Behind all this is an ethos called "The Zen of Python." This isa collection of 20 software principles that influences the design of the language. Priciplesinclude "Beautiful isbetter than ualy’ and “Simple isbetter than complex." Type mport this into Python andi wil display all the principles, Ina typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language: Dre eae! WORLD OF PYTHON Magee Petree net Pees ea Cue aa onto) PYTHON 2.X Pere ee eee) See es modul Ba ee ee ee treet na eeu? Toi ee has 5 aes ee ser ees wwwubdmpubliations.com 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. 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. FETE ERD St2rtby opening yourweb browsertowww.python. [ESTEEM Choosing the Customise option allows you to ‘0ra/downtoads/. Look for the button detaling the specify certain parameters, and whilst you may ‘download tink For Python 3.x (in our case this is Python 3.6.2 butas stay with the defaults, it's a good habit to adopt as sometimes (not mentioned you may see later versions of 3) with Python, thankfully) installers can include unwanted additional Features. On the first screen available, ensure all boxes are ticked and click the Next button, J Optional Features oeittin e@ = pyth : windy aa ee FERRER cickthe dourloadbutonforversion3and ERE) the next page of onions include some interesting save the file fo your Downloads folder. when the adationsto Python, Ensure the assocate fe with file is downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables, instalation wizard launch, omer youhavetwochoices. recom Standard brary and stall for Al 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. J Install Python 3.6.2 (32-bit) t Advanced Options ad @ == eo = Crys BOVE i pyth pythi imate tases renner 4 windows —Casermenseieran cam | wind wa Ci 1 or How to Set Up Python in Windows Cl the final Python wizard page will allow you to view the latest release _is newer, as long as it's Python 3.x our code will warkinside your notes, and Follow some online tutorials. Python 3 interf ) Setup was successful = ° py gn - windows oom Before you cose the instal wizard window, ED 2 reser ernest tater gan SiG however, it's best to click on the link next to the Sua) and this time type: CMD, you'll be presented with the shield detaled sable ath LengthLimittiswl alow Python Command Prompt ink Ck ito gett the Windows commandline tobypasthe Windows 260 chracterimtation, enablingjouto._envonment Toenter Python within the command ine, ou need execite Python programs storedin deepfoldersarangements._totype: python and press Enter, ‘gan cick Yesto authenticate the process then you can Close the instalation window ® Disable path length limit Close wn Bere T eR The commandine version of Python works in ‘much the sam way as the Shell you opened in ‘Windows 10 users will now ce Step 8; note the three leftfacing arrows (>>>). Whilst it’s a perfectly fin the installed Python aa fine environment, t's not too user ienly so leave the command 3.xwithin the Start button - line for now. Enter: exit() to leave and close the Command Recently Ac yn. The seein Prompt window. frslink Python 3.6(32-50) f° willaunch the command = line version of Python when clicked (more on thatin a moment). To open the IDLE, type IDLE into Windows start pia I 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 AV telo lel a aaa ME] UCS-LeN Ale Crem (ALR OUR aTelU) Mure CRTC R OUR Te) Lata leet Leon 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. PEPER) open anew Terminal window by clicking Go> PEPER ickon the latest version of Python 3.% in our tities, then double-click the Terminal icon, Now case this the download button for Python 3.6.2 center: python’ ==version. You should see “Python 2.5.1" and _This will automaticaly 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, it automatically Either way, it's best to check forthe latest version. starts the installation wizard (Open Safari and head overto wwwpython.ora/ With the Python instalation wizard open, click on downloads. Just as with the Windows setup the Continue button to begin the installation t's procedure on the previous pages, youcan see two yellow download worth taking @ moment to read through the Important Information buttons: one For Python 3.6.2, and the other For Python 2.7.13, section, in case it references something that applies to your version Note, that version numbers may be different due tothe Frequent of macOS. When ready, click Continue again. releases of Python PC Racca sna ed ‘The next section detals the Software License Agreement, and whilst not particularly interesting tomost folks, t's probably worth 2 read, When you're ready, click on the Continue button once again. Install button, which you need to click to start the actual installation ‘of Python 3.x0n to your Mac. You may need to enter your password to authenticate the installation pracess. Finally you're be presented withthe amount of space Python will take up on yoursystem and an BETEED) The installation shouldn't take too long; the older ‘Mac Mini we used inthis section isa litte slower than more modern Mac machines and it only took around thirty seconds forthe Installation Successful prompt to be splayed, L (_ How to Set Up Python ona Mac Cl FETED There's nothing much else eft to doin the Python installation wizard so you can click the Close button, IF you now drop backinto 8 Terminal session and re-enter the command: python3 =-version, you can see the new version is now listed, To enter the command line version of Python, youneed toenter: python3. To ext, it's: exit, PR cir o oe rni SS ‘Older Mac versions may have trouble with the newer versions of Python, in which case you will need to revert to a previous Python 3.x build; as long as you're using Python 3x. the code in this book will work For you Python 3.1.2 (5312:79360M, Mar 24 2010, 01:33:18) {Gcc 4.0.1" (apple Inc. build 5493)] on’ darwin ‘Type *copyright", "credits" or "License()" for mo Fe information. eosin 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. BEER istyounced to ascertain which version of Python RTE Some Linux distros will automatically update is currently installed in your Linux system as we the installation of Python to the latest versions ‘mentioned, we'e going to be using Linux Mint 18.1 for this section, whenever the system is updated. To check, First doa system update ‘As with macOS, drop into a Terminal by pressing Ctst+Atl+T. and upgrade with sudo apt-get update && sudo apt-get upgrade Enter your password and letthe system do any updates. avidedavidmint = Fle Edt View Search Terminal Help FSTESE RD Nextenter: python’ ==version intothe Terminal JESTER Once the update and upgrade is complete, you screen, You should have the output relating to may need to answer'Y' to authorise any upgrades, version 2.x of Python in the display. Ours n this particular case's _enter: python3. =-Version to see if Python 3xis updated or even Python 2.7.12, installed. In the case of Linux Mint, the version we have fs Python 3.52, which isine For our purposes. davidedavid-mint File Edit View Search Terminal Help ers arr | aire ee ovabmpubiaions.com However, if you want the latest version, 3.6.22s 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 LibncursesnS-dev Libssl-dev libsqlite3-dev tk-dev Libgdbm-dev Libc6-dev Libbz2-dev (pen up your Linux web browser and goto BEG the Python download page: www-python.org/ downloads. click on ne owriaad thon 362 (orwhcheve \ersonts on whenyou lok to downladthe source Python Seaton FETED the Terminal, gothe Downloads folder by entering: ed’ DownLoads/. 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 PPE) Within the Python Folder, enter: -/eonfigure sudo make aLtinstall This could alittle while depending on the speed of your computer. Once finished, enter: python3.6 =-versionto check the installed latest version. ESTEE forthe GUIIDLE, you need to enter the Following command into the Terminal sudo apt-get install idle3 The IDLE can then be started with the command: idle3. Note, that IDLE runsa different version from the one you installed from source. ESTER DD) Youstsonced 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. willbe available via the Programming section in your distro's menu, wwwbdmpubliationscom — | Getting Started with Python Cl Getting started with Python may seema Uittle 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. 22 Starting Python for the First Time 24 Your First Code 26 _ Saving and Executing Your Code 28 Executing Code from the Command Line 30 Numbers and Expressions 32 Using Comments 34 Working with Variables 36 User input 38 Creating Functions 40 Conditions and Loops Python Modules z= Getting Started with Pythor Starting Python for the First Time We're going to be using the Raspberry Pi as our Python 3 hardware platform. The Lele cto mV Ted ol Mem Chye ele aRee ld cael eR Mana eee Lee) eee Wacol ol-E bc La so as long as you have a version 3 Shell, all our code will work. 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. wanerpindescoplnies ckente TERE forename eter 22 3 (DLE. Thsopensthe Python 3Shll Windows and Macuserscan answer 4 Basal Python has takenthe Code’ snd produced the find the Python SIOLE Sel om within the windows Sear button eleven Umut. meu anda rede Be recor “lca for mre ifort, ESTEEM The Shelliswhere youcan entercode andseethe [ESSN The Python Shell acts very much lke a calculator, responses and output of code you've programmed since code is basically a series of mathematical, into Python. Tis isa kind oF sandbox, where you're able to try out interactions with the system. Integers, which are the infinite ‘some simple code and processes. sequence of whole numbers can easly be added, subtracted, rmultiptied and so on, ovabmpubiaions.com (Starting Python for the First Time Cl ESTER While that’s very interesting, it's not particularly FETTER) The Python IDLEis a configurable environment. IF ‘exiting, Instead, try this: you dont lke the way the colours are represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don’t recommend, Justlike the code we entered in Sublime inthe Installing a Text that, a you won't be seeing the same as our screenshots, Editor section ofthis book, print(*Hello everyone!”) TEED Tisisalittle more ket, since you've ust produced ESTEE ust ke most programs avalable, regardless ofthe your First bit of code. The Print command is fairly ‘operating system, there are numerous shortcut self-explanatory, itprints things. Python 3 requires the brackets as keys available. We don’t have room for them al here but within the ‘well as quote marks in order to output content to the screen, inthis Options > Configure IDLE and under the Keys tab, you can see alist «case the Hello everyone bi ofthe current bindings. >>> print("Hello everyone!") Hello everyone! eeeteeee es >>] Tirstamee satan were = Ee eae AD You may have noticed the colour coding within FETE RTO The Python IDLE isa power interface and one the Python IDLE, The colours represent different that's actually been written in Python using one ‘elements of Python code. They are: of the available GU! toolkits. If you want to know the many ins and ‘outs of the Shell we recommend you take afew momentsto view Ceo aes wurw.docs.python.org/3/library/idle.html, which detalis many oF Green-Strings Dark Red — Comments Sener Purple—Functions Light Red Error Messages (Orange Commands IDLE Colour Coding [eotour [usetorTexamptes | Purple | Fincions | tent print Lott red | Enormessages | syntansesor ED) cin sanesaten) Your First Code [ota | VARol A ELON AU INCU RVolt Mea) te Ke) eors (RULER MELA a0) Pen Matic ureter mad err Rare cre ts Nee eC ute e yates 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. FR u've closed thon DLE eopenitin BED irene rumier ate susp whichever operating system version you prefer. In. ua?) ‘output is the 2+2 you asked to be printed to the the Shell enter the Familiar Following: screen. The quotation marks are defining what's being outputted print(tHello”) tthe DLE Selo pn the tal of 22 youreed nremove print (2+2) Ere 2ust2s predicted, the word Hello appearsin the Ere ou can continue as such, printing 2+2, 46442343 Shell as blve text, indicating output from a string, and so on to the Shell. An easier wayisto use a Ie fairly straightforward and doesn't require too much explanation. variable, which is something we will cover in more depth later. For Now try now, enter: printc*2+2") a2 bez, ee What you have done here is assign the letters a ‘and b two values: 2 and 2, These are now variables, ‘which canbe called upon by Python to output, add subtract, divide ‘and soon for as long astheir numbers stay the same. Try this: printCa) print(b) Sia) ‘The output of the last step displays the current SUES values of both a and b individually, as you've asked them tobe printed separately. you want to add them up, you can Use the following: print(asb) ‘This code simply takes the values ofa and b, adds them together, and outputs the result. oe oe oe es oe et Fe ator tame BEPTSED You can play around with different kinds of variables and the Print function. For example, you could assign variables For someone's name: name="David” print(name) ‘ie Eot Soh Dg re races sew eT ET Lea RP a OT Your First Code Cl PET) Now let's adda surname: surname="Hayward” print(surname) ‘You now have two variables containing a first name anda sumame and you can print them independently IF we were to apply the same routine 3s before, using the + symbol, the name wouldn't appear correctly in the output in the Shel. Try it: print Cname+surnae) ‘You need a space between the two, defining them as two separate vvalues and not something you mathematically play around with print(name, surname) ‘Alternatively, you can ad the space yourself: print(name+” “+surname) “The use of the comma is much neater, as you can see. Congratulations, you've just taken your ist stepsinto the wide world of Python InPython 3 you can separate the two variables with a space using a comma’ wwwubdmpubliations.com C) 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. FED verter atantnuen tain BEER vouch rnc tga you can enter the code needed to create your future programs. execute the code you need to first save it. Press F5 and you get a Save...Check box open. ESTEEM The OLEEditoris,forallintents and purposes,a EWP lick on the OK buttonin the Save boxandselect a simple text editor with Python Features, colour Save As From within the Editor to.create abackup. PEPSET RD) Now-create anew file. Close the Editor, and open a new instance (Fle > New File from the Shel), Enter the following and save itas hello py: a="Python” be"is” c="cool!” print(a, b, ¢) ‘Youwill use this code in the next tutorial _ Talopy. hanalpiDoamanainoncrarheopyoaay~ 8 wwwubdmpubliations.com Saving and Executing Your Code ¢ cH 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. Python, in Linux, comes with Now you're at’ and line we Sua sting code via the command line. One of the Sua? Python. For Python ed to enter the ith Python 2, whilst the other uses the Python 3 libraries command python3 and press Enter, Th ut you into the Bnd soon Frstthough drop into the commandline or Terminalon command ne version ofthe Shel, wth he famr te igh Your operating Sater facg arrows the curser Ea From here you'te able to enter the code youve looked at previously, such as jows users wil sro a=2 art button and = print(a) need to click th search For CMD, that it works exactly the same. Go > Utlities > Terminal Executing Code from the Command Line Cl FETED Now enter: exit( to eave the command line Python session and return you back tot prompt. Enter the Folder where you saved th previous tutorial and list the available files within; hopefully you should see the hellopy file. command ine rom within the same folder as the code you're going to run, enter the Following into the python3 hello. py Thiswill execute the code we created, which to remind yous ‘a="Python”” beris” c="cool!” print(a, b, ¢) python hello.py The esttof runing Python 3 code frm the Uae Python 2 command line is quite obvious. Whilst it does error out any way, due tothe dferencesbetweenthe way Python 3 andes the rnecommandover Python 2, the esl [sites we expected: Ung Sublime Fr the moment open the hal py ie. PEPER Since Sublime Text isnt available forthe Raspberry Pi, you're going to temporarily leave the Pifor the ‘moment and use Sublime as an example that you don't necessarily need to use the Python IDLE. With the hello.py file open, alteritto include the Following: nane=inputCWhat is your name? “) print(*Hello,”, name) ‘Save the hellopy file and drop back to t ‘command line. Now execute the newly saved code with 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. C) Getting Started with Python Numbers and Expressions eS cae ne es aue emetic eae ONCE iene nena eee en aE ee ates een eC nice eect cine fe N ele ane at-8 Peano Men ele LAR Aen Cole Lon IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, maths is the driving force behind the code. FETED Per up the Gul version of Python 3, as mentioned you can use ether the Shell or the Editor. For the time being, you're going to use the Shell ust to warm ourmaths muscle, which we believe isa small gland located atthe back of the brain or not). eS a Jigs Serhan PEPER the shell enter the following: 22 54356+34553245 (99867344*27344484221 ‘You can see that Python can handle some quite large numbers. sem ngtatoscom FED os cosconcmvensesenirs Few, for example: 24283 2+@"4) You've no doubt noticed, dvsion produces a decimal number. In Python these are called fioats, cr floating point arithmetic. However, f you need an integer as ‘opposed to a decimal answer, then you can use a double slash: Siar Sia) 10/3 will splay 3333333333, whichis of course 3.3-recurring.IFyou nowenter: 1053 “This wil display 1, which isthe remainder left over from dividing 10, into3. You can also use an operation to see the remainder left over From division, For example: "Next up we have the power operator, or SAD &onertstion you watto be techrical To work ‘out the power of something you can use a double multiplication ‘symbol or double'star on the keyboard: ea 10°10 Essentially, it's 2x2x2 but we're sure you already know the basics behind maths operators. This s how you would workit out in Python. PEPTSED) Numbersand expressions dor't stop there. Python has numerous builtin Functions to work out sets ‘of numbers, absolute valves, complex numbers and a host of ‘mathematical expressions and Pythagorean tongue-tisters. For, ‘example, to convert a number to binary, use: bing) Numbers and Expressions Cl ‘This will be displayed as ‘0b11, converting the Sia) integer into binary and adding the prefix 0b to the Front. f you want to remove the Ob prefix, then you can use! format(3, ‘b’) The Format command converts a value, the nurnber 3, toa Formatted representation as controlled by the Format specification, the’ part. ‘Boolean Expressions a logical statement that will BMD nerve tue or fae We can use these to compare data and testto see if it's equalto, less than or greater than. Try this inaNewFle: a=6 b=7 print(1, a = 6) print(2, a == 7) print(3, a == 6 and b print(4, a == 7 and b print(S, not a == 7 and b == 7) print(6, a == 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) PEPETR) Execute the cade 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's an extension of ‘what you've looked at, and an important part oF programming. a: C) Getting Started with Python Using Comments When writing your code, the Flow of it, what each variable does, how the overall program will operate and so on is all inside your head. Another programmer could Follow the code line by line but over time, it can become difficult to read. #COMMENTS! Programmers use a method of keeping ther code readable by commenting on certain sections. If variables used the Programmer comments on what it’s supposed to do, for example. It's just good practise. Start by creating a new instance ofthe IDLE Editor EED Resave the code and execute it: You can see that the aaa (File > New File) and create a simple variable and ua?) output in the IDLE Shell is still the same as before, print command: despite the extra lines being added, Simply put, the hash symbol (#) a denotes a line oftext the programmer can insert to inform them, print(*The value of A is,”, a) and others, of what's going on without the user being aware. Save the file and execute the code. ‘aera py- ro plOcoaranIPyonComtanrnregya2) = 8 FETED Renninathe code willreturn theline:Thevalue of A [REESE Let's assume thatthe variable A that we've created 's, 10 nto the IDLE Shell window, which is what we isthe number of livesin a game. Everytime the ‘expected. Now, add some ofthe types af comments you'd normally player dies, the value 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 010 printC*You’ve just lost a life!”) # Print the current value of & print(*You now have”, a, “Lives left!” print(‘The value of A is,”, a) EE vebimpubicaionscom Sia) Whilst we know that the variable is tives, and that the player hasjust lost one, a casual viewer or ‘someone checking the code may not know. Imagine for a moment that the code is twenty thousand lines long, instead of just our seven. You can see how handy comments ae. reset ts Ha | # Set the start value of A to 10 a-i0 # Print the current value of A printC*The value of A is,”, a) # Player lost a life! on0-1 # Inform player, and display current value of A Gives) print(*You’ve just lost a life!) print(*You now have”, a, “Lives Left!”) Essentially, the new code together with comments could look ike: You can use comments in different ways. For ‘example, Block Comments are a large section of text that detalls 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 # who haven’t slept or washed in weeks. Despite being very smelly, the code at Least # works really well. ¢ Using Comments Cl FETED ine comments are comments that follow a section (of 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,”, a) # Print the current value of A a=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) ‘The comment, the hash symbol, can also be used to ‘comment out sections of code you don't want to be STEP 9 executed in your pragram. For instance, if you wanted to remove the first print statement, you would use: # printc“The value of A is,”, a) ance Windows Help 7 Set the start valuw oF A to 10 F print("the value of A is,", a) = Player lost’ life! # Inform player. and display current value of 4 (lives) prane(“rou've just lost a life!) Print(-You non have", a, “Lives left!) | 2 Prine the current value of A PEPER) You also use three single quotes to comment ‘outa 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 havent slept or washed in weeks. Despite being very smelly, the code at least works really well. aye ae: C) Getting Started with Python Working with Variables eee ecm ne Canaries eet a oe es Mera esr hearers tues arte INCA CoRR ZI 12) 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. insome programming languages you're required BANGED ose a lersigntodenateastrng.whichisa variable made up of multiple characters, such asa name of a person. InPython tis isnt necessary For example, inthe Shell enter: rname=”David Hayward” (or use your own name, unless youre aso called David Hayward). [ie Eat Oot Gt ro an BETTER You can check the type of variable inuse by [ssuing the type () command, placing the name of the variable inside the brackets. In our example, this would be: ‘type (name). Add a new string variable: titLe="Descended from Vikings”. sem ngtatoscom FD oc scnsesocy vorrei variable names, In our example we can use: print Cname + “: “ + title). The middle part between the quotations allows us to adda colon and a space, as variables are connected without spaces, so we need to add them manually He 5 Shel Be ans Mose EA PPD Youcanalco combine variables ‘within another variable. For ‘example, to combine both name and title variables into a new variable we use charactersname + “: “+ title ‘Then output the content of the new variable as: print (character) Numbers are stored as different variables: age=44 Type Cage) Which, as we know, are integers However, youcan't combine both strings and integer type variables in the same command, as you Sia) ‘would a set of similar variables. You need to either turn one into the ‘other or vice versa, When you do try to combine bath, you get an ‘error message: print Crane + age) Working with Variables Cl FETTER) 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: intCage) + 10 ‘This wil TypeCast the age string into an integer that can be worked with. This @ process known as TypeCasting. The Python BaD s": print (character +“ is “+ str(age) + “ years 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 >>> print (mane + age) Traceback (most recent call Last): Pile “epysheltnies", line tn prin’ (name + age) Typetrrer: Can't convert “int* object to str implicitly S8Sprane (character #32"! + str(age) +" years old David Hayward: Descended fron Viking years lg. Seo prune (character, "is", age, "yt years ole center: ‘age= input C“How old are you? “) All data stored from the Input command is stored as string variable. le Et shel nebug aptons_wndows HP Ton F7 (aetao Oct 9 201 TTY ‘Another example of TypeCasting s when you ask for input From the user, such as a name. for example, ow SES ae you! a claat "see" for ESTEE 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: shirte19.99 Now enter typeCshirrt) and you'l see that Python has allocated the number 3s a float, because the value contains 8 decimal point. 2 (Gatault, Oct 19 2014, TBST tion Linax acpyrsgheh Merests” or “License fo Soe Secantee) clase fieat'> BERET When combining integers and Floats Python usually converts the integer to a float, but should the reverse ever be appliedit'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, called truncating; in our case instead of 19.99 t becomes 19. bn ap won ee Tet cae wc Saas Soe Snecshirt) ‘ 2, a: C) Getting Started with Python User Input REL ol ey elo nee ee Ne eels Meu Tom eC oy Senne eaten Mareen C camry Lic M eg AU anole ae 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 details. BRTEEERD i’snotalready, open the Python 3 IDLE shell, and start a New Filein the Editor Let's begin with ‘something realy simple, enter; print¢*Hetto”) firstnanesinputC‘What is your first name? “) print(*Thanks.*) surnane=input(“And what is your surname? ‘Save and execute the code, and as you already no SUaP2 doubt suspected, in the IDLE Shell the program will askfor yours name storing asthe variable stam fllowed byyoursuname; ako stored in ison variable urna) we want: Now that we have the user’s name stored ina couple of variables we can call therm up whenever print(*Welcome”, firstname, surname, “ you're well today.”) T hope Run the code and you can see a slight issue, the fullstop after the surname follows a blank space. ‘To.eliminate that we can add a plus sign instead of the comma in the code: printC‘Welcome”, firstname, surnanet. I hope you're well today.) You don't always have to include quoted text within, Sia) the input command. For example, you can ask the User their name, and have the inputin the line below: print(“Hello. What’s your name?) rnane=inputQ userinputpy -/home/pi/Documnents/Pythan Code/ust le Edt Farmat sun Qptions windows Help Drint(Helle. What's your none?) (_User input Cl ‘What you've created here is aconeition, which we will cover soon. In short, we're using the input from the user and measuring itagainsta condition, So, ifthe user enters David as their name, the guard wil allow them to pass unhindered, Else if they enter a name other than David, the guard challenges them to fight. FPR ston oe rs sens cts ‘stone, so do as you like in these situations. Expanding on the code, print(“Halt! Who goes there?”) ‘name=input() EPID 2 good start toa text adventure game, pechape? [Now you can expand on it and use the raw input from the usertofleshoutthe game alittle: if nane=="Davia”: printC‘Wlelcone, good sir. You may pass.” else: print(*I know you not. Prepare for battle!” FETED ust2s you learned previously, any input froma user is automaticaly a string, so you need to apply 2 “TypeCastin order to turn itinto 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 = floatCinput(“Rate: “)) “Tofinalise the rate and distance code, we can add: distance = floatCinput(“Distance: “)) print(*Time:”, (distance / rate)) Save and execute the code and enter some numbers. Using the Float(input element, we've told Python that anything enteredis a Floating point number rather than a string Sra sebirotentsom C) Getting Started with Python Creating Functions Nes eh uses te eg ur cee alata nee nla TNC ee Came eet intents oT aen Cock marten ones 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. I's not ust data thata function works on, They can SME 50 ai manner of useful things in Python suchos sort data, change items From one Format to another and check the length or type of items. Basically, a Function is ashore word that's Followed by brackets. For example, ten), ist() or type(). BETISERD 4 function takes data, usually variable, works on depending on what the Function is programmed to do and,eturns the end value. The data being worked on goes inside the brackets, so if you wanted to know how many letters ‘aren the word antidisestablishmentarianism, then you'd enter: ‘Ten(“antidisestablishnentarianism™) and the number 28 ‘would return, ED vembsmpubicaionscom PEPER) ou con pass variables through Functions in much, the same manner Let's assume you want the numberof letters in a person's surname, you could use the Following code (enter the text editor For this example): nanesinput (“Enter your surname: “) count=LenCnane) print (“Your surname has, count, “Letters in’ it.) Press F5 and save the code to executelt. BSED cron has tens of functions bultintot, far too many to getintoin the imited space avaiable her. However, o view thelist of builtin functions avaliable to Python 3, navigate to wwrw-docspython.ora/3/ibrary/Functions.html These are the predefined functions, but since useshave created many more, they're not the only ones available. ‘Additional Functions can be added to Python a0 ‘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 BETTS) 0 vse a function from a module enter the name of the module Followed by afull stop, then the name of the Function. For instance, using the math module, since you've just imported it into Python, you can utlse the square root function, Todo so, enter: math. sqrt(16) You can see that the code is presented as module function(data). Bu era eee ie au Cue rem ac ean Peer ere ne us ae see ents STEP 1 Enter ideF Hel lo0):) HHelloc) Cee es eet en Cree nearer ites a type in Hello() and it returns the new Function peroneet Idef_HelloCname) :} print CHeTlo™ name) mee eee eet rene Seen epee et ato ees Peat Function can now pass variables through it reate your own with the def command. eae the last line in the script and press CtrlsS to save see ie Tete eer tees oe Cees ees ease eens What you've From the vid. This is how modules a ae: C) Getting Started with Python Conditions and Loops eons Ce se MaP ae Ce MMC nen ees Umea antl asut ati meray eeu tal 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 isn't. Les rate anew Python program that wl ask Suet) ‘the user to input a word, then check it to see iF it's: 2a fouretter word or not, Start with File > New File, and begin with the input variable: wordsinput(“Please enter a four-letter word: “) Now wecan create a new variable, then use the en SUEP2 function and pass the word variable through it to ‘get the total numberof letters the user has just entered: word=input(“Please enter a four-letter word: “) word_length=Len(word) ED vebsmputicaonscom Now you can use an fstatementto check ifthe ‘word length variable is equal to four and print a Friendly conformation iFit applies to the rule: wordsinput(“Please enter a four-letter nord: ) word_length=Len(nord) if word_length == print (word, “is a four-letter word. Well done.”) “The double equal sign (==) means check if something is equal to something ese. Sse} FEPTPD The colon at the end of IF tells Python thatif this statement is true do everything after the colon that's indented. Next, move the cursor back tothe beginning of the Editor: wordsinput(“Please enter a four-letter word: “) word_length=LenGnord) if word length == 4: print (word, “is a four-letter word. Well done.”) else: print (word, 's not a four-letter word.”) Sit med ie at 3 feet mr) PETES 1255 F5 and save the code to execute it. Enter ‘a fourletter word inthe Shell to begin with, you should have the returned message that it's the word is four letters Now press FS again and rerun the program but this time enter a five-letter word, The Shell wil display that it’s not a four-letter word LOOPS. oo block oF code a number of times, usually ere nee ates eer en a nant STEP 2 Dee eee eg ere eet od en eer For x in range (1, 10):| Now expand the code to include another conditions. 1a added a condition for three-letter words: wordsinput(“Please enter a four-letter word: “) word_Length=Len(word) if word length == 4: print (nord, “is a four-letter word. Well done.”) elif vord_tenath print (word, “is a three-letter word. Try again. else: print Cnord, “is not a four-letter word.”) milar to @ condition but they are somewhat different in their operation. A loop will run through the same Teta eens gets Teme ees te eee ords=[“Cat™, “Dog”, “Unicorn” ]} For word in words: print nord)) eae ee etn ‘example by using the range Function: Cera numbers used. 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 SED icistgorttetutin neces wiin ron BEBEEB tereutsaeorinte Ou Sota are Python scripts that are imported, such as import math Close down the IDLE Shell and drop into a command prompt or Terminal session. At an elevated admin command prompt, enter: pip install pygane Fe yeeE Some modules, especially on the Raspberry Pi ary PIP installation requires an elevated status are included by default, the math module being a ue itinstalling components at different locations prime example. Sadly, other modules aren't always avalable. A good Windows users can search for CMD via the Star button and right: example on non-Pi platforms isthe pygame module, which contains click the result then click Run as Administrator. Linux and Mac users ‘many Functions to help create games. Try: import pygame, can use the Sudo command, with sudo pip install package. {lose the command prompt or Terminal and relaunch the IDLE Shel. When you now enter: ‘import: pygame, 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 usually the source of errorsin execution due to them being missing C Python Modules Cl Multiple modules can be imported within your code. Sia) To.extend our example, use ‘import random ‘import math for I in range(5): print(random.randint(1, 25)) print (math. pi {a The modules contain the extra code needed to achieve a certain result within your awn 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 like: for i in rangeC1o): print(randon.randint(1, 25)) a BETTIE 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, and from agreat or lesser range. For example: ‘import random for i in range(2s) printCrandom.randint(1, 100)) The resuisasbing of rendor numbers folowed illite by the value of Pias pulled From the math module using the print(math.pi) function. You can also pull in certain Rants fom a mode by sng the fom andor commands, Senos from random import randint for i in range(s): printCrandint(1, 25)) B PEPER Tisheles create amore streamlined approach to programming, You can also use import module*, ‘which will mport 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 thers what's going on, tinny Cin snitmmenlpienatente BA - a x wmbirottansen CE 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 andTime 58 Opening Files 60 Writing to Files 62 Exceptions Python Graphics ED) eins) Lists eee tet tess Me eon eT Coe ney PAAR TOlccned cue eat iecniceut crest! as a whole, or individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. list can be strings, ‘and ists within lists. \tegers and also variables. You can even include Functions in lists, Alatsaseaene of datasets ou TRIBE Youn so ces rnc tetem nal Suet) create the name of your list Followed by an equals Sua? using the minus sign before the item number [-1], sign, then square brackets and the items separated by commas; _or the second to last item with [2] and so on. Trying to reference an note that strings use quotes: item thatisntin the list, suchas [10] will return an error: numbers = (1, 4, 7, 21, 98, 156] runbers{-1] mythical_creatures ~ ["Unicorn”, “Balrog”, ythical_creatures(=4] “Vampire”, “Dragon”, “Minotour”] BEPTSER nce you've defined your list you can call each PPFD licngissimilarto indexing but you can retrieve by referencing its name, followed by a number. Lists multiple temsin a ist by separating tem numbers start the first item entry as, followed by 1,2, 3 andso on with colon. For example: Forexample: nunbers[2:3] — ‘will output the 4 and 7, being item numbers 1 and 2. Note thatthe To call up the entire contents of thelist feturned values don't include the second index postion as you or would numbers{1:3] to retin 4, 7nd 21). ‘To callthe third from zero ter nthe ist (21 in this cas). See TTS ee ee ee etagree: wen mrs | Sia) You can update tems within an existing lis, remove items and even join ists together. For example, to Join two lists you can use: everything = nunbers + mythicol_creatures ‘Then view the combined lit with: everything FETTER cers can be added toalist by entering: punberssnunbers+[201] Or for stings: mythical_creatres-nythical_creatures+([“Griffin”] ‘Or by using the append Function: mythical_creatures.append¢*Nessie”) ‘numbers .append(278) Removal of items can be done in two ways. The first Isby the tem number: del numbers{7] ‘Alternatively, by tem name: mythical creatures. renoveC“Nessie”) Sia) Functions, for example, insert and pop are used to add and remove items at certain positions. To insert the number 62 at item index 4: ‘You can view what can be done with lists by entering dirlist into the Shell The outputs the available numbers -insert(4, 62) Toremove it: nunbers .pop(4) You also use the ist Function to breaka string down Sa) into its components. For example: List¢“Davia") Breaks the name David into Da," ‘This can then be passed toanew list: nane=List(“David Hayward") Based on that, you can create a program to store someone's name and age asalist: nane=inputCWhat’s your name? “) Iname=ListCname) age=intCinputC“How old are you: “)) Lage=[age] user = Iname + Lage The combined name and age lis i called user, which can be called byentering user into the Shell. Experiment and see what you can do. sentence = Ci & Working with Data Tuples are very much identical to lists. However, where lists can be updated, deleted or Ce eee Cenk oneeh anne cite cene ay perfect for storing Fixed data items. THE IMMUTABLE TUPLE Reasons for having tuples vary depending 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. FE cicisccandvcsmnenayscbens ERBBBR oxconcexe pencounesrsis tcoan ED ons correc Cee eee mes rreu ccs dertahs Sacer cnet cont ne Pr oy inline ie “May”, “June” NPC=[C*Conan”, 100), (“Belit”, 80), (“Valeria”, months 95)] eae 2ust2swith tists, theitemswithin a named tuple can [RBTESBMM Each ofthese data tems can be accessed asa bbe indexed according to their position inthe data ‘whole by entering NPCinto the Shelt or they can be range, ie. indexed according to their position NPC(0), You can alsoindex the nonthstal individual tuples within the NPC tis: months(5] NPcCo} (1) However, any attempt at deleting or adding to the tuple willresult will display 100. inan errorin the Shel. ESTESEERD ¢s worth noting that when referencing multiple tuples withina lst, the indexing is sightly different from the norm. You would expect the 95 combat rating ofthe character Valera to be NPC{4][S], butt's not. I’s actually: NPCL21E17 Now unpack the tuple into two corresponding variables: Sia) Chane, conbat_rating)=NPC ‘You can now check the values by entering name and combat_rating BETISIERD This means of course thatthe indexing follows thus: @ mm 0, 0 a 0,4 20 1 24 1,0 ‘Which as you can imagine, gets litle confusing when you've got a lot oF tuple data to deal with. EPI M Tuples though utilise a feature called unpacking, where the data items stored within atuple are assigned variables. Fist create the tuple with two items (name and ‘combat rating): NPC=¢*Conan”, 100) Remember with its, youcan aboindextupls Sa) using negative numbers which count backwards from the end ofthe data list. For our example, using the tuple with ‘multiple data items, you would reference the Valeria character with NPC(2][-) en Fao PEP SET IB You can use the max and min Functions to find the highest and lowest values of a tuple composed of ‘numbers. For example: hunbers=(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 nax(nunbers)) print min(nunbers)) wmcirosiacsen CE ED) veto Dictionaries Meerut tiene EC ued cea rg of dealing with data items. They can be tricky to get to grips with at first but you'll soon Pee Macuien tates KEY PAIRS A dictionary is like a lst but instead each data item comes as a pair, these are known as Key and Value. The Key part must be unique and can either be a number or string whereas the Value can be any data item you like. BETESERD 2tssayyouwant to create a phonebook in Python. [REEMA As with tists and tuples, you can check the contents ‘You would create the dictionary name and enter ‘of a dictionary by giving the dictionary aname: the data in curly brackets, separating the key and value by colon phonebook, inthis example, Ths wil display the data items you've Key: Value. For example: entered ina similar Feshion to alist, which you're no doubt familar phonebook={“Ema”: 1234, “Daniel”: 3456, “Hannah”: "™"thbynow. 6789} ESTER Just2s ith most lists, tuples and so on, strings EEE The benefit of using a dictionary isthat you ‘need be enclosed in quotes (sinale or double), ‘an enter the key to index the value. Using the whilst integers can be left open. Remember that the value can be _ phonebook example from the previous steps, you can enter: ether a string or an integer, you just need to enclose the relevant book “Enna” accel phonebook “Hannah” ED vbsmpubicaonscom Sia) valve items like: phonebook[“David"] = “0987 654 321” phonebook, ‘Adding toa dictionary is easy too. You can include ‘a new data item entry by adding the new key and You can also remove tems from a dictionary by SUES issuing the del command Followed by the item's key; the value willbe removed as well, since both work as a pair of data items: del. phonebook[“David”] Taking thisa step Further, how about creating a piece of code that will ask the user for the dictionary key and valve items? Create a new Editor instance and start by coding ina new, blank dictionary: phonebook={} iG Dictionaries ( Cc mm Next, you need to define the user inputs and variables: one For the person‘s name, the other Sia) For their phone number (let's keep it simple to avoid lengthy Python code: nane=input (“Enter name: “) nunbersintCinput(“Enter phone number: » Note we've kepthe numbers anintger instead Sa) of a string, even though the value can be both anintegeor sting. Now youneed to adhe ses inputted Yarblesto the newly created bank onary Using the same process sin Ste you can ene phonebook{nane] = number | haotirond Now when you save and execute the code, Python Sra will ask for a name and a number. twill then insert those entries into the phonebook dictionary, which you can test by entering into the Shel: phonebook phonebook [“David"] IFthe number needs to contain spaces you need to make it astring, so remove the int part of the input. wmcirosiacsen CE Working with Data Splitting and Joining Strings When dealing with data in Python, especially from a user's input, you will undoubtedly come across long sets of strings. A useful skill to learn in Python programming is being able to split those long strings For better readability. STRING THEORIES You've already looked at some list Functions, using .insert, .remove, and .pop but there are also Functions that can be applied tostrings. ETEEE DD The maintoolinthe string function asenalis sit). [EATSSIEM Note thatthe textsplit parthas the brackets, sr + eae een sneer Soca based onthe argument within the brackets. For example, here's@__andbrackets. The space isthe separator, indicating that each ist ‘string with three items, each separated by a space: item entry is separated by a space, Likewise, CSV (Comma Separated ‘text="Doniel Hannah Enna” Valve) content has @ comma, so you'd use: text="January, February March, April May, June” months=text. split*,”) ‘months ESTEEM Nowlet’stum the string into a list and spit the BEE You've previously seen how you can split astring content accordingly: into individual letters as alist, using a name: names=text. split ") name=List (“David”) name “Then enter the name of the new list, names, to see the three items. “The returned value is’D,'a, ‘v7, ‘¢*. Whilst it may seem alittle Useless under ordinary circumstances, it could be handy For creating a spelling game for example. smear

You might also like