You are on page 1of 148
RS LEARN PYTHON & C++ CODING Pa ib y The Complete Ct & Python www.pclpublications.com re) de) eel 100% INDEPENDENT The Complete Manual Series Available on Readly inne Ua eutl &iPadOSs @ User Manual ea Manual Pi reoeg b Py, gz Instagram fm _ Internet d Home Cloud User Manual fi Security anual fj Networking | Computing Manual 40) a on Manual @. £5) Papercut For a full list of titles available please visit: www.pclpublications.com 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 MD oo) Contents Cc: The Complete C++ & Python Manual 8 _WwhyPython? 10 Equipment You will Need 12 Getting to Know Python 14 How to Set Up Python in Windows 16 How toSet Up Python on a Mac 18 _ How toSet Up Python in Linux COR ne euch ie ae 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 42__ Python Modules 44) Working with Data 46 Lists 48 Tuples 50 Dictionaries 52 ing and Joining Strings 54 FormattingStrings — —— ACh dave) Date and Time Opening Files Writing to Files Exceptions Python Graphics 68 Calendar Module 70 _OSModule 72__ Random Module 74 Tkinter Module 76 Pygame Module 80 Create Your Own Modules (noukon 84 Why CH? 86 Equipment Needed 88 Howto Set Up C++ in Windows 90 _ Howto Set Up C++ on aMac 92 Howto Set Up C++ in Linux 94 Other C+ IDEs to Install ( Contents FREE CODE DOWNLOAD! , Mm ta ehMac 96) C++ Fundamentals 124) Loops and Decision Making 98 Your First C++ Program 126 while Loop 100 Structure of a C++ Program 128 ForLoop 102 Compile and Execute 130 Do... While Loop 104 Using Comments 132 _|FStatement 106 Variables 134 If... Else Statement 108 Data Types 110. Strings ae 412. C++ Maths COR heat) 114) C++ Input/Output 138 Common Coding Mistakes 140 Beginner Python Mistakes 116 User interaction 142 Beginner C++ Mistakes 118 Character Literals 144 Where Next? 120 _ Defining Constants 122__ File Input/Output wor pepubliations.com Index P ( Say Hello to Python ‘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 well as 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 ystem tools, text adventures and even control a character as they move around the screen. 8 —_WhyPython? 10 Equipment You Will Need 12 _ Getting to Know Python 14 _ How to Set Up Python in Windows 16 How to Set Up Python on a Mac 18 How to Set Up Python in Linux wom pelpubliationscom z= Say Hello to Python Why Python? MEM icens ae cumin) uct ee cmt keel cin PI eee eric nciemac cara ha iceni lcm ete clenc tes Ere Kel cre eho e nl AN M Com uCell CP CeCe Ue mRNA Renee Python out of all the rest? PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. ‘These pioneers of programming carved their way into anew Frontier, Forging small routines that enabled the letter‘ to scroll ‘across the screen It may not sound terribly exiting to a generation that's used to ultrahigh definition araphics and open world, muti player online gaming, However, Forty-something years agoit was blindingly biliant. ‘Naturally these bedroom 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 ‘others pushed the available hardware tots limits and founded the billion pound gaming empire that continually amazes us. Regardless of whether you use an Android device, iOS device, PC, Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin toa car, settop box ora thousand other connected and ‘smart’ appliances, behind them als programming, ‘All those aforementioned digital devices need instructions to tell, them what to do, and allow them to be interacted with, These instructions form the programming core ofthe device and that core ‘canbe built using a variety of programming languages. ‘The languages in use today differ depending onthe situation, the platform, the device's use and how the device wil interact with ts ‘Setcuraor(p, JontseatFocu ay oid trraycertsscitdosrocis() ext ifleurgor > 0) Pefreshrowtcursor): cert chr tacaserocus0: void _sreaear\ paint (orm ») { Sieh Slo; Pbottn boot hsetocus fort} 0; Clete real tasrecusoeep() sbi reoatserolLt) vertgrid falor fe = Stitt ela catcount()) { Fytop —cxtuaney (i) C++ usually reserved For more complex ‘programs, operating systems, games and so on. rest ¥ veontongy) OS BCC * > 1 1 < column. Getcount (); 3s) & Reader cetrabmi dente): Mie v=o colum. catcount() lend{scolorbisabled, scoloreaper); obs GiltPeop Ssazeccy) breaks Pitop t gettinecy(als one environment or users. Operating systems, such as Windows, macOS {and such are usually a combination of C++, C#, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora ofavalable 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 cll them. They're Widely used across all hardware platforms and sult virtually every conceivable application. Some operate faster than others and some are easier to learn and use than others. Python is one such general purpose language. Python is what's known as a High-Level Language, in that ‘talks' to the hardware and operating system using a variety of arrays, variables, objects, arthmetic, subroutines, loops and countless ‘more interactions. Whilst it's not as streamlined asa Low-Level Language, which can deal drectiy with memory addresses, call, stacks and registers, ts benefitis that it's universally accessible and easy to learn, Ter TavoKe java opore. javactangereFlect.*; ‘lass invoke { Dubiie static void main( string () args ) ¢ try Gass ¢ Class.forvane( args(0) ); ‘cugetwethod( args[1), new class ful Object rét = m.invoke( nuT1, Systen.out .printinG ‘Thvoked static method: " + args (1) + of class: + args(o] F (mth, fa argslnkeaults: © + et): earch ¢ Classhorroundexeeption « ) f 77 Class. fornane() can't find the class } cacch'( NosuchMethodexception e2") { 77 that method doesn't exist 3 each ¢ TTlegataccessexception e3 >, { Z[ pe gon’t"Rave' permission to invoke that metho } Catch ( tnvocationtargetexception ef ) { 77-an exception ocurred while invoking that inethod ir ysesiethod chrew an: + e4. getTargetexception( ")"); Javaisa powerful language that's used in web pages, set-top boxes, TVs and 7 (why Python? Cll Python was created over twenty six years ago and has evolved to become an ideal beginner's language for learning how to program a ‘computer. I's perfect for the hobbyist, enthusiast, student, teacher ‘and those who simply need to create their own unique interaction between either themselves ora piece of external hardware and the computer itself Python is free to download, install and use and fs available for Linux, ‘windows, macOS, MS:DOS, 05/2, BeOS, IBM iseries machines, and ‘even RISCOS. Ichas been voted one of the tap Five programming languages inthe world and s continually evolving ahead of the hardware and Internet development curve. So to answer the question: why python’ Simply put, i's Free, easy to lear, exceptionally powerful, universally accepted, effective and a| superb learning and educational tool. BASIC was once the starter language thatearly ‘-bithome computer users learned. Python isa more modern take on BASIC, i's easy to learn and makes for an ideal beginner's programming language. nnn ay z= SayHello to Python ) Equipment You Will Need Sate are eaM nnd ietCur Uc Som il Uneaten sun ll ColoTa Manto an-ell Ng Le Re Reon \U UO e NR Mea Ate Ke iN ll] 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 to test your cade. You can use Windows (fram XP onward) on either a 32 ‘or 64-bit pracessor, an Apple Mac or Linux installed PC. |_| AN IDE AnIDE (Integrated Developer Environment) is used to enter and execute Python code. Itenables you to inspect your program code and the values within the code, 35, ‘wellas offering advanced features. There are many different IDEs available so find the one that works For you and givesthe best results. PYTHON SOFTWARE ‘macOS and Linux already come with Python preinstalled as part of the operating system, as does the Raspberry Pi, However, you need to ensure that you're running the latest version of Python, Windows users need to download and install Python, which well cover shortly TEXT EDITOR Whilst atext editor isan ideal erviconment.to enter code int, it'snot an absolute necessity, You can enter and execute code directly From the IDLE but a text editor, suchas Sublime Text or Notepad +, offers more advanced features and colour coding ‘when entering code. INTERNET ACCESS Python is an ever evolving environment and as such new versions often introduce new concepts or change existing commands and code structure to make it amore efficient language. Having access to the Internet will keep you up-to-date, help you ‘out when you get stuck and oive 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 at times and other times the cade wil flow ike water. Understand youte learning something entirely new, and you wil get there. BED oie: ( Equipment You Will Need cll THE RASPBERRY PI ‘Why use a Raspberry Pi? The Raspberry Piis a 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. Sa aaa ‘The Raspberry PiS isthe latest version, incorporating a more powerful CPU, more memory, WiFi and Bluetooth support. You can pick up ai 5 for around £59 or as part of akit depending on the Pi model you're interested in ala el ea ‘The FUZE's a learning environment built on the latest modet of the Raspberry Pi. You can purchase the workstations that ‘ome with an electronicskitand even a robat arm far you to build and program. You can find more information on the FUZE at www.fuze.co.uk We have several great coding tiles available vi worm. ‘elpublications.com. Our Pi books cover how to buy your First Raspberry i, set it up and RASPBIAN ‘The Raspberry Ps main operating system isa Debian-based Linux distribution that comes with everything you need in ‘simple to use package. It’s streamlined forthe Piand is an ideal platform for hardware and software projects, Python programming and even asa desktop computer. use it there are some great step-by-step project examples ‘and guides to get the most From the Raspberry Pitoo, vwpapniatonscon QTE z= Say Hello to Python) Getting to Know Python une ccol tc rescmuae| Cute kerr ete ro SUC MRR Men ee mee Reo LMM ale (Urol enlace] to understand. WHAT IS PROGRAMMING? Ithelps to understand what a programming language is before you try to learn one, and Python is no different. Let’s take a look at how Python came about and how it relates to other languages. PROGRAMMING RECIPES Programs are like recipes for computers. A recipe to bake a cake could go tke this: PYTHON ‘Aprogramming language isa listof instructions that a computer Follows. These instructions can be as simple as displaying your name or playing a music file, or ascomplex as building a ‘whole virtual world, Python isa programming language conceivedin the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (Cw in the Netherlands asa successor to the ABC language. Put 100 grams of selfralsing flour ina bowl ‘Add 100 grams of butter to the bowl, ‘Add 100 mililitres of milk ‘Bake forhalf an hour CODE Just tke a recipe, @ program consists of instructions that you follow inorder. A program that describes a cake might run tke this: bow = 0) flour = 100 [ butter - 50 Peet) milk = 100 Soak Span cteeue ts bon .append( [four butter ,milk]) B cake. cook(bol) Guido van Rossum, the father of Python. PROGRAM COMMANDS You might not understand some of the Python commands, like bowl append and cake.cook(bowl) The first i alist, the second an object; we'l look at bath inthis book. The main thing to know is that it’s easy to read commands in Python. Once you learn what the commands do, i's easy to Figure out how a program works. BED occ: ( Getting to Know Python Cl HIGH-LEVEL LANGUAGES ZEN OF PYTHON Computer languages that are easyto read are known as “high evel’. Python lets you access al the pawer of a computer ina language ‘Thisis because they fly high above the hardware (also referred to.as that humans can understand, Behind all thisis an ethos called "The “the metal’, Languages that fly clase tothe metal like Assembly, Zen of Python.” This sa collection of 20 software principles that ‘are known as low-level”. Low-level languages commands read abit influences the design of the language. Principles include “Beautiful like this msg db ,@xa len equ $ ~ msg, isbetter than ualy" and “simples better than complex" Type import: this into Python and wil dsplay al the principles. PYTHON 3 VS PYTHON 2 eno ee ee een cee coe eee rei Lanes WORLD OF PYTHON emergent) NATE RAD 122008 Python 3 ariv Peter neeet an etme Coenen ed ae Se aerate ne) eae = Cn tare eg eet ters Cote not compatible with Python 2 scripts, modules and tutorials, Whilst Peete ese ae Seen eg PCRS cae ana urn PYTHON2.X Je r asoriginally ERAWTNERD Python 3's arowing popularity err ea it'smow prudent to start learning to de quite large collection of modules, scripts, users, tutorial Stee hase out the previous vers andso on, Over the years Python 2 has Fast become one ofthe first : fn aceX and NASA use Pe ee oe eee De ee ne eet 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 Mea Modunetcet hia meMetan ulcers 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, i's an easy process to follow. Start by opening your web browser to www.python. ‘0ra/downloads/. Look for the button detain the Sit download link or Python 3.x (in our case thisis Python 3.6.2 but as ‘mentioned you may see later versions of 3) FEPTSPRD click the download button for version 3x, and save the fie to your Downloads folder. When the Fle is downloaded, double-ick the executable and the Python installation wizard wil launch, From here you have two choices stall Now and Customise Installation, We recammend opting For the Customise instalation lnk. a seme wef fume Install Python 3.6.2 (32-bit) BED ois ESTEEERD Choosing the customise option allows you to specify certain parameters, and whilst you may stay with the defaults, it’s a good habit to adopt as sometimes (not ‘with Python, thankfully) installers can include unwanted additional Features, On the fist screen available, ensure all boxes are ticked and click the Next button, Optional Features anc mace a @ ‘The next page of options include some interesting additions to Python. Ensure the Associate file with Python, Create Shortcuts, Add Python to Environment Variables, recompile Standard Library and install for All Users options are ticked. These make using Python later much easier. Click install when you're ready to continue. Advanced Options mtr ses (acm rot tn fp hy) awl [eihegen i ROE How to Set Up Python in Windows Cl FEED >>). Whilst its @ perfectly find the installed Python Prien 60 fine environment, it’s not too user friendly, so leave the command 3x within the Start button nee line For now. Enter: exT'EC) to leave and close the Comman Recently Added section. The Prompt window first ink, Python 3.6 (32-bit) wil launch the command ine version of Python when licked (more on that in a moment) To open the IDLE, ype IDLE into Windows start. pad I z= Say Hello to Python) How to Set Up Python on a Mac aera Ea CAME a ner n eT Mn alee NRA a version of Python is already installed. However, you should make sure you're running TAC) Cia obo 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. Open anew Terminal window by clicking Go» Clckon the lates version of Python 3% nout SIE Utilities, then double-click the Terminal icon. Now SHEDS ‘case this is the download button for Python 3.6.2. enter: python’ =-version. Youshould see Python 25.1" and This will automatically download the latest version of Python and even later, i Apple has updated the OS and Python instalation, ‘depending on how you've got your Mac configured, it automatically Either way, t's best to check forthe latest version starts the installation wizard PEPER) open safari and head over to www.python.org/ FETS withthe Python installation wizard open, cick on downloads, Just as with the Windows setup the Continue button to begin the installation. Its procedure on the previous pages, ou can see two yellow download worth taking a moment toread 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. DR Coa mad EEE 2628-20 BERTIER) The next section detals the Software License Agreement, and whilst not particularly interesting to most folks it's probably worth a read. When you're ready, clickon the Continue button once again. PEPER Final you're be presented with the amount of space Python will take up on your system and an Install button, which you need to click to start the actual installation (of Python 3.x on to your Mac. You may need to enter your password to authenticate the installation process. FEPTEM) The installation shouldn't take too long; the older ‘Mac Mini we used inthis section isa little slower than more modern Mac machines andit only took around thirty seconds For the Installation Successful prompt tobe displayed, How to Set Up Python on a Mac Cll ESTEE There's nothing much else eft to doin the Python Installation wizard so you can click the Close button. IF you now drop back into a Terminal session and re-enter the ‘command: python3 ==version, you can see the new version's, row listed, To enter the command ine version of Python, you need tocenter:python3. To ext, i's: exit. BRTESED You nced to search in Finder For the Python IDLE: when you've found it, clckltto 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. . Ppten 80 Se Pytnn 3.6.0 (9.6 8elaFPN6RelS, bee 22 236, 17:20-0) PEC 42 Cppte inc. ble 56) Cant 2] on daria ype Scorgiohty “crditet or *vconeeQ? for sore inforation. sien arin af Fee a) Ines yt tie FSTSET RD Older Macversions may have trouble with the newer versions of Python, in which case you will need to revert toa previous Python 3.x build; 2s long as you're using Python 3.x, the code in this book will work for you. Python 3.1.2 (r312;79360M, Mar 24 2010, 01:33:18) {6cc 4.071" (apple Ine. build 5493)} on’ darwin Type "copyright", “credits” or "1icense()" for mo Eelnronmition. wpepubleations com 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 deing something. Different distributions go about installing software in different ways, so we will stick to Linux Mint 18.1 for this particular tutorial BETTER Fist younced to ascertain which version of Python, iscurrently installed in your Linuxsystem; as we ‘mentioned, we're going to be using Linux Mint 18.1 for this section ‘Aswith macOS, drop intoa Terminal by pressing CtrlrAtleT, ‘avide@david-mint Fle Edt View Search Terminal Help FEGED Nextenter:python =-version into the Terminal screen. You should have the output relating to version 2.x of Python inthe display. Ours inthis particular case is Python 2.7.12 davidedavid-mint Fle Edit View Search Terminal Help erst yon & Co Coding Some Linux distros il automatically update SHEPS the installation of Python to the latest versions: whenever the system = updated. To check rst dos system update Sed upgrade it sudo apt-get update && sudo apt-get upgrade Enter your password and let the system do any updates. FEED (ce the update and upgrade is complete, you ‘may need to answer'Y’ to authorise ary upgrades, center: python3. --version to see if Python 3xis updated or even installed, nthe case of Linux Mint, the version we have is Python, 3.52, whichis Fine For our purposes. FETE EDD Howeves iF you want the latest version 3.6.2 as per the Python website atthe time of writing, youneed to build Python from source. Star by entering these commands into the Terminal: sudo apt-get install build-essential checkinstall sudo apt-get install Libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev Libgdbn-dev Libc6-dev Libbz2-dev Open upyour Linux web browse ardgoto SIERO the Python download page: www.python.org/_ downloads Click onthe Download Python 3.62 (or whichever version 'on vhen au oot dwnicadthe source Python Seataocfle @ python Inthe Teminl, go the Downloads older by oud entering: cd Downloads/. Then unzip the contersofthe downloaded Python sourcecode with ta VF Python-3.6.2.tar.xz. Now enter the newiy unzipped Folder with ed Python-3.6.2/. FETED) within the python folder, enter: configure sudo make altinstall ‘This could alittle while depending on the speed of your computer. Once Finished, enter:python3.6 ==version to check the installed latest version For the GUIIDLE, you need to enter the Following Bed ‘command into the Terminal sudo apt-get install idle3 The IDLE can then be started with the command: idLe3. Note, that IDLE runs a different version fram the one you installed from source, FSTSET RD) You also need PiP(Pipinstalls Packages) whichis a tool to help you install more modules and extras. Enter: sudo apt-get install python3-pip PIP 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 distro's menu. vo ism ( How to Set Up Python in Linux Cll Getting Started _ vViuan oa uatoln ies 9 ( Getting Started with Python 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. Intthis 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 forthe First Time Your First Code Saving and Executing Your Code Executing Code from the Command Line Numbers and Expressions Using Comments Working with Variables User Input c “Condit Python Modules wor pelpubliationscom z= Getting Started with Pytho +) Starting Python For the First Time Merrie ol trl ee ie ey Dre MCI Cem ean aac ocak cancel CMe eM Cre raced Toc lea 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 con that subject. However, once you're ready, fire up your Pi and get ready for coding. FETTER) With the Raspbian desktop loaded, click onthe ESTESED for cxample, inthe Shell enter: 242 ‘Menu button followed by Programming > Python After pressing Enter, the next line displays the [3 (DLE). This opens the Python 3 Shell. Windows and Macusers can answer: 4. Basically Python has taken the ‘code’ and produced the Find the Python 3 IDLE Shell from within the windows Start button relevant output. ‘meni and via Finder. PEPTIPD) The shellis where you can enter cade andsee the [EBB the python shel acts very much ike a calculator, responses and output of code you've programmed since code i basically a series of mathematical into Python. This sa kind of sandbox, where you're able totry out interactions withthe system. Integers, which are the infinite some simple code and processes. sequence of whole numbers can easily be added, subtracted, multiplied and so on. HEED esc While that’s very interesting, i’ not particularly exciting. Instead, try this: print(“Hello everyone!”) ust lke the code we enteredin Sublime in the Installing a Text Editor section ofthis book self-explanatory prints things, Python 3 requires the brackets as well as quote marks in order to output content to the screen, inthis casetthe ‘Hello everyone! bit. >>> print("Hello everyone!) pelo everyone! Bare You may have noticed the colour coding within the Python IDLE. The colours represent different elements of Python code, They ae: Black - Data and Variables Green—Strings Purple Functions Orange Commands Blue — User Functions Dark Red ~ Comments Light Red -Error Messages, IDLE Colour Coding [eoteur [“setor [examples | Daekred | Commas | taneaber VAR FETED The Python OLE isa configurable environment. iF you don't ike the way the colours are represented, then you can always change them via Options > Configure IDLE and licking on the Highlighting tab. However, we don’t recommend that, as you won't be seeing the same as our screenshots. Ea etme I FEED ust tke most programs available, regardless of the ‘operating system, there are numerous shortcut keys avallable. We don’t have room for them all here but within the Options > Configure IDLE and under the Keys tab, you can see alist (of the current bindings. PETISETR The Puthon IDLE is apower interface and one that's actually been written in Python using one ‘of the avallable GUI toolkts. Fyou want to know the many ins and ‘outs ofthe Shel, we recommend you take afew moments to view ‘www.docs.python.org/3/library/idle.html, wich details many oF the IDLE’ Features woowecoubicaionscon CERT Starting Python for the First Time ¢ CG => Getting Started with Python Your First Code Essentially, you've already written your First piece of code with the ‘print("Hello everyone!”)' function from the previous tutorial. However, let’s expand that and look at Penh tig en CEM eum eran ccc 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. STEERED you've closed Python 3 IDLE, reopen itin whichever operating system version you prefer. In the Shell enter the Familiar following print(*Hello”) ee aw“ me tn FERED sos v ening dovratoxpensinte BED 2osccteoe, EE print (“212”) Sophie Mra a cms tr mre toma FSTSRE DD You cansee that instead of the number 4, the ‘outputs the 2+2 you asked to be printed tothe screen. The quotation marks are defining what's being outputted tothe IDLE Shell to print the total of 2+2 you need to remove the quotes: print(2+2) You can continue as such, printing 2+2, 46442343 and soon ta the Shell. An easier way sto use a variable, which s something we wil cover in more depth later. For now, enter: (our First Code ¢ CG hat youhave done here isasin the letters SNPS and b two values: 2 and 2. These are now variables, which can be called upon by Python to output, add, subtract, divide and son for slong 9 the tumbers stay the same Ty ts print(a) print(b) TEED te output ofthe las step displays the current values ofboth aand b indvidvally as you've asked them tobe printed separately. IF you want to add them up, you can Use the following: printCasb) ‘This code simply takes the values of aand b, adds them together and outputs the result oe ba she bt aon ee Bere AD You can play around with different kinds of variables and the Print Function. For example, you could ‘assign variables for someone's name: nane="David” print(name) FETED) ow let'sadda surname: surnane="Hayward” print(surname) ‘You now have two variables containing a frst name anda surname ‘and you can print them independently, ie beh tug ons undo te BETTER we were to apply the same routine as before, Using the + symbol, the name wouldnt appear New File, This will open a new window Inthe IDLE Editorasitisin the Shel, enabling you \with Untitied as its name. Thisis the Python IDLE Ealtor 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, FTE Te IDLE Editors, forall intents and purposes, a FSTeeE DD ick on the OK button in the Save box and select a simple text editor with Python features, colour destination where you't save all your Python code. coding and so on; much in the same vein as Sublime. You enter ‘The destination can be a dedicated Folder called Python or you code as you would within the Shell so taking an example from the 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!") C Saving and Executing Your Code Cll Enter a name for your code, ‘print hello’ for ‘example, and clickon the Save button. Once the Python code is savedit's executed and the output willbe detailed in the IDLE Shell in this case, the words Hello everyone! PEPER Thisishow the vast majority of your Python code willbe conducted, Enter itinto the Editor, hit 5, save the code and look atthe output inthe Shell Sometimes things will fer, depending on whether you've requested a separate window, but essentially that’s the process.’ the process we will Use throughout this book, unless otherwise stated ue ta Oe) Btep re do He IF you open the file location ofthe saved Python code, you can see that it ends in a py extension. Thisis the default Python file name. Any code you create will be whateverpy and any code downloaded from the many Internet Python resource sites willbe. Just ensure that the code is written For Python 3 Lets extend the code and entra few examples S18 from the previous tutorial: a2 b=2 ‘name="David” surnane="Haynard” print(nane,,surnane) print (asb) IF you press FS now youll be asked to save the fe, again, as t’sbeen modified fram before. FETED you click the OK button, the filewill be ‘overwritten with the new code entries, and ‘executed, withthe output in the Shell k’snot a problem with just these few lines but if you were to edt a larger file, overwriting can become an issue. Instead, use File > Save As from within the Editor tocreatea backup, BETTER ow create anew file. Close the Editor, and open ‘a new instance (File > New Fle from the She). Enter the Following and save itashellopy: ‘a"Python” boris” "cool!" print(a, b, ©) ‘You wil use this code inthe next tutorial sn 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. ED Python, in Linux, comes with ‘executing code via the command line. One of the with Python 2, whist the other uses the Python 3 libraries ‘on. First though, drop into the command line or Terminal on operating system, PETE fom here you're able to enter th looked at prev a-2 printCa) ‘You can see that it works exactly the same. and ma get access 10 their command line by clicking Go> Utities > Terminal yon & Co Coding Executing Code from the Command Line Cl Now enter: exit to leave the command line Python session and return you back tothe command prompt. Enter the folder where you saved the code from the previous tutorial and list the available Files within; hopefully you should see the helo.py ile FPP The result of running Python 3 cade fromthe Python 2 command tine is quite obvious. Whitt joesn't error out in any way, due tothe differences between the way Python 3 handles the Print command over Python 2, the result isn't as we expected, Using Sublime forthe moment, open the hellopy file, From within the same folder asthe code you're a="Python” 4 c="cool!” print(a, b, <) fe we created, which to remind youl: python hello.py Since Sublime Text isn't available For the Raspberry Pi you're going to temporarily leave the Pi for the moment and use Sublime as an example that you don't necessarily need to use the Python IDLE. With the hello. file open alter itto include the following: nane=input(“What is your name? “) print(*Hello,”, name) code with Save the hellopy file and drop back tothe commandline. Now execute the newly saved python3 hello.py ne result willbe the original Python is cool! statement, toge with the added input command asking you For your name, and displaying tin the commat ——— z= Getting Started with Python Numbers and Expressions AVA Co) naa ortega 1 o(e=1 Rodeo aN MOLALLA) cae-Le Lele CO DE LAT AE like. Let's expand on that now and see just how powerful Python is asa calculator. You eV L AT aaNet PRI Colm Mena el Kolm NT en MUM OU Ce 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. STEERED 022 ue the GUI version of Python 3, asmentioned JESTESIEMM You can use all the usual mathematical operations: ‘you can use either the Shel or the Editor. For the divide, multiply, brackets and so on, Practise with a time being, you're going to use the Shelljustto warm our maths ew, For example: ‘muscle, which we believe isa small gland located at the back ofthe ve brain or not) 62 24283 G2)" PEPER the Shell enter the following: PEPI You've no doubt noticed, division produces a decimal number. In Python these are called oats, = ‘or floating point arithmetic. However, Fyou need an integer as 54396+34553245 99867344*27344484221 ‘opposedito adecimal answer, then you can use a double lash: Yu can see that Python can handle some quite large numbers. = ‘And soon, ED rene c+ cong ‘You can also use an operation to see the remainder lefeover Fram division, For example: 10/3 ‘will display 3.333333333, which is of course 3.3-ecurting Ifyou nowenter: 103, ‘This ill display 1, which i the remainder let over From dividing 10 into 3, FETED 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 3 double multiplication symbol or double-star on the keyboard: a3. 1010 Essentially, is 2x2x2 but we're sure you already know the basics bbehind maths operators. This show you would workit outin Python, C Numbers and Expressions Cl Thiswill be displayed as 0b11, converting the integer into binary and adding the prefix Ob tothe Front. Fyou want to remove the 0b prefix, then you can use: format(3, ‘b") ‘The Format command converts a value, the number 3,t0a Formatted representation as controlled by the Format specification, the part. ESTEEM) 4 800!ean Expression isa logical statement that wil either be true or False, We can use these to compare data and test to see fit's equalt, less than or greater than. Try this ina NewFile: a-=6 b-7 print(1, a == 6) print(2, a == 7) print@, 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(s, not Ca print(a, not a Numbers and expressions don't stop there. Python has nurnerous builtin Functions to work out sets (of numbers, absolute values, complex numbers and a host of ‘mathematical expressions and Pythagorean tongue-buisters. For ‘example, to convert a number to binary, use: bina) FSTISETR) Execute the code fram Step 9, nd you can see a series of True or False statements, depending on the result of the two defining values: 6 and 7. t's an extension of ‘what you've looked at, and an important part of programming. woncnn CS z= Getting Started with Python Using Comments When writing your code, the Flow of it, what each variable does, how the overall Pen err erate tar Uae reece 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. Ifa variable is used, the ‘programmer comments on what it’s supposed to do, for example. I's just good practise. PR ry ceatng orewirstonce of the OLE tor Rene the code nd eats Roun see tare (Fes Nel) nd create ple noble and cutnutinthe OLE Shel sstlthesome oboe, print command: despite the extra lines being added. Simply put, the hash symbol (#) es tiertean act atin plagencertae ratty et — sno others what's gongonwihout the wet beng ovare Save the file and execute the code. i yen 42 Set * fe go st bag ns reer Carmey) param MERE lame reece ee we oat (ie Ea Fame in tnt Wom te ft ESTEE Punning the code willreturn the ine: The value of A [ENEESIAMM Let's assume that the variable that we've created is, 10intothe IDLE Shell window, which is what we Is the number of lives ina game. Every time the expected. Now, add some of the types of comments you'd normally player dis, the value is decreased by 1. The programmer could seewithin code: insert aroutine along the lines of # Set the start value of A to 10 ana-1 10 print(*You've just lost a life!”) # Print the current value of A print(*You now have", a, “Lives left!" print(“The value of A is,”, a) v (. Using C it Cl (Using Comments Whilst we know thatthe variable is lves, and thatthe player has just 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 are Essentially, the new code together with comments STEP could look tke: # Set the start value of A to 10 10 # Print the current value of A print(“The value of A is,”, a) # Player lost a life! na-1 4 Inform player, and display current value of A lives) print(*You’ve just lost a life!”) print(*You now have”, a, “Lives left!) Inline comments are comments that follow a section BALD code Toke or evarpestrom above, sted of inserting the code ona 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-1 # Player lost a life! print¢“You’ve just lost a life!”) print("You now have”, a, “Lives left!”) # Inform player, and display current value of A (lives) FETTER) The comment, the hash symbol, can also be usedto comment out sections of code you don't want to be ‘executed in your program. For instance if you wanted to remove the fist print statement, you would use: # print(“The value of A is,”, a) Leer anaes % Set the start value of A to 10 j] # Print the current value of A }# peintc"The valve of A'is.", ay Blayer lost’ life! os} Toform player. and display current value of A (lives) prine(-You've just lost life!" Print(-You non have", a, “lives left!=) You can use commentsin different ways, For ‘example, Black Comments are a large section of text that details what's going on in the code, such as telling the code reader what variables you're planning on using: W 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. You also use three single quotes to comment. ‘out a Block Comment or multiline section of ‘comments. Place ther before and after the areas you want to ‘comment for them ta work: This is the best game ever, and has been developed by a crack squad of Python experts who haven’ t slept or washed in weeks. Despite being very smelly, the code at least works really well. z= Getting Started with Python Working with Variables Wet eas cu tom eur Crane svete neor elect g ta ee romantic enhance eae ese itecaei} RUTTEN CUT oe VARIOUS VARIABLES You'll be working with the Python 3 IDLE Shell in this tutorial. IF you haven't already, open Python 3 or close down the pr IDLE Shell to clear up any old code. In some programming languages you're required BAD 0:0» cota sgntocenotea stn, whichisa variable made up of multiple characters, uch asa name ofa person. InPython this isnt necessary, For example, in the Shell enter: nane="David Hayward’ (or use your own name, unless you're also called David Hayward). PEPTSPR) You can check the type of variable in use by issuing the type ()cornmand, placing the name of the variable inside the brackets. n our example, this would be: type name). Add anew string variable: title="Descended rom Vikings”. TERED Youve seen previousy that variables can be concatenated using the plus symbol between the variable names. nour example we can use: print. (name + “: + title). The middle part between the quotations allows sto ‘add colon and a space as variables ae connected without spaces, so weneed to add them manually. [Be ES) nn Stn ro PIR Youcanaiso combine variables within another variable. For ‘example, to combine both name and title variables into anew variable we use: charactersname +“: + title ‘Then output the content of the new variable as: print (character) Numbers are stored as different variables: age=44 Type (age) Which, as we know, are integers. C Working with Variables cl BEER Howeves, you can’t combine both strings and integer type variables inthe sare command, as You would a set of similar variables. You need to either turn one into the ‘other or vce versa. When you do try to combine both, youget an error message: print (name + age) Thispresets bit oF roblem when wan to S1a78 work with a number that's been inputted by the use a5 age 10 wont work due to beng astrng variable and an integer instead, you need enter int(age) + 10 ‘This ill TypeCast the age string into an integer that can be ‘worked with. BETTER Thisis2 process known as TypeCasting. The Python codes: print (character + “is “ + str(age) + “ years old.) or you can use: print (character, “is, age, “years old.”) ‘Notice again that inthe last example, you dont need the spaces between the words in quotes as the commas treat each argument to print separately >>> print (nane + age) ‘Traceback (most recent call last): File “", Line 1, in module> rine’ (nave * age) Typetrror: Can't convert "int* object to str implicitly BiBSprine (character +" is'= + str(age) *\" years old." David Hayward: Descended fron Vikings iz “4 years old. S3S'prane (character, "ts", age, "years old.) David Haynard: Descended from Vikings is 44 years old. 2 FETT The use of Typecastingis also important when dealing with floating point arithmetic; remember: numbers that have a decimal point in them. For example, enter: shirt=19.99 Now enter type(shirt) and you'llsee that Python has allocated the number as a oat’, because the value contains a decimal point. le Eat shel Qeboa Sptons windows ep Python 5-47 Coefault, Get TB 204e, 13:31 T1) ree ta oe or ieee _ Serta FETEGEAD *rother example of TypeCasting s when you ask For ingut from the user, such as a name. for example, enter ‘age= input (“How old are you? *) All data stored from the Input command isstored asa string variable. Ble Est Shek Debug optons windows iy Tea ‘when combining integers and floats Python usually converts the integer toa float, but should the reverse ever be appliedit's worth remembering that Python doesn't return the exact value, When converting a oat to an integer, Python will always round down to the nearest integer, ‘called truncating; in our case instead of 19.99 t becomes 19, le Eat shel ebug tions windows lp Python 3-42 (afoul, Oot 1 BONe, TBST (eet 3:4) on tans Fes Scpyighes Seretia> or “Licensed for mare infomation. cian float’? 3 oncom z= Getting Started with Python User Input WASTE Co ar ciel ae TeneMRUaea Keele ice Ame nec (ood earlier, so now would be a good time to Focus solely on how you would get information Pesan cere aetna USER FRIENDLY The type of input you want From the user will depend greatly on the type of program you're coding. For example, @ game may ‘ask for a character's name, whereas a database can ask For personal details. IFits notalready, open the Python 3 IDLE Shel, "Now that we have the user's name stored in a LD seit aicwtieinthe eater vetsbesin with al couple oF variables we an call them up whenever something really simple, enter: wewant: print(*Hello") printCWelcone”, firstname, surname, “. I hope firstname=inputC‘what is your first mane? “) you're well. today.) print(“Thanks.") surnane=input(“And what is your surname? “) FETED Sve and execute the code, and as you alreadyno ESE Run the code and you can see a sight issue, the doubt suspected, in the IDLE Shel the program will full stop after the surname follows a blank space. ask for your first name, storing its the variable Firstname, followed To eliminate that we can add a plus sign instead of the comma in by your surname; also stored in its own variable (surname). the code: printC‘Welcone”, firstname, surnames‘. I hope you’re well today.”) (User input Cll iG P| ‘You don't always have to include quoted text within Sus the input command. For example, you can ask the user their name, and have the input inthe line below: print(“Hello. What’s your name?”) name=inputQ userinput py - home/pi/Documents/Python Code/us| [Ele Edt Farmat Bun Options wondows Help iprant( Welle. What's your nane?™) F name=inpt() What youve create hres codon, which we SHEE) ‘will cover soon. In short, we're using the input From theuser and mesuingit against condition So the vser eters Davids thet name, the guard wil alow them to pass unhindered Ete they enter name other than Dai, the guard chalenges themto afight ESTEE The code from the previous step is often regarded asbeing alittle neater than having a lengthy ‘amount of text in the input command, butt’s not arule that's set in stone, so do as you like in these situations. Expanding on the code, tay this print(*Halt! Who goes there?”) rnane=input) Just as you learned previously, any input from a User is automatically string, so you need to apply 2 STEP 9 “TypeCastin order to turit into something ese. Thiscreates some interesting adctions tothe input command. For example: # Code to calculate rate and distance print(“Input a rate and a distance”) rate = floatCinput(*Rate: “)) ES TeGE AD 52 900d start to atext adventure game, perhaps? Now you can expand on t and use the raw input from the user to flesh out the game alittle: ‘if name=="David”: print(*Welcome, good sir. You may pass.") else: print(*I know you not. Prepare for battle! PTD) 1o finalise the rate and distance code, we can ade: distance = float Cinput(“Distance: “)) printCTime:”, (distance / rate)) Save and execute the code and enter some numbers. Using the Float(input element, we've told Python that anything enteredisa floating point number rather than a string cnn z= Getting Started with Python Creating Functions ANC e aT Cel R CME Eee rey MU LS RoR NT] ONCE Ne MSM aoe em a cet Col eLeh dC CiMten (oe UAL MUS RLM edo eA Seco Te ol a esTe0A) enables you to define your own Functions. FUNKY FUNCTIONS ‘A function isa command that you enter into Python to do something. It's alittle piece of self-contained code that takes data, works on it and then returns the result. ESTEE '¢snot just data that a function works on. They can do all manner of useful things in Python, such as sort data change items From one format to another and checkthe length or type ofitems. Basically, a function isa short word that’s Followed by brackets, For example, len(, list) or type(), ‘Afunction takes data, usually variable, works on itdepending on what the Function is proorammed to do andreturnsthe end value. The data being worked on goes Inside the brackets, so if you wanted to know how many letters are in the word antidisestablishmentarianism, then you'd enter: Len¢“antidisestablishmentarianisn’) and the number 28, would return, Fae eGE RD You can pass variables through functions in much the same manner. Let's assume you want the number of letters in person's surname, you could use the following ‘code (enter the text editor for this example): hname=input “Enter your surname: “) count=Len(nane) print (*Your surname has“, count, “Letters in it.”) Press FS and save the code to execute it. Python has tens of functions bul nt i, Fartoo ‘mary to get inti the limited space availabe here, However, o view the list of builtin functions available to Python 3, navigate to wwww.docs.python.org/3/library/Functions.htm, These arethe predefined functions but since users have created many more, theyrenot the only anes available. (Creating Functions cl Additional functions can be added to Python through modules. Python has vast range of ‘modules availabe that can cover numerous programming duties, ‘They ad 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. Tose funcionfrom a module ete the name of Sua76 the module followed by a full stop, then the name (of the Function. For instance, using the math module since you've just imported it nto Python, you cn utilise the square root Function, To.doso, enter math. sqrt(16) ‘You can see thatthe code is presented as module Function( data. FORGING FUNCTIONS There are many different functions you can import created by other Python programmers and you will undoubtedly come eee cee es Sete tees Rte eae Teen e eee tect eee aca create a function Cer ater teen eee nee naa tee eee Beene Seen) eae roc ena weit rien Peet STEP 3 the last line in th Areata eames Cena ae ere er rete cee, Breet New Be a cd eT ear tls modul Rant ar ie Sete eats emer: es oad idet addCa, b):] voowpchubicaionscon CRITE z= Getting Started with Python Conditions and Loops Conditions and loops are what makes a program interesting; they can be simple or elem eas OWA UMM en Tu Ke olin elk CeN RNA An cele nn ee} 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 ifitisn't. Let's create a new Python program that will ask EB 01 you can use anf statement to checkifthe AMD te csestoinputa ord.thenchecictosee F's aM sor tenath vale is equa to four and pene afourletter word or not. Startwith File > NewFile,andbegin with friendly conformation iit applies tothe rue: the input variable: a eo word=input(“PLease enter a four-letter word: “) word=input(“Please enter a four-letter word: “) _ word_Lengthelen(word if word_length == 4: print (word, “is a four-letter word. Wel done. ‘The double equal sig (==) means checkif something sequal to something else. Now we can create anew variable, then use the len ‘The colon atthe end of IF tells Python that i this Function and pass the word variable through it to statement i true do everything after the colon {get the total number of letters the user has just entered: that's indented. Next, move the cursor back to the beginning of the Editor, word-input(“Please enter a four-letter word: 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 re er er et 7 else: print (word, “is not a four-letter word.) Press FS and save the code to excite Enter SDS a four-letter word in the Shell to begin with, you should havethe returned message thatthe words four eters Now pes apan and rerun te rogram baths tne enter fetter word The Sell play tats nota fueltter word LOOPS (conitinsndioos CE Now expand the code to include another conditions. SUS Eventually, it could become quite complex. We've ‘added a condition for three letter words 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.”) elif word_length == 3: print (word, “is a three-letter word. Try again.”) else print (word, “is not a four-letter word.”) ‘Alo0p looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same Deter ag me ee nse ears step 1 i for x= 1) While x < 10%) print GO] act, aia etc eee eae Cg eros Pe er aren eee ete eee ieee tet ta Petr renee ae rmsd at variabl aes eee t eet ers: for_word in_words print (word)] pee te eo example by using the range Fun for xin range C1, 10):) print Go) eee Sere eee ere eee ett? Getting Started with Python Python Modules MASTERING MODULES Think of modules as an extension that's imported into your Python code to enhance and extend its capabilities. There are countless modules available and as we've seen, you can even make your own, Ea Although god, the builtin functions within Python ace limited. The use of modules, however, allows us ‘0 make more sophisticated programs. As you are aware, modules Some rode especally on the Raspbery sue are included by default, the math module being a brie example. Sadly, other modules aretalvaysavalabe. good trample onnor platforms the pygamem many Functions to le, which contains pon & Co Coding FEPIED The resuttis an errorin the DLE Shell asthe game module isn't recognised or installed in Python. To install a module we can use PIP (Pip Installs Packages) Close down the IDLE Shell an drop into a command prompt or Terminal session, At an elevated admin command prompt, enter: pip install pygane FETIP the PP installation requresan elevated status duet installing components at different locations. Windows users can search for CMD via the Start button a the result then click Run as Administrator. Linux a (Qrronodues Ca (Python Modules Close the command prompt or Terminal and relaunch the IDLE Shell when you now enter: ‘import pygame, the module will be imported into the code without any problems. Youll find that most code downloaded or copied from the internet will contain a module, mainstream of nigue, these are usually the source of errorsin execution due to them being missing. ry ‘Multiple modules can be imported within your code. S18 To extend our example, use: import random ‘import math for I in range(s): print(random.randint(1, 25)) print nath.pi) “The modules contain the extra code needed to achieve a certain result within your own code, as we've previously experimented with, For example: ‘import random Siar Brings in the cade From the random number generator module. You can then use this module to create something like: for i in range(10): printCrandom.randint(1, 25)) & PEED The resuttisastring of random numbers Followed bythe value of Pi as pulled from the math module using the print(math.pi Function, You can also pullin certain Functions from a module by using the From and import commands, such as: from random import randint for i in range(S): print(randint(1, 25)) a 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 a great or lesser range. For example: import random for i in range(25): printCrandom.randint(1, 100)) ‘This helps create a more streamlined approach to STEP 10 programming. You can also use import modules, ‘which wil import 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 tel others what's going on, tenn Citentttoanetentdtinteg DA - ax pte rE mules 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 lis 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 DateandTime 58 Opening Files 60 Writingto Files 62 _ Exceptions 64 Python Graphics eee eons teehee aU Ceo eter} Python. A list is simply a collection of items, or data if you prefer, that can be accessed as a whole, or individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include Functions in ists, and lists within lists. FSTEEEDD Alistise sequence of data values called items. You eate the name of your list followed by an equals sign then square brackets and the items separated by commas; note that strings use quotes: nunbers = [1, 4, 7, 21, 98, 156] mythical_creatures — [“Unicorn”, “Balrog”, “Vanpire®, “Dragon”, “Minotaur"] One youve dined our youcanca.ech te bby referencing its name, Followed by a number. Lists start the first item entry as 0, Followed by 1, 2,3 and so on, For example: unbers Tocallup the entire contents ofthe lst nunbers[3]) To cll the third From zera itemin the lst (21 in this case). You can also access, or index, the lastitem inalistby Using the minus sign before the item number [-], ‘or the second to last item with [2] and Soon. Trying to reference an iter that isn't in the list, such as [10} wil return an exror: unbers [1] mythical_creatures[=4] ESTEE DD Sting issimitar to indexing but you can retrieve ‘multiple tems in a lst by separating item numbers with a colon. For example: unbers[1:3] vill output the 4 and 7, being tem numbers 1 and 2. Note that the returned values don'tinclude the second index pasiton (as you ‘would numbers[t:3] to retum 4,7 and 21), ‘ou cn update Res within anexsting Ut, remove Su items and even join lists together. For example, to Join two lists you can use: everything = nunbers + mythical_creatures. ‘Then view the combined list with: everything Items can be added to alist by entering: nunbers=nunbers+[201] Or for strings: nythical_creatres-nythical_creatures+[“Griffin"] (Or by using the append Function mythical_creatures.append(“Nessie”) rnunber's .append(278) Removal of tems can be done in two ways. The First Gis Isby the tem number: del nunbers[7] Altematively, by item name: mythical_creatures. renoveC“Nessie”) Youcanview what canbe dane wth sts by entering Sues dir(list) into the Shell. The output is the available functions, for exemple, insert and pop are used to add and remove items at certain positions To insert the number 62 at item index 4 numbers.insert(4, 62) Toremoveit runbers.popC4) Sed ito its components. For example: List(“David”) Breaks the name David into toanewlist You also use the list function to break a string down Thiscan then be passed ane=1ist*David Hayward”) rane age=[44) User = nane + age user Based on that, you can create a program to store STEP 10 someone's name and age as alist: hane=inputCWhat”s your nae? “) ‘name=List(name) ‘age=intCinput (“How old are you: “)) ‘Lage-[age] user = Inane + lage ‘The combined name and age lists called user, which canbe called by entering user into the Shel. Experiment and see what you can do, Tuples are very much identical to lists. However, where lists can be updated, deleted or changed in some way, a tuple remains a constant. This is called immutable and they're Paced UNMET e THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the program special but they/re also used for example, in an adventure game, PEED tucieis created the sameway asalistbutin this, instance you use curved brackets instead of square brackets. For example: months=("January”, “February”, “March”, “April”, “May”, “June”) months intended to do. Normally, a tuple is reserved For something where non-playing character names are stored. BIREDD Vou con create grouped tuplesinto ists that contain multiple sets of data Forinstance, here's @ tuple ‘called NPC (Non Playable Characters) containing the character name {and their combat rating for an adventure game: NPC=[C*Conan™, 100), (“Belit”, 80), (“Valeria”, 95)) acts Miccarns irae: e er, Just as wth ists, the tems within a named tuple can be indexed according to their position inthe data range, Le. months[0] months[5] However, any attempt at deleting or adding tothe tuple wil result inan errarin the Shell, Each ofthese data Items can be accessed asa whole by entering NPCinto the Shell or they can be Bcd indexed according to their position NPC[0, You can also index the individual tuples within the NPC lst: ‘NPC(O} (1) will spay 100. isworhrcingttwbenfeereng mute ETERS now racket roo Su tuples within a list, the indexing is slightly different. Sue corresponding variables: from thenarm. Yu would expect te 95 combat rating ofthe character Valeria to be NPC[4][5], but it's not. It’s actually: Comer PeEnatGDEHES Necte]et] ‘You can now check the values by entering name and combat. rating, FETED Remember, as with sts, you can also index tuples Using negative numbers which count backwards From the end of the data list. For our example, using the tuple with multiple data tems, you would reference the Valeria character with: NeczI[-0 Which a you can apie, getsa te confusing when you've gota lotof tuple data to deal wth eee aaa FSTeGEAD Testes though utilise a feature called unpacking, Be eREO You con use the max and min functions tofind the ‘where the data items stored within a tuple are highest and lowest values ofa tuple composed of assigned variables First create the tuple with twoitems(nameand numbers. For example: combat rating} hunbers=(10.3, 23, 45.2, 109.3, 6.1, 56.7, 99) Meco ‘The numbers can be integers and floats. To output the highest and lowest, use: print (naxCnunbers)) Pe Ta TE TTT print(win¢nunbers)) Terre e eet neu Ee NAC auertete ie A ry of dealing with data items. They can be tricky to get to grips with at First but you'll soon Perce aculcntmetancr KEY PAIRS. alist 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. STEERED [c's sevyouwant tocreatea phonebookin Python. [ESTEEM As with lists and tuples, you can check the contents ‘You would create the dictionary name and enter ‘ofa dictionary by giving the dictionary a name: the data in curly brackets, separating the key and value by a colon phonebook, in this example, This will display the data items you've Key:Value. For example: entered ina similar Fashion toa list, which you're no doubt Familiar phonebook={“Enma”: 1234, “Daniel”: 3456, “Hannah”: Wh by now. 6789} oe PETER estas ith most ists, tuples and so on, strings FEED The benefit of using a dictionary s that you need be enclosed in quotes (single or double), canenter the key to index the value. Using the \whilst integers can be left open. Remember thatthe value canbe _phonebook example from the previous steps, you can enter: eithera string or aninceger youjustneedto enclose therelevant — onebook[ “Ema ieee phonebook[“Hannah”] phonebook2={“David": “0987 654 321”} ‘Adding toa dictionary esto. Youcan include SS anew data item entry by adding the new key and vale ems the phonebook[“David"] = “0987 654 321” phonebook Nest, you need to define the wsernputs and S1a78 variables: one for the person's name, the other for their phone number (let's keep it simple to avoid lengthy. Python code ane=inputC“Enter name: hunber=intCinputC“Enter phone nunber: “)) STEP 6 key; the value willbe removed as wel since both work 3s a pair of data items: You can also remove items From a dictionary by Issuing the del command Followed by the item's el phonebook[*David"] STEI "Note we've kept the number asan integer instead (ofa string, even though the value can be both ~aninteger ora string, Now you need to add the user's inputted variables to the newly created blank dictionary. Using the same process asin Step 5, you can enter: phonebook{nane] = nunber seated Taking this astep further, how about creating a piece of code that will ask the user forthe dictionary key and value items? Create a new Ecitor instance and star by coding in anew, blank dictionary: phonebook={} fuse — Now when you save and execute the code, Python will ask For a name and a number. fe will then insert those entriesinto the phonebook dictionary, which you can test by entering nto the Shel phonebook phonebook[“David”] IF the number needs to contain spaces you need to make ita string, sso remove the int part ofthe input. z= Working with Data Splitting and Joining Strings MT Ke Uae Me eM aM eam orl AMER eT eR R NT Uae ole 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 to strings. STEERED The main toolin the string Function arsenatis split. [ESTESEMD Note thatthe text spit part has the brackets, With you're able to spit aparta string of data, uotes, then a space followed by closing quotes based on the argument within the brackets. For example, here's and brackets. The space isthe separator, indicating that each lst string with three ems, each separated by a space: item entryis separated by a space. Likewise, CSV (Comma Separated a Value) content has a comma, so you'd use: ‘text~"January, February,March, April May, June” months=text. split(*,”) PEPER) ow let’ turn the string into a list and splicthe TEE Youve previously seen how you can splita string content accordingly: Into individual etters asa list, using aname: nanes=text -split(* *) ame=List(“David") ‘Then enter the name of the new ist; names, tosee the three tems, "ame ‘The returned value is‘D'a,'V, 7, Whilst t may seem atte useless under ordinary cumstances, t could be handy for creating spelling game for example, ( soliting and Joining Strings Cl Thesnpostestie seth jon uiee ERT sewihie tinction hesepratr dont ala you will have separate items in a string and can join S1a78 ‘have to bea space, it can also be acomma, a full ‘them all together to form a word or just a combination of items, ‘stop, a hyphen or whatever you like: depending on the program you're writing, Forinstance alphabet=".join([“a","b","c","4","e"]) alphabet ‘This ill display ‘abcde in the Shell. “Red”, “Green”, “Blue”] "," join(colours) FETED You can therefore apply join to the separatedname [EMINEM There's some interesting Functions you apply toa ‘you made in Step 4, combining the letters again to string, such as.capitaize and tle, For example: ce titlee"conan the cinmerian” nnane=". join(nane) title. capitalize() name title title, ‘we've joined the string back together, and retained thelist called ‘name, passing through the Join Function, Pe Ea a TT FETISEAD 000d example of using the join functioniswhen REBAR You can also use logic operators on strings, {you have alist of words you want to combine into withthe in’ and ‘notin Functions. These enable a sentence: you to check iF string contains (or does not contain) a sequence List=[“Conan”, “raised”, “his”, “mighty”, “sword”, fcharecters “and”, “struck”, “the”, “denon”] fmessage="Have a nice day” text” *.join(List) “nice” in message text "bad" not in message "Note the space between the quotes before the join Function (where “day” not in message there were no spacesin the Step 6sjoin) “night” in message ‘aces = z= Working with Data Formatting Strings When you work with data, creating lists, dictionaries and objects you may often want Roemmaet dace ee crane ei neo st ane acd PR oda ees ecto let ctu tcs STRING FORMATTING Since Python 3, string Formatting has become a much neater process, using the Format function combined with curly brackets. It’s a more logical and better formed approach than previous versions. Tebnicematnginegvonstocaean —— ERRERE vovcn fcnesoiceintegesino hemi ou variable into the string using the curly brackets: Su nunber=10000 rnane="Conan” print(*{} of {} was a skilled mercenary, printC“The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a 1)". Format Cnane)) mmerchant.”.format(nane, place, nunber)) PEPTIPR Remember to close the print function with two sets [EASA There are many different ways to apply string of brackets, as you've encased the variable in one, formatting, some are quite simple, as we've shown {and the print Function in another. You can include multiple cases of you here; others canbe significantly more complex. Ital depends String formatting ina single print Function: ‘on what you want from your program. A good place to reference Frequently regarding string Formatting is the Python Docs webpage, found at wwrw.docs.python.org/3.1/ibrary/string.html. Here, you vill Find tons of help nane="Conan” place="Cinmeria” printC*{} hailed from the North, in a cold land known as {}”.format(name, place)) Pe rr ee mr wee eee (Formatting 5 Ni front ofthe lst name: hunbers=1, 3, 45, 567546, 3425346345 print(“Some numbers: {}, {}, {}, {}, 0”. format (*nunbers)) \With indexing in lists, the same applies to calling @ STEP 6 list using string Formatting, You can index each item ‘according to its position (from 0 to however many are present} nunbers-1, 4, 7, 9 print(*More numbers: 23h (0h (2h i -format(*nunbers)) ue ba oh ty une ww Ae Interestingly you can reference alist using the string Formatting function. You need to place an asterisk in You can also print out the content of a user's input Sue8 in the same Fashion: ane=inputC“What?s your nane? “) printC*Hello {}.".formatCnane) FSTEED You can extend this simple code example to display the first letter ina person's entered name: nane=input(“What?s your name? “) print(“Hello {}.”.format(nane)) ‘Tname=List(nane) print(*The first Letter of your nane is a {0}". format (*Inane)) Format function ‘And as you probably suspect, you can mix strings and integersin a single lst to be called in the characters={“Conan”, “Belit” 20) print (“{0} is {3} years old. Whereas {1} is {4} years old.”. format(*characters)) » Waleria”, 19, 27, You can also call upon a pair of lists and reference STEP 10 them individually within the same print Function, Looking back the code from Step 7, you can alter it with: ames=[“Conan”, “Belit”, “Valeria”] ages=[25, 21, 22] Creating two lists. Now you can call each ist and individual tems: print(“{0[@]} is {1[0]} years old. Whereas {@[1]} is {1[1]} years old.”.format(nanes, ages)) Date and Time PM Rene Loi amen recto ae cCR lt Eo en eure rac eee Cet nel aese aii For how long. Luckily acquiring the date and time is easy, thanks to the Time module. TIME LORDS. The time module contains Functions that help you retrieve the current system time, reads the date From strings, Formats the time and date and much more. STEP 1 ee Youcanse the soucureofhow ines presented ‘that's built-in to Python 3 so you shouldn't need to_ byentering: dopineacinmandpronptangpnsate OrceRSIMCNEe, — etae tocatstinec you can althe curtent time and date with simple command: ‘import time ‘The output is displayed as such: ‘time. struct_time(tm_ ‘time.asctimeQ) year=2017, tmsmon=9, tm_mday=7, tm_hour=9, ° ‘tmmin=6, tmsece13, tmunday-3, tmyday=250, tm ‘isdst=0)’; obviously dependent on your current time as opposed tothe time shown above [Sunt see ies Pea a —_— ESTEE The time Functions spit into nine tuples, these are [ESTESIPBM There are numerous functions buitinto the time divided up into indexed items, as with any other ‘module. One of the most common of these is tuple, and shown in the screen shot below. strftime0. With t, you're able to present awide range of arguments ‘as converts the time tuple into a string For example, to display the current day of the week you can use: Fy time, strFtime #4") S| Seont 1 (0061 weap sent 6 ote Sr) 7 owt 1368 ond fens 0. met eters DT ss a 7 (. Date and Ti (Date and Time Cll PEPER) Thisnaturaly means you can incorporate various Functions into your own code, such as: time. strFtime(“%a”) time. strFtimeC“%B") time. strFtimeC“%b”) time. strFtimeC“3H") time. strFtimeC“HAN") FETED Note thelast two entries, with 6H and %H9%M, as {you can see these are the hours and minutes and as the last entry indicates, entering them as %H¥6M doesn't display the time correctly in the Shel. You can easly rectify this wth: time. strftimeC*KH:30") This means you're going to be able to display either the current time or the time when something occurred, such asa user entering their name. Ty this code in the Editor: ‘import time nane=inputC“Enter Login name: “) print(“Welcome”, name, “\d”) print(“User:”, name, “logged in at”, time. strftime(“3H:3M")) Try to extend Further to include day, month, year and so on, You sav at the endo the previous section, inthe 1278 code to calculate Pi to however many decimal places the users waned you cn time particle eventinPthon Take the code rom above and alter sight by including start_time=time.timeC) Then there's endtime=time. time()-start_time pete oe FEED The output will look similar to the screenshot below. ‘The timer Function needs tobe either side of the input statement, as that's when the variable name is being created,

You might also like