Vous êtes sur la page 1sur 164
Codin« for Pyt // you need to know about Coding al Peles: SFUTIT0100 DOWNLOAD Ca ere US Black Dog Media Master Your Tech To continue learning more about your tech visit us at: www.bdmpublications.com NN each IVE VE Cosae AN Photography, eee eae Tremacos * Catalina lanual Print & digital editions Featuring the very latest updates Step-by-step tutorials and guides Created by BDM experts Check out our latest titles today! SPECIAL DEALS and Bonus Content Sign up to our monthly newsletter and get the latest updates, offers and news from BDM. We are here to help you Master Your Tech! Ci . , tae Toren on ; Oar a mR Teor Ronee RU ONC ign up and get creative. ai Black Dog i-Tech Series Coding for Pyt Unlock your imagination with Python... There are few coding languages that have enjoyed the success of Python. Thanks to Python's unique development, everyone can learn the code that is: helping to drive such technological projects as the Large Hadron Collider, collating the petabytes of data that made up the First image of a Black Hole and creating the next generation of Artificial Intelligence. It doesn’t take long to get to grips with Python, but you need to start small. This guide will help you form the Foundation of your Python coding future, from installing the language on to your computer, through to Forming user interaction and complex variables. There's so much you can do with Python and within these pages you'll find everything you need to know to become a Python programmer, ready for the next level of advanced coding. Whether you're looking to learn Python for future career prospects, or just have some fun and discover something new, our step-by-step tutorials and guides will give you that much-needed foothold to help you on your way. So let's dive in and start coding with Python. @bdmpubs J 20™M Publications | www.bdmpublications.com Fy 10 R os 6 | Getting Started SRT Peel eore CeIn ueg Manda ered aceney aus! Rae RST tT aM MM URS cae rau es emer uraacius 76 Opening Files 66 = Tuples ee nnd DEUS ee 70 Splitting and Joining Strings CU) Manes eM aoa cea sige c BE Ey a a V5 * as ar é iar: ae te ae es] i @ ce a a a Om ra Q ees oon de: NS al Master Python with the help of our fantastic Code Portal, Featuring code for games, tools and more. CMe ng ng race ens Sra eget kein rue eccg Sree ocean seer 128 Playing Musicwith the Winsound Seo ener cs oD Sac RCC Da Us H re eee ee Eran ecole cd Sree Leona 133 _ Simple Python Calculator SEM earners Deed ad ‘aiey ae oe c UD wees p a 3 ae eek aa a etan CS "OC etc) Ps ren ae deo: Getting Sea ]nacre! eH ee Rad Petra ees rr t (cetinestanee CE Python isa high-level, general-purpose programming language that was developed by Guido van Rossum in the late eighties and is based upon a number of other languages, while being the successor to the popular ABC language. Ithas been devised to work on a human level, so it's readable and understandable without needing to delve into obscure volumes of machine code, hexadecimal characters, or even ones and zeros. It’s lear, logical, comprehensive, powerful and functional, yet also easy to follow and learn. You will Find Python at the heart of some of the most interesting and cutting-edge technologies in the world. It's the code that binds supercomputer algorithms together; it’s used in the space industry, and in science and engineering. Al, and the likes of Alexa and Siri, Cortana and the Google Assistant all utilise Python for their powerful voice recognition technology. It's simply an amazing, versatile and incredible language to learn. So let's get started and explore what you need to become a Python programmer. Being a Programmer ABrief History of Coding What can You Do with Python? Python in Numbers Why Python? Python on the Pi Using Virtual Machines Creating a Coding Platform z= Getting Started Being a Programmer Programmer, developer, coder, they're all titles For the same occupation, someone who creates code. What they're creating the code for can be anything from a video game eben ena al tae en reel enme ne Ml cele) Programmer though? ‘Times have changed since programming inthe ‘80s, but the core values still remain, “It’s up to you how far to take your coding adventure!” Being able to Follow a logical pattern and ssee an end result is one of the most valued oF a programmer. MORE THAN CODE For those of you old enough to remember the ‘80s, the golden era of home ‘computing, the world of computing was avery different scene to how itis today. 8-bit computers that you could purchase as.a whole, as opposed to being in kit Form and you having to solder the parts together, were the stufF ‘of dreams; and getting your hands on one was sheer bliss contained within 2a large plastic box. However, it wasn't so much the new technology that ‘computers then offered, moreover it was the Fat that For the First time ‘ever, you could control what was being viewed on the ‘television’ Instead of simply playing one of the thousands of games available at the time, many users decided they wanted to create their own content, thelr ‘own games; or simply something that could help them with their homework ‘or home finances. The simplicity of the 8-bit home computer meant that ‘creating something from a few lines of BASIC code was achievable and so the first generation of home-bred programmer was born. From that point on, programming expanded exponentially. It wasn’t long before the bedroom coder was a thing ofthe past and huge teams of designers, coders, artists and musicians were involved in making a single ‘game. This of course led to the programmer becoming more than simply ‘someone who could Fashion a sprite on the screen and make it move at the press of akey. Naturally, time has moved on and with it the technology that we use. However, the Fundamentals of programming remain the same; but what ‘exactly does it take to be a programmer? ‘The single most common trait of any programmer, regardless of what they’re doing, is the ability to see a logical pattern. By this we mean ‘someone who can logically Follow something from start to finish and ‘envisage the intended outcome. While you may not Feel you're such 2 person, itis possible to train your brain into this way of thinking. Yes, t takes time but once you start to think in this particular way you will be able to.construct and follow code. ‘Second to logic is an understanding of mathematics. You don't have to be ‘at a genius level but you do need to understand the rudiments of maths. Maths is all about being able to solve a problem and code mostly falls under the umbrella of mathematics Being able to see the big picture is certainly beneficial for the modern programmer. Undoubtedly, as a programmer, you will be part of ateam ‘of other programmers, and more than likely part of an even bigger team (of designers, all of whom are creating a final product. While you may only be expected to create a small element of that final product, being able to understand what everyone else is doing will help you create something that's ultimately better than simply being locked in your own coding cubicle. Finally, there's also a level of creativity needed to be a good programmer, ‘Again though, you don't need to be a creative genius, just have the imagination to be able to see the end product and how the user willinteract with it. ‘There is of course alot more involved in being a programmer, including learning the actual code itself, However, with time, patience and the determination to learn, anyone can become a programmer. Whether you want to be part ofa triple-A video game team or simply create an ‘automated routine to make your computing life easier, i's up to you how Far to take your coding adventure! ( Being a Programmer Cl =D A Brief History of Coding {leet o Mega aan ee Ne Renn aoe ar led olor ceo ee) (aN] kB oe eels Keone ate Kon Var A) a ea ag Od ESM ao eo neKe Uc Ucoare Reels eM a TE-[aet =] NVM ee Men ced me tee e Aeon RRR RRC RRC RO RRR Essentially al forms of coding are made up of ones and zeros -on or off states. This works for both a modern computer and even the oldest known computational device. ‘87 BC 1800 1842-1843 Ws cificult to ping Teg ‘programmable loom, which used cards with Pie eee eee eaters sid Ce eee nny eae tee “The Bon Masa brothers, three Persian Ee tiated Snead Cee ree Coo cd ere at renee a ere ere eae eee method of calculating Bernoulli Numbers 7 ee Par Me We Wee Ce nes Perea Ce a ural ees CNA Rian hae er ety CE ey Bg ees 1951-1958 1960-1970 From the 1970s, the development of the likes of C SQL, Cwith Classes (C+), MATLAB, Common Lisp and more, came to the fore. The’80s was undoubtedly the golden age ofthe home ‘computer atime when slicon processors were cheap enough For ‘ordinary Folk to buy. This ed toa boom in home/bedroom coders with the rise of bit machines. 1970-1985, 1990s-Present Day Computer programming was mainly utilised by big corporations and the 70s. A notable: towarda more user friendly, forhome user, language was the development of BASIC ‘Objective-c (Geginners All-purpose Symbolic instruction Code) in the mid-sixties. rey occas Cee error eee eed Ciro ee enema) erected ice ein Pere ea euch tooe es stillin use today. ‘The internet age brought a wealth of new eter ere oie sence et nee ae eee ne "Not only could a user learn how to code, Repel et neuen Be te se tee ‘Admiral Grace Hopper was part of the team that developed the UNIVAC I computer and she eventually ‘developed a compiler forit.Intime, the compiler she developed became }BOL (Common Business-oriented Language), a computer language that's ee cd What can You Do with Python? Python is an open-source, object-oriented programming language that’s simple to understand and write, yet also powerful and extremely malleable. It's these Roar TeeCencttle eM antler Mure estan TaM an oracle lale Uevel aon (Cra Pesce ies or ne ag gree ‘oF instructions has a considerable impact on our modem digital _ scenes. This s why it's such an important language to learn, ee ume eo) ‘reate interactive stories and games; from scientific applications to, Sino eee eco nes Ce eens Tse na etc ee ie ead Cet een area ieraaece et eu tue ee eats SE eur ou re mam eee er eee aoc eee emery fils the gaps and provides the means to get the ob done. You'll. Big data isa buzzword you're likely to have come acrossin the last couple of years Prone enter hsyeet eee cenit Pere eee ete teen erenreogetis eset ee eee a Pee ree Ca industries, from social media to health and welfare, engineering to space exploration era) ra Oe ecu ue meta enue Pere teeny eee crease ee kee econ to : oe ee eo emer en See ae eee ect once behoaeorsirepeetenancinn ovine Harrap neonate Lepoiiye: spseremr sk ber airn payment) Collsons pet secondthat the Large Hadron Calder HC) produces Adiferent language eerie tempter NRE ETE ot EO AA) ee Reeser ee 5 42) wonbampubtistionscom RTI TEL ICE } ers pain eme nemeenmar tececirunsiee| paneentthreureder mers Pictipiiepunearairemaerr piety bihareyaiet wre viononeritnet etna iepeinirirsann steneniriad pea fae However, Al isnt simply the creation of autonomous robots eens err eed eee Re eee ee er ey | ean ecu c nec Ce se oe nas ge ene ree er Rc | Instagram and so on. Have you ever looked up a celebrity on Instagram and then discovered that your searches within other Pee eae etre ee od Pe Cc aaa Lees eS eae Rene a an Spotty, For example, uses Python based code, among Son eee eae een) ener ry amnesic inthe pasts all ever stuff and, moving ee eee eee Raeeser en inret ts ee _S WEB DEVELOPMENT |Web development has moved on considerably since the early days of HTML scripting ina limited text editor. The many Frameworks and web management services available now ‘means that building a page has become increasinaly complex. With Python, the web developer has the ability to create dynamic and highly secure web apps, enabling interaction with ther web services and apps such asinstagram and Pinterest. Python also allows the collection of data from other v and even apps built within other websites. T What can You Do AMINECRAFY Eons james coded using aye surpisedto lean tha Python is used as an extra on many ofthe high-anking modern games, Many map ec iif youbuild a stilisePytho the serverside elements, These include; code to 1 balancing cr check whether the player’ language potential cheatin, ste game's < There'salsoa the serveradmin toad ofthe background PY JON EVERY\ ‘As you can see, Pythons quite a versatile Cou Te a eee eee ee able to take you into the next generation of Co cr ae hobbyist. Peer ner eee Cee ed ro => Getting Started 5 There's a lot to like about Python, but don’t just take our word for it. Here are some amazing facts and Figures surrounding one of the most popular programming languages of recent years. Gs) Alexa, Amazon's Virtual Personal Assistant, uses Python to help with speech recognition, 5 Sadaqwn “8 Data analysis and Machine Learning are the two most used Python ‘examples. PYTHON AND LINUX SKILLS ARETHETHIRD — waereneengef20 MOST POPULAR —nateuracrcresiyton discussed language on ~~ ET. SKILLS IN to operate between other thelneme EU. ‘rane pokages. a nm = AWM ~ f % 15% | ‘ : 15% ng SMa Sling 8 “nnn “etna “early San rsK0F aor srw Scr Romano worm publications com (- Python in Numbers Cl PYTHON SKILL-BASED POSITIONS ARE THE 6th: “MOST SOUGHT-AFTER There are over ‘6 1000 Python jobs posted every six months in the UK. JOBS IN THE UK. Python Data Science is oosle's the top Data Science, Blockchain New York and San thought to become the company for hiring Python ‘and Machine Learning, Francisco are the top most soughtafter ob in developers, closely ae the fastest growing Python developer cities the coming years. followed by MierosoFe. Python coding sls, inthe world. —_> Python developers enjoy an average salary of —w — === £60,000 (95% ) (15%) (79%) (19%) 9% ) Lt es gay IN “nmin To sMorarcccrtin —_oraurnth en $F ce wmivor Eee Pema tee Fomnnecum openers aperinte! MrTcn a anes MCN on eoRerot faemend emcee eat eral erecta evan ranued om Geren | een pesesaiue pean eae fee cused anuacat \ @) Getting Started ) Why Python? A There are many different programming languages available for the modern computer, Pete EV cece Mattei cr escuela eed entrees are designed For scientific work, others for mobile platforms and such. So why choose Python out of all the rest? PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away untilthe wee hours, slaving over an overheating heap of circuitry to create something akin to magic. ‘These pioneers of programming carved their way into anew Regardless of whether you use an Android device, iOS device, PC, Frontier, Forging smal routines that enabled the letter’ to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin ‘across the screen. It may not sound terribly exciting to ageneration tocar, set-top box or a thousand other connected and ‘smart that's used to ultra high-definition graphics and open world, multi» appliances, behind them alls programming, player online gaming, However, Forty-something years ago it was blindingly brian. Allthose aforementioned digital devices need instructions to tell. them wiatto do, and allow them to be interacted with, These Naturally these bedroom coders helped form the Foundations for instructions Form the programming core of the device and that core ‘every plece of digital technology we use today. Some went onto _can be bult using a variety of programming languages. ‘become chief developers for top software companies, whereas ‘others pushed the available hardware tots imits and founded the The languages in use today differ depending on the situation, the bilion pound gaming empire that continually amazes us. platform, the device's use and how the device wil interact with ts See eee et viveotniny| @|D|BHeCe/>/T@ ctrtsscnntdoottocst vem serayctrl::childLostFocus() itlcurgor = 0) Pefreshrow cursor): curt chi taboserocus(): gees eo, asrecusbeep(): OetLinest(sb)e eader-cetserol10; y=) olor fe = slend(scoleroisabled, scolorPeper): Sera) sie(a < oatcoune) Tyee amen) sb LittPeop > sizeccy) breaks top t aettinecy(i) farina J°= js: 3 = column. cetcoune(); j+4) ( | ‘int Gv hasder-Setvabwastn(g)s Int em = columni}i-margins ) ettargint: 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 of availabe languages such as HTML, Java, Python and soon. ‘More general-purpose programming is used to create programs, apps, software or whatever else you want to call them. Theyre 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 asa High-Level Language, in that it talks to the hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless more interactions. Whilstt'snatas streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that it's universally accessible {and easy toler, import java. lang.reflect.*; ‘lass. tnvoke { Oe ublic static void main( string (] args ) ¢ try Glass ¢ = Class. fornane( args[0] ); Method'm = c.getethod( args{1], néw class Ot} Object rét = m.invoke( null, nut system out printinG Stavoked. static method: " + args(1] #Poffetass: * © args{o) Zn with no args\neesults: "+ ret); } catch ¢ Classnotroundexception e ) { 77 Class fornane() can't find the class } arch’ NosuchMethodexception e2\) 77 that method doesn't exist 3 earch’ TMegataccessexception e3 ),{ 77 we don't have permission to invoke that inethod ¥ Catch ( nvocationtargetexception ef ) { 77-an exception ocurred while invoking that inethod Syst out .printin¢ jethod threw an: " + e4, getTargetexception( ")"); Javaisa powerful language that’s used in ‘web pages, settop boxes, ‘TWsand even cars. (why Pyth ' a y Pythor Python was created over twenty six years ago and has evolved to become an ideal beginner's language for learning how to programa computer. It's perfect For the hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves or a piece of external 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 leven RISC OS, I has been voted one ofthe top five programming languages inthe world ands continually evolving ahead of the hardware and Internet development curve. So to answer the question: why Python? Simply put, it's Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational tool. BASIC was once the starter language that early B-bit home computer users learned. in ey srr) om) reer ree Python isa more modern take on BASIC, it's easy to learn and makes for an ideal beginner's programming language. Python on the Pi IF you're considering on which platform to install and use Python, then give some thought to one of the best coding bases available: the Raspberry Pi. The Pi has many advantages for the coder: it’s cheap, easy to use, and extraordinarily Flexible. THE POWER OF PI Paar ce a ees ee ee ag us are unable to jump into a several hundred-pound investment when we're starting off and this is where the Raspberry Pi can coos \While having a Far more powerful coding platform on which to Roots ee eo) Ets oto eee nats Reet Die ce aaa ‘The Raspberry Plisa Fantastic piece of modern hardware that has created, or rather re-created, the Fascination we once all had ‘about computers, how they work, how to code and foundation level electronics. Thanks to its unique mix of hardware and custom software, ithas proved itself tobe an amazing platform on which to eer ce ee Cie ea eo naan) ‘ode with other programming languages, it’s Python that has been firmly pushed to the Forefront. The Raspberry Pi uses Raspbian as Cee re ae tny St eee ond ee ee Bonu ce eee ae Ceca eet) eee cs Python modules, extensions and even examples, out ofthe box. peer etn ramet tert cg instructions on how to set one up (by using one of our excellent eet omer eet to eu) ‘ansstart coding with Python as soon as the desktop has loaded. ‘Significantly, there's alot more to the Raspberry Pi, which makes, itan excellent choice for someone whois starting to learn how to Sr er Pa ae eee to remotely connect tothe Raspberry Prom any other computer, a oe eT) Sea tee ot power socket anywhere in your house within range of your wireless router. As long as the Pils connected, you willbe able to remotely See eee ed sitting i Front ofthe Pi with a keyboard and mouse. Using this method saves alt of money, as you don't need another Peet eee nee ee on cS Peete ene et eet eee for space and money, then for around £60, buying one ofthe many er) kits available will provide the Pi with apreoaded SD card (withthe latest Raspbian 05), acase, power socket and cables, thisis a good Pratt ey steno rt ah een) wallundera desk, while stil being able to connect toitand code. ‘The main advantage is, of oUrse, the extra content that the Raspberry Pi Foundation has included out of the box. The reason ea eee ee eed Rt ee tree Ce eee ee tee ee IDEs forthe user to compile Python code on; as well as both Python 2 and Python 3, there's even a Python library that allows you to Petes There are other advantages, such as being able to combine Python eer Nee ern eae ees Cee Cr ete ert ont being able to code the GPIO connection onthe Pit Further control any attached robotics or electronics projects. Raspbian also includes ee nee ots Circuitry that offers diferent electronics robotics and motorisation projectsto the PD, which can be accessed via Python code, Consequently, the Raspberry Plisan excellent coding base, as well Peet nia ec a erent eee ie een oe orcad throughout this ttl, While the code is written and performed on a Pi, you're also able to use itin Windows, other versions of Linux and ‘macOS. the code requires a specfic operating system, then, don't De seed Ceo me ete os ae Fete Introduced on 24th June 2019, the Raspberry Pi4 Model Bis a significant leapin terms ofP performance specifications. It was also one ofthe quid riginal i to sellout with anew 1 a choice of 16 closer to becoming a true desktop computer. In adton, the Pid was launched withthe startling decision to include dual monitor support, inthe Form ofa pair of two ts Youlals find a pair Inaddtion to releasing the Pi the Raspberry Piteam also compiled anew version ofthe Raspbian operating system, codenamed Buster. In conjunction with the new hardware the offer few updates. Although onthe whole it appearance and operation tothe previous version of Raspbian. The Updates are mainy splay and playback giving the Pi anewset of graphical divers and performance enhancements 2 in this book wll work withthe Raspberry P 4 and Raspbian Buster! ‘once setup you can remotely connec to the P's desktop (eri 0 ports, Bluetooth 5.0, anda GPU that’s capable of handing lutions and OpenGLES 3.0 graphics. Inshort, the Pi4is the most powerful othe current Raspberry Pi models. However, the different memory versions have an increased ost. The 1GB version costs £34, 2GBis€44, and the 4GB version wil you back £54, Remember to also Factor in one oF two micro HOM You can even test connected hardware with Python SMa oe z= Getting Started ) Using Virtual Machines Ate roa Men tete ene Een eur) on your desktop. This way, you're able to host multiple systems in a secure, safe and ference a Dennen MNT Kee ‘Sounds good, but what exactly isa Virtual Machine (VM) and how does it work? ‘The official definition ofa vital machine is‘an efficient, isolated duplicate oF areal computer machine. This basically means that @ virtual machine is an emulated computer system that can operate in ‘exactly the same way asa physical machine, but within the confines ‘of a dedicated virtual machine operator, or Hypervisor. ‘The Hypervisor itself, is an app that will allow youtto installa separate operating system, creating a vitual computer system within itself, complete with access to the Internet, your home networkand so on, ‘The Hypervisor wil take resources from the host system - your physical computer, to create the virtual computer. This means that part of your physical computer's: memory, CPU, hard drive space ‘and other shared resources, will beset aside for use in the virtual machine and therefore won't be available tothe physical computer untithe hypervisor has been closed down, Coding for Linux This resource overhead canbe cripping forthe physical machine iF you dont already have enough ‘memory, or hard drive space available, or your computer has a particularly slow processor. While it's entirely possible to run Virtual machines on a ttle 52GB of memary, it's nt advisable. Ideally, you wll ‘need a minimum oF 868 ‘of memory you can get away with 4GB, but again, your physical computer will begin to suffer with the loss of memory to the virtual machine), at least 25, to 50GB of free space on your hard drive and a quad: core processor (again, you can have adualcore CPU, but that can cause a bottleneck on your physical computer). ‘Our Linux titles contain steps on how to installa hypervisor and 0s. ‘The limit to how many different virtual machines you host on your physical computer is restricted, therefore, by the amount of physical system resources you can allocate to each, while still leaving enough for your physical computer to operate on. You're able to install Linux, and code inside a virtual ‘machine on a Windows 10 host. VIRTUAL OS From within hypervisor you're able to run a number of different ‘operating systems. The type of OS depends greatly onthe hypervisor you're running, as some are better at emulating 3 particular system over others, For example, VirtualBox, afree and easy to use hypervisor from Oracle, is great at running Windows and Linux virtual machines, bt isnt so good at Android or macOS, (QEMU is go0d For emulating ARM processors, therefore ideal for ‘Android and such, butit can be dificult to master. There are plenty of hypervisors available to try for free, with an equal amount commercially available that are significantly more powerful and offer better features. However, for most users, both beginner and professional, VirtualBox does a good enough jo. Within 3 hypervisor, you're able to set up and install ary ofthe newer distributions oF Linux, or iFyou Feel the need, you're also able toinstall some of the more antiquated versions. You can install early versions oF Windows, even as Fr back as Windows 3 complete with DOS 6.22 although you may Find some Functionality of the VM lost due to the older drivers (such as access to the networt). With this in mind then, you'e able to have an instalation of Linux Mint, or the latest version of Ubuntu, running in an app on your Windows 10 PC. This's the beauty of using a virtual machine. Conversely, if your physical computer has Linux its installed ‘operating system, then with a hypervisor you're able to createa Windows 10 vital machine although you will need to have a licence code availabe to register and activate Windows 10. Using virtual machines removes the need to dual-hoot. Duatbooting ishaving two, or more, physical operating systems installed on| the same, or multiple, hard drives on a single computer. As the ‘computer powers up, you're given the option ta choose which OS, youwant to boot into, While this sounds like a more ideal scenario it isn't akways as straight Forward as it sounds, asall the operating systems that are booted into will have Full access to the computer's entire system resources, The problems with dual-booting come when one ofthe operating systems is updated. Most updates cover security patching, or bug Fixing, however, some updates can alter the core -the kernel, oF the OS. when these changes are applied, the update may alter the way in which the OS stars up, meaning the initial boot choice you made could be overwritten, leaving you without the ability to access the other operating systems installed on the computer. To rectify this, you'll need to access the Master Boot Record and alter the configuration to re-allow booting inta the other systems. There's ‘also the danger of possibly overwriting the fist installed 0S, or ‘overwriting data and more often than not, most operating systems dont play well when running side-byside. Indeed, while good, dual booting has more than its Far share of problems In contrast, using a virtual machine environment, while stil problematic at times, takes ‘out some of the more nasty and disastrous aspects of using multiple ‘operating systems ona single computer. Even old operating systems can be run inside a virtual machine. Virtual machines can be as simple, or as complex as your needs require. (Using Virtual Machines Cl ADVANTAGES FOR CODERS For the coder, having virtual machine setup offers many ‘advantages, the most popular being cross-platform code. Meaning if you write code within Windows 10, then with an installation of Linux distro ina hypervisor, you're able to quickly and effortiesly ower up the virtual machine and test your code in a completely different operating system. From ths, you're able to iron out any bugs, tweak the code so it works better on a different platform and ‘expand the reach of your cade to non-Windows uses. The advantage of being able to con! environment, in specific ways For specific projects, is quite invaluable. Using a virtual machine setup greatly reduces the uncertainties that are inherent to having multiple versions of programming languages, libraries IDEsand modules installed, to support the many cfferent projects you may become involved in as ‘coder. Elements of code that ‘talk’ lect ta specifics of an ‘operating system can easilybe overcome, without the need to clutter up your main, host system with cross-platform libraries, which in turn may have an effect on ather libraries within the IDE. ‘Another element to considers stability, IF you're writing code hat could potentially cause some instability tothe core OS during its development phase, then executing and testing that ‘code on a virtual machine makes more sense than testing ton your main computer; where having to repeatedly reboot, or reset something due the code's instabilities, can become inefficient and just plain annoying The virtual machine environment can beviewed asa sandbox, where you're able to test unstable code without t causing harm, or doing damage, to your main, working computer. Viruses and malware can be isolated within the VM without infecting the main computer, you're able to set up anonymity Internet use within the VM and you're able toinstal third-party software without it slowing down your main computer. GOING VIRTUAL While you're atthe early stages of coding, using a virtual machine may seem a ittle excessive, However, it’s worth looking into because coding in Linux can often be easier than coding in Windows, as some versions of Linux have IDEs preinstalled, Either way, virtualisation oF ‘an operating system show many of the professional and successful coders and developers work, so getting used toit early on in your skill etis advantageous, py Ceding in Python on the Raspberry Pi Desktop OS inside a VM on Windows 10! To stat, look at installing VirtualBox. Then consider taking a look at our Linux titles, https://odmpublications.com/ts=linux&post_ type=product, to learn how to install Linux na virtual environment ‘and how best to utlise the aperating system, Creating a Coding Platform The term ‘Coding Platform’ can denote a type of hardware, on which you can code, or a particular operating system, or even a custom environment that’s pre-built and designed to allow the easy creation of games. In truth it’s quite a loose term, as a Coding Platform can be a mixture of all these ingredients, it’s simply down to what Programming language you intend to code in and what your end goals a1 ct toget going numerous apps that: ern aor fees: PAPAS Thankfully, coding at the Foundation level doesn't require specialist equipment, ora tap ofthe range, liquid 1yérogen- Hello, World / Getting to Know Python Tuer eect cc lee) eure kerr let er Norn cod At VMN Meee mae Re TCE Mel fel Mea eee (ITO Lg 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 language isallistof instructions that a computer follows. These instructions can be as simple as displaying your name or playing a music file, or ascomplexas building a whole virtual wari, Python isa programming language conceived inthe late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (Cw inthe Netherlands asa successor to the ABClanguage, Guido van Rossum, the father of Python. PROGRAMMING RECIPES Programs are lke recipes For computers. A recipe to bake a cake could go like this Put 100 grams of selfraisng flour in a bow ‘Add 100 grams of butter tothe bowl ‘Add 100 miliitres of milk Bake for half an hour. CODE Just like a recipe, a program consists oF instructions that you Fallow in order. A program that describes acake might run like ths: bowt flour Ij butter = 50 milk bowl .append¢[four, butter milk] Il cake: cookCoonl) PROGRAM COMMANDS. You might not understand some of the Python commands, like bowl append and cake.cook(bow), ‘The first isa list, the second an object; we'll look at bath inthis book. The main thing to know is. that it’s easy to read commands in Python. Once you learn what the commands do, it's easy to Figure out how a program works, “ 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 all the power of a computer ina language This because they fly high above the hardware also referred to.as that humans can understand, Behind all thisis an ethos called "The “the metal). Languages that “ly closeto the metal, like Assembly, Zen of Python.” Thisis a 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 tke thisimsg db ,0xa len equ $ = msg isbetter than ualy" and “simple is better than complex." Type import this into Python andit will dsplay al the principles. PYTHON 3 VS PYTHON 2 eeu amnesic ise Segue Pe Lae! WORLD OF PYTHON (pienempaueeae PRET RAD (5 2008 e1thon 3 arrived with several new, Cae Cae ee e Python site and investigate provides more stable, effective and efficient programming is ete ae Pigs oe an lett era pytenaze me tens : PYTHON 2. es onal ERRNINED 23ine0 9 arnina papery bes mean tat Te ei Unie 7 Messe CS MC emg ie eons ‘40 ta programming languages For beginners and experts to code in, which makes tan extremely valuable resour z=» Hello, World How to Set Up Python in Windows Wn UAC earl ale and MNCL Tua aT Pierce meses eens aetna oe ce) 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 it will be necessary to install it yourself manually. Thankfully, it’s an easy process to follow. FETED Se2rtbyopening your web browsertowww.python. EEE choosing the Customise option allows you to ‘ra/downloads/. Look forthe button detailing the specify certain parameters, and whilst you may Download link For Python 3.x. Python is regularly updated, changing stay with the defaults, i's a goad habit to adopt a, sometimes (aot the lst digit for each bug Fix and update. Therefore, don't worry if with Python, thankfull), installers can include unwanted additional you see Python 3.8, r mare, as lang asi’s Python 3, che cade inthis Features. On the frst screen available, ensure all boxes are ticked ‘book wll work Fine, ‘and click the Next button, os =a Optional Features amin = 7 Bam nn : ent te Be ian ie te ge Won tn ew PEPPER ick the Download button for version 3.xand BEPEPR) the next page of options include some interesting save the file to your Downloads folder. When the additions to Python. Ensure the Associate file with File is downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables, installation wizard will aunch. Fram here, you have two choices: recompile Standard Library ad Install for All Users options are Install Now and Customise Installation. We recommend opting for _ticked. These make using Python later much easier. Clickinstall when the Customise instalation link. you're ready to continue. B rrensararoasan ST) reeianarwases a Install Python 3.8.0 (32-bit) ‘Advanced Options se ta nF gue ny ae © vst ow ea nena rea tne Ct a gett ‘aserynnte nine e sans ae ssa Srmoyin sunar ray : —~ Cre ogee Covent eg bre 82015 ie) Fi Fi Cor sro ome ED) sirosicioncan How to Set Up Python in Windows Cll You may need to confirm the installation with Ty the Windows authentication natification. Simply click Yes and Python wil begin to install.Once the installation is omplete, the final Python wizard p3g wwthe latest release notes a ing onthe IDLE (Python 3.x32-bi link wll launch the Python Shell, where you can begin your Python pragramming journey. Don't orf your version's newer, as long asit's Python 3.x our code works inside your Python 3 interface will alow you to Follow some online tutorials python windows EEZD eerie od ick on the link next tothe 1 this time type: CMO, you'llbe presented with shield detalled disable Path Length Limit +ompt link Clickitto getto the V his wil allow Python the Com ndows 260 character limitation, enabling you to line environment. To enter Python within the commandline, you ‘execute Python programs stored in deep Folders arrangements. need to type: python and press Enter. Click Yes again, to authenticate the process, then you can Close the installation window. o Chose BED i icssenrontettereatetryon AAEM te eran weet hon vs 3.x within the Start button Recently Added section. ‘much the same way asthe Shell you opened in The first ink, Python 3x (32-bit) will aunch the command line ep 8; note the three leftfacing arrows (>>>). Whilst i's a perf rersian of Python when clicked (mare on thatin a Fine environment, its not too user-friendly, so leave the command he IDLE, type IDLE into Windows sta line For now. Enter: Exit to leave and cl Prom lose the Command Hello, World How to Set Up Python in Linux PYTHON PENGUIN Linuxis such a versatile operating system that it's often difficult to nail down just one-way of doing something. Different BETTIE Fist you need to ascertain which version of Python urrentl installed in your Linux system. To begin with, drop into a Terminal session from your dstro’s menu, or hit the CtrbvAlesT keys. davidedavie-Mine:~ file Eat View Search Terminal Hee Next, enter: python =-version into the Terminal sure screen. You should have the output relating to version 2.x of Python inthe display. Most Linux dstro come with both Python 2 and 3 by default, as there's plenty of code out there. stil avallable For Python 2, Now enter: python3. =-version. davidedavid-Mint:~ Fle edt Help View Search Terminal ‘our tutorials will work. I's always worth checking to see ifthe distro has been updated with the latest versions, enter: sudo apt-get: update && sudo apt-get upgrade to update the system, In our case we have both Python 2 and 3 installed As long as Python 3xxis installed, then the code in worm publications com distributions go about installing software in different ways, so For this particular tutorial we will stick to Linux Mint. ‘Once the update and upgrade completes, enter SED hana version gan to see Python 3xis updated, or even installed. Aslong as you have Python 3.x, you're running the most recent major version, the numbers after t indicate patches plus Further updates. Often they're unnecessary, but they can contain vital new elements, However, you want the latest, cutting edge ED version you ned to build Python from source. Start by entering these commands into the Terminal sudo apt-get install build-essential checkinstall sudo opt-get install Libreadline-gplv2-dev LibncursesuS-dev libssl-dev libsqlite3-dev tk-dev Libgdbn-dev Libc6-dev Libbz2-dev ( How to Set Up Python in Linux Spenoyourtnawedbiontandsotote | EARP Forte COU yovreedtoeterte long ued Python download page: httpsi//www.python.org/ ue) ‘command into the Terminal: downloads Cickonthe Downloads flowed byte button under the Python Source window, Ths opens a download Galogue box choose oloation, then tart the dovnload process. ThelOLEcan thenbe started wth the command: {de Noe that [DLE Tunsa dent version tothe one youlntaled From source, sudo opt-get install idle3 vides Mint: -/DownlondPyton 372 Inthe Terminal g0 tothe Downloads folder Sia byentering: ed DownLoads/. Then unzip the contents ofthe downloaded Python source code with: tar =xVF Python-3.Y.Y.tar.x2 (replace the Vs with the version numbers Youve downloaded). Now enter the new unzipped folder with Python-3.Y.¥/ FIED 1 aso need PP (Pip sal Packages) whichis 2 tool to help you install mare modules and extras. Enter sudo apt-get install. python3-pip (Once PiPis installed, check forthe latest update with: pip3 install --upgrade pip When complete, close the Terminal and Python 3x ill be available via the Programming section in your distro's menu. idan ommend 3.72 e PEPER wichinthe Python folder, enter: -/configure sudo make altinstall This could take a while, depending on the speed of your computer. (Once finished, enter: python3.7 =-verssion to checktthe latest installed version. You now have Python 3.7 installed, alongside older Python 3xxx and Python 2. Installation of Python on macO can be done in much the same way asthe Windows installation. Simply go to the Python webpage, hover your mouse pointer over the Downloads linkand select Mac 05 X from the options. You willthen be ‘Quided to the Python releases for Mac versions, along with the necessary installers for macOS 64:bit for OS X 10.9 and late. ‘wovabepublications com => Hello, World Starting Python For the First Time BUN Ch oan Noe AON Mol eu MeL ciel cele arene Ue eR Aen cod CLE hele CMa eu See cama eeeocn Le Meeniteraiien eke Elecite) RUE a nO N Morale ea Lt okeoLe laren] ace STARTING PYTHON Everything you need to begin programming with Python is available from the Raspberry Pi desktop. However, you want, drop into the Terminal and update the system with: sudo apt-get update. FETTSERD With the Raspbian desktop loaded, click on the ESTEE or exemple, in the shell enter: 242 “Menu button Followed by Programming > Python ‘After pressing Enter, the next line dsplays the 3 (IDLE). This opens the Python 3 Shell Windows and Mac users can answer: 4. Basically, Python has taken the ‘code’ and produced the Find the Python 3 IDLE Shell from within the Windows Start button relevant output. menu and via Finder. PPIPD The shellis where you can enter cade andsee the EFM the Python shell acts very much ike a calculator, responses and output of code you've pragrammed since code i basically a series of mathematical into Python. This is akind 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, multiplied and so on. ype Scapytsghess Nraaita" or “Lianaac)> for mace sntemation. eels, Or 2s, TTT ( Starting Python for the First Time Cl While thats very interesting, it's not particularly exciting, Instead, try this printC“Hello everyone!" Just enter itinto the IDLE as you've done inthe previous steps, well as quote marks in order to output content to the screen, inthis case the ‘Hello everyone! bit, >>> print("Hello everyone!") Hello everyone! >>> | You may have noticed the colour cading within Rice the Python IDLE. The colours represent different ‘elements of Python code. They are Black Data and Variables Green~Strings Purple Functions (Orange Commands Blue— User Functions Dark Red Comments Light Red ~ Error Messages, IDLE Colour Coding ahtved[Ererrsseote | syntanteror: | PETER) The Python IDLE isa configurable environment. F you don't ike the way the colours ae represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don't recommend that, as you won't be seeing the same as our screenshots ESTER ust ike most programs available, regardless ofthe ‘operating system, there are numerous shortcut keys available. 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 The Python IDLE's a power interface and one that’s actually been written in Python using one ofthe available GUI toolkits. I you want to know the many ins and cuts ofthe Shell, we recommend you take afew moments to view ‘www-docs.python.org/3/library/idte.htm, which details many of the IDLE's Features sworabdrmpubicatonscom — ES ED) tetowore 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 er h ined Meee et utaven cnc 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. BEER you've closed Python 3 IDLE, reopen itin FETTER You can see that instead ofthe number 4, the whichever operating system version you prefer. In ‘outputs the 2+2 you asked to be printed tothe the Shell enter the Familiar Following: screen, The quotation marks are defining what's being outputted tothe IDLE Shell to print the total of 2+2 youneed to remove the quotes: pe pit Seas” a “hewn fr are information, EITEEE DD st 2s predicted, the word Hello appears in the BETES You can continue as such, printing 2+2, 46442343 Shell as blue text, indicating output from a string ‘and so on to the Shell. An easier way is touse a ‘fay straightforward and doesnt require too much explanation. variable, which is something we will cover in more depth late. For Now try row, enter: ( 5 (eo C Your First Code \hatyouhave done here assign the tesa Sua?5 and b two values: 2 and 2. These are now variables, which can be called upon by Python to output, add, subtract, divide ands0 0 foras ong as their numbers stay the same. Tr this printca) print(b) FETED The output ofthe last step displays the current values of both a and b individually, as you've asked ‘them to be printed separately IFyou want toad them up, you can usethe following print (arb) This code simply takes the values of a and b, adds them together and outputs the result ‘oe bash oy aon ee FETS You can play around with different kind of variables and the Print function. For example, you could assign variables for someone's name: nane="David” print(name) PEPER) Now let's add surname: ‘surnane="Hayward” print(surname) ‘You now have two variables containing a first name anda surname ‘and you can print them independently. IF we were to apply the same routine as before, Sia Using the + symbol, the name wouldn't appear correctly inthe outputin the Shel, Try it printCname+surnane) You need a space between the two, defining them as two separate values and not something you mathematically play around with, |e eat oat ge tm ne In Python 3 you can separate the two variables STEP 10 with a space using a comma: print(nane, surname) Alternatively, you can add the space yourself: print(nanes” “+surname) “The use of the cammais much neater, as you can see. Congratulations, you've just taken your first steps into the wide ‘world of Python. ora vémpublications com Hello, World Saving and Executing Your Code MCRL R Mea) Re ete CAE Keele El eee eel 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. FET SERED Fist, open the Python IDLE Shell and when ts up, dlickon File > New Fie. This will open a new window with Untitied a its name. Thisis the Python IDLE Editor and within it you can enter the code needed to create your Future programs. FETED The IDLE Editor's, forall intents and purposes, a simple text editor with Python features, colour ‘coding and so on; much inthe same vein as Sublime. You enter ‘ode as you would within the Shel, so taking an example from the previous tutorial, enter: FETED You can see thatthe same colour coding isin place inthe IDLE Editor asitisin the Shell, enabling you to better understand what's going on with your code. However, to ‘execute the code you need to first save it. Press FS and you get a Save. .Check box open. = eee BEPIM click on the OK button in the Save box and select a destination where you'l save all your Python code. “The destination can be a dedicated Folder called Python or you canjust dump it wherever you like. Remember to keepa tidy drive though, to help you out inthe Future. (Saving and Executing Your Code \ Gl Enter aname for your code, ‘print hello’ for ‘example, and clickon the Save button. Once the Python code is saved it's executed and the output willbe detailed in the IDLE Shell In this case, the words Hello everyone!” Thisishow the vast majority of your Python code willbe conducted. Enter it into the Editor, hit F5, save the code and look atthe output inthe Shell. Sometimes things will fer, depending on whether you've requested a separate ‘window, but essentaly that’s the process's the process we will use throughout this book, unless otherwise stated Let’ extend the code and entera few examples from the previous tutorial: name="David” surname="Hayward” printCnane, surname) print Carb) Ifyou press F5 now youll be asked to save the file, again, a t's been modified from before. FETED vou cick the Ok button, the Fle willbe ‘overwritten withthe new’ cade entries, and executed, with the output inthe Shell. t's not a problem with just these few lines butf you were to edt a larger file, overwriting can become an issue. Instead, use File > Save As from within the Editor tocreate a backup, Ifyou open the file lacation ofthe saved Python, code, you can see that it endsin a py extension. Thisis the default Python file name. Any code you create will be whatever py and any code downloaded from the many Internet Python resource sites will be py. ust ensure thatthe code is written for Python 3, PEPRET DD Now create anew file. Close the Editor, and open anew instance (File > New File from the Shel) Enter the following and save itas hello py ‘a="Python” boris” c="cool!” print(a, b, <) ‘You willuse this code in the next tutorial Talay. enapiboamara yen Comate py aaa ie Ee Fart Snore urs He Hello, World Executing Code from the Command Line COMMAND THE CODE vow bdmpublatons.com Executing Code from the Command Line 0 RD the resutt of running Python 3 cade from the thon 2 command line is quite obvious, Whilst it doesn't error outin any way, due to the nter the: erer ous tutorial and lst the avaliable files within; hopefully you way Python 3 handles the Print command over Python 2, the result should see the helo.py file isn’t 9s we expected, Using Sublime For the moment, open the heliopy file EEED Coresnesemetsieastecotovie— EREERY sce stine rset rabery going oun enter theflovanginco the Pye gg to temporary eae the forthe ommend Ie rent and se Subline san evarpe that ou dort necessary need tose the Python OLE wth the hellopy open ater tt python3 hello.py include the Following This wil execute the code we created, which to remind you is pamenirpue omaeatspomnaie, ‘o="Python” print(“Hello,”, name) betist c="cool!” " print(a, b,c) FETED Naturally since this is Python 3 code, using the PEPAETP 2¥2 the heliopy fle and drop backto the syntax and layout that’s unique to Python 3, t only ‘commandline. Now execute the newly sa works when you use the python3 command. iFyoulike,ythe same code with: with Python 2 by entering python3 hello. py python hello.py The result wil with the a cisplay 3¢ the original Python is input command asking y in the command window. C) Hello, world Numbers and Expressions eRe eee Se aur eur eer ao un aCe sone ne a omer eri Cilaraieuceca tenure cnt cya uieer be cc ces cl CWRU LA Tenia ety PABST Colm en eel KeleR alent Um (OU Uo 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. EITEERED eer up the Guiversion of Python 3, as mentioned EREESEMM You can use all the usual mathematical operations: ‘you can use ether the Shell or the Editor. For the. divide, multiply, brackets and so on. Practise with a ‘ume being, you're going to use the Shelljustto warm our maths Few, For example: ‘muscle, which we believe isa small gland located at the back ofthe brain (or no) inthe Shel ene the flowing STEP 4 een Secial number In yeon these are cleats, ‘Ffloating point arithmetic. However, you need an integer as. ‘opposed to a decimal answer, then you can use a double lash: 2a 5435634553245 99867344927344484221 ‘You can see that Python can handle some quite large numbers C Numbers and Expressions Cl You can also use an operation to see the remainder left over From division. For exemple 10/3 Will display 3333333333, which is of course 3.3-ecurting, Ifyou now enter: ‘This wil display 1, which i the remainder leftover From dividing 10 into 3 This wil be displayed as 0b11, converting the integer into binary and adding the prefix 0b to the Front. Fyou want to remove the 0b prefix, then you can use: Format(3, ‘b’) “The Format command converts a value, the number 3, toa Formatted representation as controlled by the Format specification, the part FETT ext uo 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-tar on the keyboard 23, 10*10 Essentially, i's 2x2x2 but we're sure you already know the basics behind maths operators. Thisis how you would work tout in Python. Numbers and expressions don't stop there. Python has numerous builtin Functions to work out sets (of numbers, absolute values, complex numbers and a host of mathematical expressions and Pythagorean tongue-twisters. For ‘example, to corwert a number to binary, use: inca) Bee 4 2o0lean Expression i a logical statement that will, either be true or False, We can use these to compare data and test to see it's equal to, less than or greater than, Try this inanew6lle: a=6 b=7 print(l, a == 6) print(2, a == 7) print(3, a == 6 and b == 7) print(4, a == 7 and b == 7) print(S, not a == 7 and b == 7) print(6, a == 7 or b == 7) print(?, a == 7 or b == 6) print(8, not Ca == 7 and b == 6)) print(9, not a == 7 and b == 6) Execute the code from Step 9, and you can see a series of True or False statements, depending on the result of the two defining values: 6 and 7's an extension of ‘what you've looked at, and an important pat of programming. C) Hello, world Using Comments When writing your code, the Flow, what each variable does, how the overall program will operate and so onis all inside your head. Another programmer could follow the ere eM ec Ima cul cox lita eae #COMMENTS! Programmers use a method of keeping their code readable by commenting on certain sections. IF a variable is used, the programmer comments on what it’s supposed to do, For example. I's just good practi ESTESERD iztt by creating anew instance of the IDLE Editor IRIN esave the code and execute it. You can see thatthe (Fle > New Fe and create a simple variable and ‘outputin the IDLE Shells stil the same as before, print command: despite the extra lines being added, Simply put, the hash symbol (i) ‘denotes a ine of text the programmer can insert to inform them, CTC RENE ENE RURRISROEEO ‘and others, of what's going on without the user being aware. Save the file and execute the code, Fee Sal rr co FETED) erning the code will return theline: The value of A EAM Ler's assume that the variable Athat we've created is, 10into the IDLE Shell window, which is what we the number of lives in a game. Everytime the ‘expected. Now, add some ofthe types of 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: ss an (Using Comments Cl hist we know that the variable is lves, and that the 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 nes long instead of just our seven, You can see how handy comments are Essentially, the new code together with comments 17 # Set the start value of A to 10 0-10 # Print the current value of A print(“The value of A is,”, a) # Player lost a life! ona-1 # Inform player, and display current value of A lives) print(*You've just lost a life!”) printC*You now have”, a, “Lives left! You can use comments in different ways, For ‘example, Black Comments are a large section of text that details what's going on in the code, such as telling the code reader what variables you're planning on using # This is the best game ever, and has been developed by a crack squad of Python experts 4 who haven’t slept or washed in weeks. Despite being very smelly, the code at least # works really well. Inline comments ae comments that follow section 18 of code. Take our examples from above, instead oF inserting the code on a separate line, we could use: 010 # Set the start value of A to 10 print(“The value of A is,”, a) # Print the current value of A ‘o=a-1 # Player lost a life! printC*You’ve just lost a life!”) Print(*You now have”, a, “Lives left!”) # Inform Player, and display current value of A (lives) PEPER the comment, the hash symbol, can also be used to comment out sections oF code you dor't want to be executed in your program. For instance, iFyou wanted to remove the Fist print statement, you would use: # print(“The value of A is,”, a) fe set the start value of A to 10 Fran ane carent gal of A fe peinec*The value of A is. a fs Player loses life! bat ]#"intorm player. and display current value of A (lives) jJecinee"vourve just tose Tite!") Brint(-vou now have", a, "Lives Yeft!") You also use three single quotes to comment ‘uta Black Comment or multiline section of comments. Place them before and after the areas you want to comment for them to work: This is the best game ever, and has been developed by a crack squad of Python experts who haven? slept or washed in weeks. Despite being very smelly, the code at Least works really well. C) Hello, world Working with Variables We've seen some examples of variables in our Python code already but it’s always reuters cca na eater coe beat aecestcliy Retest urs VARIOUS VARIABLES. You'll be working with the Python 3 IDLE Shell IDLE Shell to clear up any old code. this tutorial. you haven't already, open Python 3 or close down the previous ERTESERD "some programming languages you're required = EBM Youve seen previously that variables can be to.use a dollar sign to denote a string, whichis 2 concatenated using the plus symbol between the variable made up of multiple characters, such as a name ofa person. variable names. In our example we can use: print Cname +: InPython ths isnt necessary. For example, inthe Shell enter: + title). The middle part between the quotations allows us to ‘nane="David Hayward? (or use your own name, unlessyou're adda colon and a space, as variables are connected without spaces, also called David Hayward). sowe need to add them manually. STEEP You can check the typeof variable in use by ED Youcnatso issuing the type () command, placing the name of combine variables the variable inside the brackets. In ur example, this would be: within another variable. For ‘type (ane). Add anew string variable: itle="Descended example, to combine both name and title variables into anew variable we use: “Then output the content of the new variables: Numbers are stored as different variables: hich, as we know, are integers. Working with Variables Cl ESTER However, you can't combine both strings and integer type variables inthe same command, a5 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, you get an error message: print (name + age) yeas tnt comert “in ebfet to Ea This presenta bt apoblem when you wantto 18 work with a number that's been inputted by the user a5 age +10 wont work dve to beng sting arabe and an Integer insted, you need enter: ‘int(age) + 10 ‘This wll TypeCast the age string into an integer that can be ‘worked with BTID) Thisis2 process known as TypeCasting. The Python codes print (character +“ is * + strCage) + “ years old.) oryou can use: print (character, “is, age, “years old.") Notice again that inthe last example, you don't need the spaces between the wordsin quotes asthe commas treat each argument to print separately >>> print (name ‘Traceback (nest File. " prant (character. "is". age, “Years old.) David Hayesrd: Deseended from Vikings is 44 years old. 2 ) all last): t line 1, in FEPTED arctier example of Typecasting is when youask for input From the user, suchas a name. for example, enter: ‘ages input (‘How old are you? “) Al data stored from the input command isstored as string variable fle Gat Shek Debug Oront wndows te Prihon 3.2 CGnfolt, oct 192014, T3TTY BERT When combining integers and floats Python Usually converts the integer to afloat, but should the reverse ever be applied it's worth remembering that Python doesn’t return the exact value. When converting a float to an integer, Python wil always round down to the nearest integer, called truncating; in our case instead of 19.99 it becomes 19. a FETTER the use of Typecasting is also important when dealing with floating point arithmetic; remember: numbers that have a decimal point in them. For example, enter: shint=19.99 Now enter typeCshirt) and youl se that Python has allocated the number asa float’ becausethe value contains a decimal point. eee python 34.2 (Oefoule, Get 19 2048, 13:3111) Meredits” or “License()* for nore information. ease aac ey clase *ficae’> Ss>"inecsnire) Ea -wora bdmpublicationscom C) Hello, world User Input AWE ola Ted erie a ee Ceee ALB eee Mikel MARL n lod Penn olacdatcle cian aan Cleary embetter ccna 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. ERED its not sready, open the Python 3 IDLE shell, and tart @ New File in the Editor. Let's begin with something really simple, enter ‘we want "Now that we have the user'sname stored in a couple of variables we can call ther up whenever BATERED See .2nd execute the code, and asyou alreadyno RWB fun the code and you can see aslightissue, the doubt suspected, in the IDLE Shel the program will full stop after the surname Follows a blank space. ‘ask for your fies name, storing itas the variable firstname, followed To eliminate that we can add a plus sign instead of the comma in bby your surname; aso stored in its own variable (curnare). the code: You don't always have to include quoted text within the input command. For example, you can ask the user their name, and have the input inthe line below: serinput py - /home/pi/Documents/Python Code/ust hats your nane?") fhane=input() FETED 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, uuythis: Sie Esk Faymat Bin Gens windows Hee peerbmates BETIED t's 2.000 starctoa text adventure game, perhaps? Now you can expand onit and use the aw input from the use to flesh out the gamea ltl: Se (2 at Fam Bn airs wom jE Gomme What you've ctested here sa condition, which we will cover soon. In short, we're using the input from the user and measuring it against a condition. So, ifthe user enters David as their name, the guard will allow them to pass unhindered Else, iFthey enter aname other than David, the guard challenges, them toa fight. Sia PEPE DD us:esyou teamed previous, any input froma ‘seris automatically a string, soyouneed to apply a “TypeCastin order to turit nto something ese. This creates some interesting aditions tothe input command. For example: Oiag ‘Save and execute the code and enter some numbers. Using the Float(input element, we've told Python that anything enteredis Floating point number rather than a string, “To finalise the rate and distance code, we can ade: seinen Hello, World Creating Functions INCH aE ToL A Muar Eicigre Ran MUS Moi UAr-) >) (CM NOR CSM a) oe eR a Mn cect CoM eLed LUT Celufo Dato CoN A Vel Keel ek McA aan OTe Cae CoOL RLU LAY aaron) enables you to define your own functions. FUNKY FUNCTIONS A function ‘works on it and then returns the result, ‘a command that you enter into Python to do something. sa little piece of self-contained code that takes data, Is not just data thata function works on. They can doall manner of useful things in Python, suchas sort data, change items from one formattto another and check the length or type oF items, Basically, a function isa short word that’s Followed by brackets, For example, len0, list or typeO). ESTEE 8 function takes data, usually a variable, works on it depending on what the Function is programmed todo and returnsthe end value. The data being worked on goes Inside the brackets, so if you wanted to know how many letters are in the word antidicestablishmentarianism, then you'd enter: ‘Len¢“antidisestablishnentarianisn”) and the number 28 ‘would return, PETISEDD vou can pass variables through Functions in much the same manner, Let's assume you want the number of letters in a person's surname, you could use the following code (enter the text editor for this example) Press FS and save the code to execute it. Siar Python has tens of Functions built into it, far too ‘many to get into inthe limited space available here, However, to view the list of built-in functions available to Python 3, navigate to www: docs.python.ora/'/lbraryfunctionshtml. These are the predefined Functions, butsince users have created many ‘more, they're nat the only ones availabe. © Creating Functions Cl ma octet ‘Once entered, you have access toll the Math module Functions. You can see that the code s presented as module function(data. mma FORGING FUNCTIONS eu nse a rnreUMh rena iead Be ieee eae I Me CUE Kas AEs NMS celui STEP1 7 Mgr STEP3 epee Rear cae ese epeaisenre fdef_Hello():} B print Ciel tony rom Hello import Hel fielloOy fielloCDavid™)} Ese ress F5to save and execute the code, PD 60: 101 expand the function to accepts STEP 4 Yueeeee a eae Eas pon Gs Meee: Cate amie hes ee Tsuen “This will now accept the variable name, otherwise it prints Hel eee rea aay ee Oe C) Hello, world Conditions and Loops Conditions and loops are what make a program interesting; they can be simple or rather Reds Ma Vettecteneut caterer MUR E aie l cc eilcy they could be the number of lives left in a game orjust 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. ESTESERD c's create anew Python program that wll ask BEPED ow you can use aif statementto check ifthe the user to input word then checkit to see it’s word length variable sequal to Four and print a a foucletter word ornot. tart with Fie> New File, and begin with friendly conformation fit apples to the ul: the input variable: PETTSE RD ow we can create anew variable, then use the len EERE the colon at the end of tells Python that if this Function and pass the word variable through it to statement i true do everything after the colon ‘get the total numberof letters the user has just entered: that's indented, Next, move the cursor back to the beginning of the Editor piesa oo ( Conditions and Loops Cl PRPTIDD Press 5 and savethe code to execute't. Enter Bee Mow expand the code to include another conditions. a Fourdetter word in the Shell to begin with, you Eventually, tcould become quite complex. We've should have the returned message that's the wordisfour letters. added a condition for three-letter words: Now press F5 again and rerun the program but this time enter a five-letter word, The Shell wil display that it's not aFourletter word, nord=input(“Please enter a four-letter word: “) nord_length=LenCword) if word_length = 4: print (nord, “is a four-letter word. Well done.”) elif word length print (word, “is a three-letter word. Try again.) else: print (word, “is not a four-letter word.") LOOPS ‘Alo0p looks quite similar to 2 condition but they are somewhat different in their operation. A loop will run through the same black of code a number of times, usually with the support oF a condition, I 60 < tart with asimple while statement, users, PPIEM he For loop i another examole. Faris Baer eerie CGC arenes Tee age = prordse[*Cat®. “Dog®, “Unicorn PEG print Tword) PEPPER the citterenceberweenitandwhleicwnenvhie IM the Forloop ca Le ‘ ei Eines Cem is sagt tas Z pyre Me print Gy Be gia The koa partisnic needed here because the range f ee eae BE) sto,wora Python Modules We've mentioned modules previously, (the Math module) but as modules are such a large part of getting the most from Python, it’s worth dedicating a little more time to Ten eRe eR ACM aren MaMa RESON Kea shone 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. thin python BRTEIEYD Te esutisan aor intel OLE se, asthe ygame module isnt recognised or installed in Although good, the bitin function BARD aetited the vse of ;o make more sophisticated programs. As you ‘are Python scripts that are imported, such asi pip install pygame SEED ress ne example. Sadly, other modu! example on non-Piplatformeis the Pygame module, Run as Administrator, Linux. y Functions to help create games. Try: import pygame. can use the Suda command, with sudo pip install packag} ED vw vsmouricatonscom Close the command prompt or Terminal and relaunch the IDLE Shell. when you now enter: ‘import pygane, the module willbe imported ita the code without any problems. Youll find that most code downloaded or copied from the Internet will contain a module, mainstream of ‘nique, these are usually the source of errors in execution due to them being missing, a ( (Python Modules Cl ESTEE) Mutiole modules canbe imported within your code. Toextend our example, use: import random import math for I in range(s): printCrandom.randint(1, 25)) printGnath.pid fe = ‘The madules contain the extra code needed to achieve a certain result within your own code, as ‘we've previously experimented with. For example: ‘import random Brings inthe code from the Random Number Generator module. You can then use this module to create something like: for i in range(10): print(random.randint(1, 25)) This code, when saved and executed, will display ten Rice random numbers from 1 to 25. You can lay 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)) The results string of random numbers Followed Sia by the value of Pas 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, suchas: from random import randint for i in range(S): print(randint(1, 25)) a = Thishelps create a more streamlined approach to STEP 10 programming. You can also use import modules, ‘hich willimport everything defined within the named module. However, it's often regarded as a waste of resources but it works nonetheless. Finally, modules can be imported as aliases: import math asm print(n.pid OF course, adding comments helps to tell others what's ging on, Daten avian mie =a x [aoeee 4 Hello, World Python Errors It goes without saying that you'll eventually come across an error in your code, where keer ene elon kona itemise korean Paes cele cnn eur coor t tl ie eid DEBUGGING Errors in code are called bugs and are perfectly normal. They can often be easily rectified with thing isto keep looking, experimenting and testing. Eventually your code will be bug fre: Code isnt as uid asthe written word, no matter Thankfully Python is helpful when it comes to how good the programming language is. Python is displaying error messages. When you receive an certainly easier than most languages but even tisprone tosome error in redtext From the IDLE Shel.it will define the error tse annoying bugs. The most comman are typos bythe user and whist along with the line number where the error has occurred, Whilst in ‘easy to find in simple dozersline code, imagine having to debug the IDLE Editor this isa litle daunting For lots of code; text editors ‘multethousand line code, help by including line numbering. oS Be SS Precise Sy S) eee ieee o ESSER The most common of errorsis the typo, as we've ESTEE Sv2taxerrors are probably the second most ‘mentioned, The typos are often at the command ‘common errors you'll come across asa programmer level mistyping the print command For example. However, they also Even ithe spelling is correct, the actual command itselfs wrong, ‘occur when you have numerous variables al of which have lengthy In Python 3 ths often occurs when Python 2 syntaxes are applied. ‘names. The best advice isto simply ga through the cade and check The most annoying ofthese's the print function. n Python 3 we use your spelling print(“words"), whereas Python? uses print "words". te at thd pg ton undo web a “etna tt me stent, ig ag” eee fr me itt (python Errors Cl Pesky brackets are also a nuisance in programming BED 1 epecaly when ouhave something tke print (balanced_checkCinput©)) Remember that for every there must be an equal number of 1 sagort aye 5 ede batanced enech ata * : 2 2 3 Je caaracter in reference. tea) i ‘ek open chracter) x Piette geen) t= racer EETeeE DD 22 excellent way to check your code step-by-step isto use Python Tutor’s Visualise web page, found at www-pythontutor.comvisualze html¢made=edit. Simply paste your code into the editor and clckthe Visualse Execution button torun the code line-by-tine, This helps to clear bugs and ‘any misunderstandings. ESTED There are thousands of online Python resources, code snippets and lengthy discussions across Forums ‘on how bestto achieve something, Whilst 99 per cent of tis good ode, don't always be lured into copying and pasting random code into your editor. More often than nat, it won't work and the worst partis that you havent learnt anything, Indents are a nasty part of Python programming that a lot of beginners fal foul of Recall the f loop from the Conditions and Loops section, where the colon means ‘everything indented Following the statement isto be executed as, Long as it’s true? Missing the indent, or having too much of indent, will come back with an error. PEED Penning makes for good code. whilst aitle old school it's 8 goad habit to plan what your code ill do before sitting down to type it out List the variables that will be used and the modules too; then write outa script for any user interaction or outputs, Purely out of interest, the word debugging in computing terms comes from Admiral Grace Hopper, wha back in the ‘40s was working on a monalithic Harvard -Markillelectromechanical computer. According to legend Hopper Found a moth stuckin a relay, thus stopping the system from ‘working, Removal of the math was hence called debugging z=» Hello, World Combining What You Know So Far PCR Conte Ro mee enn rod ete Ce Tue uae keonu a Lae) we've looked at so far, and apply it to writing a piece of code. This code can then be eee Nea CLect ice ciaca eee k on PLAYING WITH PI For this example we're going to create a program that will calculate the value of Pito a set number of decimal places, as described by the user. It combines much of what we've learnt, and a little more. ESTISERD st2:¢by opening Python and creating a New Filein [ERISWM the previous step defines the rules that make the Editor Fist we need to get hold of an equation upthe algorithm and creates the string that will that can accurately calculate Piwithout rendering the computer's eventually display the value of %, according the Chudnovsky CPU useless For several minutes. The recommended calculation _brothers' algorithm. You have no doubt already surmised that it Used in such circumstancesis the Chudhovsky Algorithm, you ‘would be handy to actualy output the value ofPito the screen. To, can find more information about it at en:wikipedia.org/wiki/ rectify that you can add CChudnovsky_algorithm, prtneceanecaype You can utilise the Chudnovsky Algorithm to create BAD Yo. cur Python script based onthe calculation. Ragga) Youcen save and execute the code at this pointif you like. The output will print the value of Pi to 27 Begin by importing some important modules and functions within Grima laces: qaisezusss@sTs4so7eseassser wise precy Coe impressive on its own, you want some user interaction to ask the From decimal inport Decimal, getcontext User 2s to how many places Pishouldbe calculated, “This uses the decimal and getcontext Functions From the Decimal You can insert an input line before the Pi calculation ‘module, both of which deal with large decimal place numbers and DeF command, It needs to be an integer asi will naturally the Math module. otherwise default toa string, We can callit numberofdigits and use scram escusten 2507 the getcontext Function: Now you can insert the Pi calculation algorithm part ofthe code. Thisisa version of the ‘Chudnovsky Algorithm: © Combining What You Know So Far Cl FRPTSEMD You can execute the code now and task the user how many decimal places they want to calculate to, outputting the result in the IDLE Shell. Try it with 1000 places bt dont go too high or else your computer willbe locked up in calculating Pi, Part of programming is being able to modify code, making it more presentable. Let's include ‘anelement that times how long ittakes our ‘computer to calculate the Pi decimal places, ‘and present the information in a different colour. For this, drop into the command tine and impart the Colorama module (RPI users already have it installed) pip install colorama Tofrishourcode,we need ohnitlse the se? dy Colorama module and start the time Function at the point where the calculation start, and when it finishes. The end result is a coloured ink displaying how long the process took (in the Terminal or command line from decimal import Decimal, getcontext ‘import math import time import colorana from colorana import Fore colorana. initO nunberofdigits = intCinput(“please enter the nunber of decimal places to calculate Pi to: “)) getcontext().prec = nunberofdigits start_time = time.timeQ) def cale(n): ETeEE DD Mowe need to import the Colorama module (which will output textin jours) along with the Fore function (which dictates the foreground, ink, colour) and the Time module to start a virtual stopwatch to see how long ‘ur calculations take: import time import colorana from colorana import Fore Decimalca) pi = Decimal (a) deno = Decimal (0) k=0 for k in range(n): t = (ecimal(-1)**K)*Cnath. factorial (Decimal (6)*k))*(135914094545140134"K) deno = math. factorial(3*k)*(nath. Factorial (k)**Decimal(3))*(640320"*(3*k)) pi_ += Decimal(t)/Decimal(deno) pi= pi * Decimal(iz)/ Decimal (640320*Decimal(1.5)) pi = Voi return str¢pi) print¢catc(1)) print(Fore-RED + “\nTime token:”, time.time() - start_time) vevoubdmpublationscom Python in Focus: Stitching Black Holes One of the biggest scientific, engineering and space-based projects came to a head in 2019, revealing humanity's First glimpse at the universe's most elusive object: a black ems aN eTer eel oke Nea ay area UY Dea eee Gr a ee) in curved spacetime predicts that event horizons emit Hawking Oe eee ea fede ee ee eee eeu rd re ae Ce a ee ta ee ue iene io oe mms Sa Ce ee ee Cee en See eta electromagnetic radiation suchas light—can escape Fromit. The _Notthat long ago a black hole was jst a collection of theories : theory of general relativity predicts that a sufficiently compact mass and mathematics written down on paper, speculated only by the F can deform spacetime to Form ablack hole. The boundary ofthe brightest minds of our time. However, as with most things scientific, region From which no escape is possibleis called the eventhorizon. ur understanding of the universe and our abilities to ead ithave ‘Although the event horizon has an enormous effect on the ate and greatly improved and, withthe culmination of years of Circumstances ofan object crossing it, no locally detectable features hard work by a collaboration of observatories, peterson tne creas en Senne ett See eee eet ea ee) EVENT HORIZON TELESCOPE ‘One ofthe problems regarding the imaging of such an objects angular resolution. In Astronomy, the size of the objectsin the night eR eg ee cd Rt et) that describes the size of an angle in degrees, designated by the eee ee ere eect 90". One degree can be divided into 60 arcminutes (abbreviated 60 arcmin or 60). An arcminute can also be divided into 60 areseconds Set once) For example, looking atthe moon, whichis roughly 31 arcminutes, imagine drawing alin from you to one side of the moon and Nee eee ed ‘wo lines is the angular size, or angular resolution SO eee od De ea es ee Le es size of 40 microarc seconds, or one milionth ofan arcsecond. So, Ce er etal See eee is ‘This is where the Event Horizon Telescope project comes into play eee eee eer teres take images of the black hole over a period of around six months, Critically timed, using atomic clocks, the telescopes imaged the area ene ee ety eee cere ec? BIG DATA AND PYTHON Me oe eee oc eo tune of over athousand hard drives, which came to an astonishing 5 eee eon) into a workable Form and presenting it as an image. Peete eae Poe entep ey uA eT Python code that was able to stitch BIC ere entry Cet ensue ee Ce eT Cee Se easy Pe eee ta tec es ORS ee cu aD Se ce a eae cof the MB7 galaxy thats surrounded by a ring of burning gasses. The ete et ure acne) also state give ita couple of years and theyll be able to increase the Image resolution significantly. nee ease ens erecta LC) index Working with Data Yorking with Data Data is everything; it can topple governments, change election results, and tell us the secrets of the universe. ‘Over these coming pages we look at how you can create lists, tuples, dictionaries and multi-dimensional lists, and then how you can use them to forge exciting and useful programs. In addition, you will learn how you can use the date and time functions, write to files to your system and even create graphical user interfaces that will take your coding skills to new levels and into new project ideas. Opening iting to Files Exception: thon Graphics smbining What You K ython in Focus: Gaming @) Working with Data Lists Lists are one of the most common types of data structures you will come across in POA ra eral cid eu ec at e Cn unseni recor) as a whole, or individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include functions in lists, and lists within lists. Alistisa sequence of data values called items. You ED co. tre rare of your ct Followedby 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”, FETTER) (Xe you've defined your list you can call each byreferencing itsname, followed by a number. Lists star the first item entry as 0, followed by 1,2, 3 and soon, For example: unbers To callup the entire contents ofthe lst. ‘unbers(3] Tocallthe third from zero item inthe lst (21 in this case), Youcanalsoaccessorinde,thelatitemina ist by EPs ‘using the minus sign before the item number [1], or the second to last item with [-2] and so on. Trying to reference an item that isn’t in the list, such as [10] will return an error: rumnbers{-11 mythical_creatures[-4] ESTEE icing is simitarto indexing but you can retrieve ‘multiple tems in alist by separating item numbers with a colon. For example: runbers [1:3] Willoutput the 4 and 7, being item numbers 1 and 2. Note that the returned values don't include the second index pasiton (as you ‘would numbers[1:3] to return 4, 7 and 21). You can update items within an existing list, remove items and even jon sts together. For example, to you can use: jointwo everything = nunbers + mythical_creatures ‘Then view the combined list with: everything PPT ers can be added toa ist by entering numbers=numbers+[201] Or for strings mythical_creatres=nythical_creaturess[“Griffin”] (Or by sing the append Function: ythical_creatures.append(“Nessie”) ruber .append(278) Removal af tems can be done in two ways. The First Rice Isby the tem number: del nunbers[7] ‘Alternatively, by tem name: mythical_creatures. renove“Nessie”) Youcanview what canbe done wth sts by entering 18 dir(list) into the Shell. The output is the available functions, for example, insert ne pop ar seo ad and remove Rems at etan postions. To sett the mumber 62 et ke index numbers. insert(4, 62) Toremovet numbers .popC4), PEED vou also use the list Function to breaka string down into its components, For example: ‘List(“Devia") Breaks the name David into’D,, 3, toa new ist: ‘¢.Thiscan then be passed nane=list(“David Hayward”) ame age=[44] user = nane + age PETTET DD 22:2¢ on that, you can create a program to store someone's name and age asa lit: amesinput¢‘What’s your nane? “) Inane=listCnane) ‘agesintCinput (“How old are you: “)) ‘ages[age] user = nae + Lage ‘The combined name and age lists called user, which canbe called by entering user int the Shell Experiment and see what you can do, @) Working with Data Tuples BO) FTN a mune s(n e(e-1 Meo eA RD eMC Ke-] AB OLA) Lele ce elle Kol changed in some way, a tuple remains a constant. This is called immutable and they're Peuceauncm ich etic THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the program is intended to do. Normally, atuple is reserved For something special but they're also used for example, in an adventure game, where non-playing character names are stored. Atupleis created the same way as list butin this EED You can create grouped tuples into lists that contain SED isconceyou ce cuvedbracetsinteed oF sauare MMMMMRAD tile sets oF data rorintance, here's tuple brackets, For example: called NPC (Non-Piayable Characters) containing the character name months=C“January”, “February”; “March?y “Aprit”,, 2nd theircombat rating For an adventure game: “May”, “June”) NPC=[C*Conan”, 100), C“Belit”, 80), (“Valeria”, months 959] ‘ie Ea Soh Rn Stes who Ea oo) Quy Ss wn FETTER ust aswith ists, the tems within named tuplecan ETA cach of these data items can be accessed asa be indexed according to theic postion inthe data whole by entering NPC into the Shell or they canbe range, Le. indexed according to their position NPC[O. You can also index the an individual tuples within the NPC lst: mmonths[5] Nectey1] However, any attempt at deleting or adding to the tuple willresult Will display 100. in an error in the Shell Tes woth noting that when referencing mule Sua?5 tuples within a list, the indexing is slightly different. from the nom. You would expect the 95 combat rang othe character Valeria to be NPC[4][5], but it's not. It's actually: NPCc2]01] | ast Eg ts no FEST) This means of course that the indexing Follows thus: @ ya o 2 a1 20 1 2a 1,0 Which as you can imagine, gets ate confusing when you've got a lot of tuple data to deal wth, [eo FETS SED Teples though utilise a feature called unpacking, where the data items stored within atuple are assigned variables First create the tuple with two items (name and combat rating) NPC=¢*Conan”, 100) PEED ow unpack the tuple into two corresponding variables: name, conbat_rating)=NPC ‘You can now check the values by entering name and combat. rating, | oe et am ones we ESTER Remember, as with lists, you can also index tuples sing negative numbers which count backwards From the end of the data list. For our example, using the tuple with multiple data items, you would reference the Valeria character with BRET vou can use the max and min functions to Find the highest and lowest values ofa tuple composed of rumbers. For example: rumberss(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(maxCnunbers)) print CminCnunbers)) YT z= Working with Data) Dictionaries Lists are extremely useful but dictionaries in Python are by far the more technical way of dealing with data items. They can be tricky to get to grips with at first but you'll soon Pee aMule ces KEY PAIRS ‘A dictionary is ike a list but instead each data item comes as a pair, these are known as Key and Value. The Key part must be unique and can either be a number or string whereas the Value can be any data item you like. Lecseyounonttocenteaotentcacnryton ETRE sew ste anus youcan check thecorets Su You would create the dictionary name and enter Sues) of a 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 in a similar Fashion to a list, which you're no doubt familiar vith by nov. phonebook={“Enma”: 1234, “Daniel”: 3456, “Hannah”: PEPER 2s with mos ists, tuples and so on strings FEID te benefit of using a dictionary isthat you need be enclosed in quotes (sinle or double), caneenterthekey to index the vale. Using the \whilstintegers canbe left open. Remember thatthe value can be phonebook example from the previous steps, youcan enter: ether a tring or aninteger, you just need toenclase the relevant : Sennen phonebook “Enna” ‘one in quotes: honebook[“Hannah") phonebook2={“David”: “0987 654 321”} r (. Dictionaries 4 ‘Adding to a dictionary easy too. You can include ‘a new data tem entry by adding the new key and value items ike: phonebook{“David”] = “0987 654 321” phonebook Net you need todefine the vserinputs and 18 variables: one for the person's name, the other forthelephone number le’ keep simple to avid lengthy Python code): name=input“Enter_name: “) nunber=intCinputC*Enter phone number: *)) FETT You can also remove items from a dictionary by Issuing the del command Followed by the item's key; the value willbe removed as well since both work asa pair oF data tems: del phonebook[“David"] PRPPIE DM Taking this astep further, how about creating a piece of code that will ask the user forthe dictionary key and value tems? Create a new Editor instance and start by coding in anew, blank dictionary phonebook={} Note we've kept the number as an integer instead ‘of a string, even though the value can be both ‘an integer ora string. Now you need to add the user's inputted variables to the newly created blank dictionary. Using the same process as in Step 5, you can enter: Phonebook[nane] = nunber fonts = er PRTTSETBD Now when you save and execute the code, Python willask fora name and a number. e wil then insert those entries into the phonebook dictionary, which you can test by entering into the Shell phonebook Phonebook[*David"] IF the number needs to contain spaces you need to makeitta string, ‘so remove the int part ofthe input. z= Working with Dati Splitting and Joining Strings AT Kel lat R eae eM aM aoa Cel NACE emo URNTI AU are ole cel Ny 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. ESTEE The main toolin the string Function arsenatis.spit(). [ESTEEM Note thatthe text split part has the brackets, With you'r able to spit aparta string of data, quotes 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 list string with three items, each separated by a space item entryis separated by a space. Likewise, CSV (Comma Separated Value) content has a comma, so you'd use: text="January, February,March,April May, June” months=text. split(*,") months ‘text="Daniel Hannah Enna” PEPER iow let'sturn the stringintoa list and splicthe PEPPPR Youve previously seenhow you can split string content accordingly: into individual letters as alist, using a name: nanesstext.-split “) name=list(*David”) rane Then enter the name of the new list, names, to see the three items. ‘The returned value is‘, ‘av, 7, Whitt may seema little Useless under ordinary circumstances, t could be handy for creating a spelling game for example. The opposite of the split Functionis join, where ‘you will have separate items in a string and canjoin them all together to form a word or ust a combination of tems, depending on the program you're writing. For instance: This will display ‘abcde’ in the Shell joint eee ee rman ‘As with the split function, the separator doesn't 8 Sue? have to bea space, it can also be a comma, a full stop, a hyphen or whatever you ti You can therefore apply jon to the separated name you made in Step 4, combining the leters again to Siar formthename: ‘We've joined the string back together, and retained thelist called ‘name, passing it through the join Function, Sid sentence: ‘A good example of using the join Function is when ‘you have alist of words you want to combine into a "Note the space between the quotes before the join Function (where there were no quotes in Step 6's join). ‘There's some interesting Functions you apply to 8 string, such as. capitalize and title For example: STEP ‘Youcan ao use ag operators on tng, SIEtALo ‘with the ‘in’ and ‘not in’ functions. These enable you to check fa string contains (or does not contain) a sequence ———— z= Working with Data) Formatting Strings When you work with data, creating lists, dictionaries and objects you may often want Rrunead nt ee ore M ane eee Rear Matar PCa Iam ana cekekeoulelauracs 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. Thebaicowatginhyhonstocaecs —— ERRERE YouencFouse akong eather Su variable into the string using the curly brackets: Sues) unber=10000 ane="Conan” printC*{} of {} was a skilled mercenary, printC*The barbarian hero of the Hyborian Age is: and thief too. He once stole {} gold from a "format name)) merchant..”.format(name, place, nunber)) FETTER Remember to close the print function with two sets RAAB there are many different ways to apply sting 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 tring Formatting isthe Python Docs webpage, ame="Conan” a Found at www.docs pythan.org/3.1ibrarystring html. Here, you printC“{} hailed from the North, in @ cold land Wilindétonsof hein. known as {}”.format(nane, place)) 7 Fe ting St ¢ oO Zz \ ‘ormatting gs Interestingly you an reference alist using the sting Sua?5 Formatting Function. You need to place an asterisk in front ofthe ist name: nunbers=1, 3, 45, 567546, 3425346345 print(*Sone numbers: (3, 0, , 0 O- format C*nunbers)) FEED with indexing in sts, the same applies to caling a list sing string Formatting, You can index each item ‘according tots position (From Oto however many are present} nunbers=1, 4, 7, 9 print(*More numbers: {3}, {0}, {2}, {1}.”. format (*numbers)) ue Ea oh tg ene wn PPE nc as you probably suspect, you can mixstrings and integersina singe list to be called in the Format Function characters=[“Conan”, “elit”, “Valeria”, 19, 27, 20) print C“{0} is {3} years old. Whereas {1} is {4} years old.”. format(*characters)) BETTER) You can also print out the content ofa user's input in the same Fashion ame=inputC“What’s your name? “) print(*Hello {}.".formatCname) ‘You can extend tis simple code example to display the frst leter in a person's entered name: name=inputC“What’s your name? “) printC*Hello {}.”.format¢nane)) Iname=List(name) print(“The first letter of your nane is a {0}”. format¢*Inane)) BERT You 20 also call upon a pair of lists and reference them individually within the same print Function, Looking back the code from Step 7, you can alter it with: names=[“Conan”, “elit”, “Valeria”] ages=[25, 21, 22] Creating two lists. Now you can call each list, and individual items: printC*{0[0]} is {1[0]} years old. Whereas {O[1]} is {1[1]} years old.”.format(nanes, ages)) ora vémpublications com z= Working with Data) Date and Time aN en Or Rane Netoicun en Mee cease cu ACR TT Docu E nce arated ere ns ues Com M Ree inure ilu eeomccn aL ts 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. ED syeseirpne meen ene ‘import time ‘time asctimeC) Ree ESTESER The time Function s spit into nine tuples, these are divided up into indexed items, as with any other tuple, and shown in the screen shot below. 5 secon 0106 (60 or 61 ae eap-seconds) © Dayot week 0106 (01¢ Mondo) 7 pavotyear 1 t0 366 tan cay © Deyo savnge 1, 0,2, -1 means trary determines OST ora vmpublications com You canseethesrudurofhowtines presented em byentering: time, local time@) ‘The outputis displayed as such: “time, struct timeCtm. year=2017, tmmon=9, tmmday=7, tm_hour=9, ‘tmmin=6, tm_sec=13, tmnday=3, tmyday=250, tm ‘isdst=0)’; obviously dependent on your current time as opposed tothe time this book was written. ESTEEM Tere are numerous functions built nto the Time modile. One of the most common of these is. strftime(. With it, you'e able to present awide range of arguments ‘sit convert the time tuple into a string For example, to dsplay the current day ofthe week you can use: ‘time. strftimeC‘KA") seas a TT Cason Thisnatrally means you can incorporate various FR vou sow atthe end ofthe previous section, nthe SMD frcionsinco your own code schos Sc t>colcate rico however ony decal laces the vers wanteé you can ime a particular event in Python, Take the code from above and alter slghtly by nuding start_tine=tine. tine Then there's eet tte ect FETEEEERD Note the ast two entries, with %H and %H%M, a5 EATER The output will ook similar to the screenshot below. you can see these are the hours and minutes and as. ‘The timer Function needs tobe either side ofthe the last entry indicates, entering them as %H¥6M doesnt display the input statement, as that’s when the variable name is being created, ‘ume correctly in the Shell. You can easly rectify this with: ‘depending on how long the user took to login. The length of time is then dsplayed on the last tine ofthe code asthe endtime variable. STAD TaNaSN te login te thir cet This means you're going to be able to display “There's lot that can be done with the Time either the current time or the time when ‘module; some of tis quite complex to, such as something occurred, such as a user entering their name. Try ) » FETTER You can use exceptions to handle a variety of useful tasks, Using an example From our previous tutorials, let's assume you want to open ail and write toi try: ‘txt = open(“/home/pi/Documents/textfile.txt”, “r”) txt.writeC“This is a test. Normal service will shortly resune!”) except I0Error: print (“Error: unable to write the file. Check permissions”) else: print (“Content written to file successfully. Have a nice day.”) ‘txt.closeQ) Obviously this won't work due to the file textile tutbeing opened as read only (the part). Soin this case rather than Python teling you that you're doing something ‘wrong, you've created an exception using the |OErrar class informing the user that the permissions are incorrect. as yu already know, wil create the file and write the content then commit the changes to the file, The end resut wll report a different set of circumstances, in this case, a successful execution of the code. Naturally, you can quickly Fix the issue by changing the “read only instance with a“w' for write. Ths, FETTER You can also use a finaly: block, which works in a similar Fashion but you cant use else with lt. To use cur example From Step 6 try ‘txt = open"/home/pi/Docunents/textfile. txt", “r”) try: txt.write(“This is a test. Normal service will shortly resume!") finally: print (“Content written to file successfully. Have a nice day.") ‘txt.closeQ) except I0Error: print (Error: unable to write the file. Check permissions”) ‘As before an error will accur as you've used the '*reacronly permission. Fyou change ittoa"w", then the code will execute without the error being displayed inthe IDLE Shell. Needless to say, it can be a tricky getting the exception code right the firs time. Practise though, and you wil get the hang oft. z= Working with Data) Python Graphics While dealing with text on the screen, either as a game or ina program, is great, there MU em aue lease ice uke ites een Tn eee Medien Licentiate GOING GRAPHICAL You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available, to bring out some spectacular effects. near thedex goncimowiestobean tering TREE Theccmnante cient cove lanl Python graphics is Turtle. The Turtle module is, as Sues) circle on the screen, with 50 being the size. You the nameausoests seson he tre rootsed nary s5008,canpay around th hese ute gong up 0100130 and that can be programmed to draw something ona large piece beyond: you can draw an ar by entering: turtle. circle(SO, ‘of paper on the Floor. The Turtle module can be imported with 180), where the size is 50, but you're telling Python to only draw ‘import turtle. 180° of the circle, Ege acc wn mn FETTER Let's beainby drawing a simple circle. StataNew — AAV the last part ofthe circle code tells Python to keep File, then enter the following code: the window where the drawing staking place to remain open, so the user can click ta close it. Now, let's make a square: ‘import turtle turtle. circle(s0), — turtle. getscreen()._root.mainloop() print(*Drawing @ square..”) ‘As usual press 5 to save the code and execute R.Anewwindowwil for t in rangeC4): now open up and the ‘Turtle’ will draw a circle. turtle. forward(100)_ (Python Graphics Cl FETSEEERD You can add anew tine tothe square code to add some colour: turtle. colorc“Red”) ‘Then youcan even change the character to an actual turtle by entering turtle. shapeC*turtle”) You can also use the command turtle. begin_ALLO, and turtle. end_f110 tofillin the square withthe chosen colours; ‘ed outline, yellow ili this case PRED Now let's get the code by importing the Pygame module: ‘import pygane pygane.init©) ‘img = pygame. image. LoadC*RPi .pna”) white = (255, 255, 255) w= 500 eT h= 450 fee ‘screen = pygame.display. [astern eran setnodeccn, h)> screen. fill(Cvitite)) screen. fill(viite)) screen. bliting, (0,0) Pygane. display. fiipC) hile True: for event in pygane.event.get(): if event.type = pyoame QUIT: You can see that the Turtle module can draw ‘out some pretty goad shapes and become alitle ‘more complex as you begin to master the way it works. Enter this example: from turtle import * | color¢‘red’, ‘yellow’ begin ALLO) while True: forward(200) Leftc170) if abs(pos()) < 1: break end ALLO doneQ) lesa different method, butvery effective, Another way in which you can display graphicsis by using the Pygame module. There are numerous ways in which pygame can help you output graphicsto the screen but For now let's look at displaying a predefined image. Start by ‘opening a browser and finding an image, then save itt the Folder ‘where you save your Python code. pygame.quitC, Inthe previous step you imported pygame, nated Su) the pygame engine and asked it to import our saved Raspberry ogo mage, savedasRPLpng,Nestyou ded the Dackoround colour ofthe window to sly the mage andthe window sea pe the actual mage mensions Fal you havea loop cose the window w = 900 h = 450 screen = pygame.display.set_mode((w, h)) screen. fill¢(white)) screen. fill((white)) screen.blit(img,(0,0)) pygame. display. flip() while True: for event in pygame-event.get(): if event.type == pygame. QUIT: pygame.quit() PEPSI css 65 to save and execute the code and your image willbe displayed in a new window. Have a play around with the colours, sizes and so on and take time to look Up the many functions within the Pygame module too. — \aspberryPi z= Working with Dati Combining What You Know So Far Based on what you've looked at over this section, let’s combine it all and come up with a piece of code that can easily be applied into a real-world situation; or at the very Eeneeou een hen atkeu acc ee nck tinier eas LOGGING IN For this example, let's look to a piece of code that creates user logins and then allows them to log into the system and write the time they logged in at. You can even include an option to quit the program by pressing'a’. PEPER 2xin by importing the Time module, creating FETED the olobalstatus statement separates a local ‘a new dictionary to handle the usernames and variable From one that can be called throughout passwords and creating a variable to evaluate the current status of the code, this way you can use the q=quit element without itbeing the program: changed insde the Function, We've also referenced some newly oe defined Functions: oldUser and newUser which well get to next. users = {} i maa status =“ ESTER the newuser Functions next: def newserO: PEPER Next you need to define some functions. You can _—_ereateLogin = input(“Create @ login name: “) begin by creating the main menu, where all users will return to after selecting the available options: idicrentsLon Me sas print C*\nLogin name already exists!\n") def mainMenu(): else: global status createPassw = input(“Create password: “) status = input(“Do you have a login account?, users[createlogin] = createPassw y/n? Or press q to quit.”) printC"\nUser created!\n”) if status == “y": Logins=open(“/home/pi/Docunent's/Logins.txt”, oldUser() a") elif status = “n Logins.writeC*\n” + createlogin +“ “ + createPassn) Togins.closeC) “This creates a new user and password, and writes the entries into a file called logins, Combining What You Know So Far Cl PEPER You willneed to specify your own location forthe = PIM Finally, youneed to continually check thatthe ‘¢'key cerepeaiiog sagem neegeam sree pie tata = . status = displayMenu() resteLogin = snputc"create 2 login mane: “> i hasn't been pressed to exit the program, We can do At GSPENECCankagin hone already exists!\ar) Stettler tt Fogin-opnt/hcse'p roncments login. tnt", ogane neitec-r" + eresecagan + 8s ereatePaten) Ioging closet) PPR ov to create the oldUser function | pxcasoetenees 5 def olduserO: login = inputC"Enter login name: “) assw = inputC“Enter password: “) # check if user exists and Login matches i“ password if Login in users and usersflogin] == pass: print C“\ntogin successful!\n") oleate" ena) print (“User:”, login, “accessed the system ene (ane Sn rato reper on:”, time .asctime()) else print C\nlser doesn’t exist or wrong cosneeeeeeee Leama TERED Aithouch aseeminaly minor two lines the while Wo aia (oop is what keeps the program running, At the end of every function it's checked against the current value of status. IF that global value ist 'q'then the program continues. Fits equal to ‘then the program can quit. inreame already exists! 0°) while status != “q status ~ displayMenu() ee ees You can now create users, then og in with their tea names and passwords withthe login fle Wg aie being created to tore the ogn data andsucesst logins being Site seme mestarped, Now t's up ta youta further mprove the code rt Cm gpm) Perhaps youcan import the ist of created uses roma previous session and display graphic upon asuccessfullogi? Theres afar bit happening here, There are login Suzrt? and passw variables, which are then matched to the ser detonany ftere’se match thenyouhave asvcesfl login {and the time and date of the login is outputted. IF they don't match, ‘then you print an error and the process starts again. A 1Sine (angie nuccertatn) ea Working with Data GAME CODE Cea ee et os something of the past. Most games these days re created using Aen ease e ent ieee ee eens around an original product, such asthe world generating engine that Bethesda use forthe Skyrim and Fallout series of games. ‘Others examples can be coded from the ground up, but these Pee ir act ec eas into allthis? Se ep ced Ce ee et eee ut etn a es aS eally designed to cope with the Fast paced Formula on which ‘games suchas BattleField or the Call of Duty series are based, ‘These games are often coded with C+, or some other Form oF Cee eu ea eer eh etre ay Perot cy BUILDING TOOLS Inthe game industry, Python is mostly limited tothe Cee ae aoe Te Cen Pe rt ee eee Ce eee ete Cee er re ad Petree meer ny between the player and nomplaying characters inthe game. ‘You wil also find that Python canbe used to control the game's eae re ee era Ree ee eo et erry consist of characters other than the one the gamer controls ‘These Sims willgo about their business with their actions determined by the player's choices, thisinvolves an advanced mt guger nse se ers ‘Other examples include many of the available open world ‘games, where the introduction ofthe player wil change the Pere air ne nee en neo et Seen nents aetna eae Pere eu ecm Pree ae ee Cee a Pr en cae ea etd Re ea te ere ay Peete C2) index Using Modules aes q OER oe ea Wine @selaction at the! end -ad ; es Ry g-OR Se See mH = ee e \ td obj ects [Pre Using Modul Python module is a Python-created source file that contains the necessary code for classes, Functions and global variables. You can bind and reference modules to extend functionality, and create even more spectacular Python programs. Are you curious about how to improve your use of these modules to adda little something extra to your code? Then read on and learn how they can be used to Fashion Fantastic code with graphics, animations and operating system specific commands. jlendar Module Python in Focus: Artificial intelligence 89 ED) ins die Calendar Module Beyond the Time module, the Calendar module can produce some interesting results Micutcet ch VcninCtned Caisse aes geomet cee Mu emetic Rel relict nen WORKING WITH DATES The Calendar module is bi to Python 3. However, if for some reason it’s not installed you can ad ‘calendar as a Windows administrator, or sudo pip install calendar For Linux and macOS. ESTESERD U2urchPuthon3 andenter import calendar to BEEBE There are numerous functions within the Calendar callup the module ang ts inherent Functions. nce ‘module that may be of interest to you when 'sloaded into memory, star by entering: Forming your own code. For example, you can display the number of leap years between two specific years: ‘The result is 28, starting from 1904 onward, FETTER You cansee thatthe days of September 2019 are EEAEWAB You could even Fashion that particular example into displayed in a wall calendar fashion. Naturally you apiece of working, user interactive Python code: ‘an change the 2019, 9 part ofthe second tine to any year and ‘month you want, a birthday for example (1973, 6). The First-line Configures TextCalendar to starts weeks on a Sunday you can opt for Monday if you prefer bona shat ao Sepia te a ht te teat tiereton iene men ED vmbdmpubicatonscom C Calendar Module ¢ oO Zz You can also create a program that wil display al SALE in ys weeks ond nonths within oghen yeu ‘import calendar year=intCinput(“Enter the year to display: “) print (calendar. prcalCyear)) ‘We're sure youll agree that's quite a handy bit of code to have tohand. FETED terestinaly we can also list the number of days in ‘month by using a simple: For loop: ‘import calendar cal=calendar. TextCalendarCcalendan. SUNDAY) for i in cal.itermonthdays(2019, 6): printci) daysinmonth py - fhome/pi/Documents/daysinmor [Ble Eét Fgrmat_ Bun Qptions indow Help Tinport calendar alscalendar. TextCalendar (calendar. SUNDAY) for Lin eal. itermonthdays(2019,-6 prine(a) You can see that, at the outset, the code produced some zeros. Thisis due to the starting day of the ‘week, Sunday in this case, plus overlapping days From the previous month. Meaning the counting ofthe days wil start on Saturday 1st June 2019 and will tatal 30, a the output correctly displays it Soh Deus gens meee oe STamaUTT Tal You're also able to prntthe individual months, or ED 3. chew import calendar for nane in calendar month-nane: print(name) import calendar for name in calendar.day_name: ‘The Calendar module also allows us to write the Sia Functions in HTML, so that you can display it on a ‘website, Let's start by creating a new Fle import calendar cal=open("/home/pi/Documents/cal.htmi”, “w") cecalendar.HTMLCalendar(calendar SUNDAY) cal.write(c. formatmonth(2019, 1)) cal.closeC) ‘This code will create an HTML file called cal, open it with a browser ‘and it eisplays the calendar for January 2018. oe OF course, you can modify that to display a given STEP 10 year as a web page calendar: ‘import calendar yearsintCinput¢“Enter the year to display as a webpage: “)) cal=openC“/home/pi/Docunents/cal html”, “w) cal .writeCcalendar. HTMLCalendarCcalendar. MONDAY). formatyear(year)) cal.closeQ) “This code asks the user For a year and then creates the necessary ‘webpage. Remember to change your file destination, ora vémpublications com => Usi g Modules ) OS Module MUTT Cole (e-| CoRR CoM nl ea-lemel Kae AU UMMM an aU eer e acolo RR Olt MEA meMMeNe une Inset ine work with Windows whereas others will work with Linux and macOS. INTO THE SYSTEM ‘One of the primary Features of the OS module is the ability to list, move, create, delete and other stored on the system, making it the perfect module For backup code. interact with files veucnsattimosrediewihsamesincle RETIRE The nus etic ttt Su Functions to see how it interacts with the operating BUEPs) ‘current working directory of Python, as determined system environment that Python is running on. Fyou're using Linux by the system; as you might suspect, the os getcwdl Function is cor the Raspberry Pi, try this: asking Python to retrieve the Current Working Directory Linux users import os wisee something log these nes asthe aspbery asi home=os..getond() print Chome) FERED te cetumned result From printing the variablehome ESEIM vet another interesting element to the OS module, isthe current user's home folder on the system. isits abilty to launch programs that are installed inourexample that's fhome/pi:itwillbe different dependingon _inthe host system. Forinstance, if you wanted to launch the the username you log in as and the operating system you use. Chromium browser from within a Python program you can use For example, Windows 10 will output: C\Program Fils (x86), the command Python6-32. oe ry browsersos.system(“/usr/bin/chromium-browser”) L (05 Module Cl STEED Te ability to manipulate directories, or folders if ‘you prefer, is one of the OS module's best Features. For example, to create anew directory you can use import os (0s mkdirC*NEW") PEPER) The os.ystem( function is what allows interaction with external programs; you can even callup previous Python programs using this method. You wil obviously need to know the Full path and program file name for to work successfully. However, you can use the Following: teens ‘This creates a new directory within the Current Working Director o5:systeNC{starElehronel"hEDS:Z/NEVOURUBETEON csc ordngtotheobjecinthemid union. feed/music””) SED [02 soso erere a sreconenyouve ceed import os os.rename(*NEW”, OLD”) PEPTD For step s'sexample we used windows, toshow To delete them: that the OS module works roughly the same across import oS allplatforms. nthat case, we opened YouTube's music Feed page, so itis therefore possible to open specific pages: ‘import os os.system(‘chromium-bronser “http:// ‘bdmpubLi cations. com/”*) 0s.rmdir¢“OLD") Another module that goestogether with 0 i UEP shutil. You can use the Shutil module together ‘with OS and time to create a time-stamped backup directory, and copyfiesintol import os, shutil, time root_src_dir = r*/home/pi/Documents? root_dst_dir = */home/pi/backup/? + time.asctime() for src_dir, dirs, files in os.walkCroot_src_dir): ves dst_dir = src_dir.replace(root_src_dir, root FEPED Notcinthepreviusstep'sexampletheuseof —dstdir, 1) singe and double quotes. The single quotes encase the entire command and launching Chromium, whereasthe double {quotes open the specified page. You can even use variables to call multiple tabsin the same browser: inport os a=(‘chromium-browser “http: //bdmpublications . conv”") b=(‘chromium-browser “http: //wwn.google.co.uk”’) os. system(a + b) if not os.path-exists(dst_dir): os.makedirs(dst_dir) for file_ in files: srcfile = os.path.join(src_dir, file_) dst_fle = 0s.path. join(dst_dir, file) if os. path.existsCdst_file): os. renoveCdst_file) shutil.copy(srefile, dst_dir) print(“Ss>>>>>>>>Backup completecceeccec> Hooeeteay "M82 3>> centcr.2y BREE The Math module can also be renamed as you Import it, as withthe other modules on offer within Python. This often saves time, but don't Forget to make a comment to show someone else looking at your code what you've done: Age "eredsts” oF License)” for more information. >see asthe 33s wleranct 23.45) 3 ( Using the Math Module Cl Although it’s not common practise, iis possible to import functions from a module and rename them. In this example, we're importing Floor from Math and renaming it toF- although where lenathy code in us, this process can quickly become confusing from math import floor as f £4.2) ‘le Et Shel Debug options windows Help Python 3-42 (Getoult, Oct 19 2006, 13 Fe ae age tema tors tom >SE"rrsetmath Inport Fleer 26 # oo 4 i For further accuracy, when comes to numbersthe 18 ‘expand expm Functions can be used to compute precise vals from math import exp, expmi exp(le-5) - 1 # value accurate to 11 places expmiCle-5) # result accurate to full precision eso f“Ricense() for nore information. Se asocies) = beet BEE Iporting athe Functions ofthe Math Module can bbe done by entering from math import * \hile certainly handy, this is often frowned upon by the developer ‘community asit takes up unnecessary resources and isn't an efficient way of coding. However, it works For you then go ahead, ‘copyright’: “ergdits" or “License() Se SPha ingore De sare’) 533 cosy fa) ‘tor more information BETS AD terestinaly, some functions within the Math ‘module are more accurate, or to be more precise are designed to return a more accurate value, than others. For example IPED will return the value of 0 999999999, Whereas: ‘ENC DSLR LLL returns the value of 1.0. a FETED This level of accuracyisreally quite impressive, but {uite niche forthe most part. Probably the two most used functions are e and Pi, where e isthe numerical constant equal to 2.71828 (where the circumference ofa circle is divided by its diameter) import math print(wath.e) print(nath.pi) ‘le Eat shel Debug Stine windows Help Python 343 (default Oct (ee a.9.4) on dime Ee eooyighe, retits 2 skomraseaseo Bare, ean 1 “Iscense()” for more information. ‘The wealth of mathematical functions avalable through the Math module is vast and covers everything from Factors to infinity, powers to trigonometry and angular conversion to constants. Look up https://docs.python.org/3/ Uibrary/math.htmi for alist of available Math module Functions. ora vémpublications com Using Modules Random Module The Random module is one you will likely come across many times in your Python Pe eS eee eect acm ek cen kere acura Ci Gcetan em tate cen oul tga ete aemuesaaacc es RANDOM NUMBERS ‘There are numerous Functions within the Random module, which when applied can create some interesting and very useful Python programs. ESTISEDD -ustas with other madules you need to import random before you can use any ofthe Functions ‘we're going to look atin this tutorial. Let’ begin by simply printing a random number from 1 to 5: SPEED in ourexample the number four was returned, However, enter the print Function afew more ‘umes and it wil display different Integer values from the set oF ‘numbers given, er0 to five, The ‘overall effec, although pseudo- random, is adequate for the ‘average programmer to utlise in their code. Forabige st of umber ncn lating leit point values, you can extend the range by using the sullen sr ‘import random primtCrandom.random() *100) \ill display a Floating point number between 0 and 100, tothe tune ‘of around Fifteen decimal points. Bee tiowever, the Random module isn’t used exclusively for numbers. You can use it to select an entry from a list From random, and thelist can contain anything: ‘This will display one ofthe names of our adventurers at random, whichis great addition toa text adventure game. PETESERD You can extend the previous example somewhat by hhaving random.choice0 select From alist of mixed variables. For instance: © Random Module € Zz Ieraingsoucndio weahnconnithnte ERRAR iets. ancaroie ce of coe hich se SUz?6 Random module to shuffle the items in the list, thus. Sue) Virtual coin ten thousand times and countshow ‘adding a litle more randomness into the equation many timesit wil land on heads o tals: random. shuffleCLst) ‘import random print(Ist) output={“Heads”:0, “Tails”:0} ‘This way, you can keep shuffling the list before displaying a random DAIS COUPCERKOAO) item from it. for i in range(10000): output [random. choi ce(coin)]+=1 print(“Heads:”, output[“Heads”]) print(Tails:”, output [*Tails”]) PEPER) Using shure, you can create an entirely random lst (of numbers. For example, within a given range: faport rondon Ast=[[i] for I in range(20)] random. shuffleCLst) BE EEE Dre's an interesting piece of code. Using a text print(Ist) file containing 466 thousand words, you can pluck 2 ser generated number of word rom he le text le foun a Keen suing thet andyoucanhaveaerentslctont arab eamfauengtahwors ‘import random print(‘Ssssss>5s>Random Word Finder>>>>>>>>2Your adventure rolecce EGER ithePygamewindowstil wont Ea close don't worry, it's justa pancy between the IDLE (whichis written with Tkiter) and the Pygame module f you et Tae He run your code via the command line, it closes perfectly well BETIS You'e going to shift the code around a bit now, yygame. image. LoadC/home/pi/DownLoads/ running the main Pygame code within awhileloop; _spritel.png”) itmakesit neater and easier to follow. We've downloaded a graphic - makes it neat ‘ we ol def sprite(x,y): touse and we need to set some parameters for pygame: Gaerne ELRECINGHEGGYDD ‘import pygame y x=(800"0.45) pygame.init() y=(600°0.8) runningsTrue gamewindon.fLUGwhite) while running: spritecx,y) gamewindow=pygane di splay. set_node((800,600)) ——aa pygane.display.set_captionC*Adventure Gane”) for event in pygane.event .get(): black=(0,0,0) ‘if event.type==pygame QUIT: white=(255,255,255) FSTeGEERD [ts cuickly go through the code changes. We've downloaded image caled spritet.ong and allocated to the defined two colours, black and white together variable img; and also defined a sprite Function and the lit function with their respective RGB colour values. Next we've loaded the wil allow us to eventually move the image. mnt Pree 30(90040.45) roa pypiteocats import © yrteooee:e rame.initd smerindon.till(vhie) a Sprivecxy3 Braane: display vpdacec) merindowpyzane display set_mode((800,600)) Bese: diapiaysetcaption(-haventre cone") scke(0.0"0), ‘or event in pygane.event. get): wntten( 255,235,255) i Gventypers@utT Sne-pysanesnage-load{~/hone/pi/Donnloads/sprivet.png") runningersise det sprivece.y) mewindon BIECCAMe. (x99) en 101 => Us 9 Modules) FaTeGR AD "ow we can change the code around again, this time containing a movement option within the ‘while loop, and adding the variables needed to move the sprite ‘around the screen: ‘import pygame from pygane.locals import * pygome. init@) running=True ‘ganewindow=pygane. display. set_modeC(800, 600)) Pygane.display.set_caption(“Adventure Gane”) black=(0,0,0) ihite=(255,255,255) ‘imgepygame image . load “/hone/pi/Downloads/spritel. png”) def sprite(x,y): ‘ganewindow.blitCing, x=(800*0.45) y=(600*0.8) xchange=0 Gy imgspeed=0 while running: for event in pygane.event.get(): if event.type=QU running=False ‘if event.type == pygame. KEYDOWN: Af event .key==pygame. K_LEFT: xchange=-5 elif event. key==pygame. K RIGHT: xchange=5 ‘if event. type==pygame.KEYUP: ‘if event. key==pygame.K_LEFT or event keye=pygame.K RIGHT: xchange=0 x 4= xchange gamenindon.fllCnhite) sprite(x,y) pygame. display. updateC) pygame.quitC) Copy he code down and using he tan sight row keys onthe eyboard you can move yur spre acosthebotom oF Sua the screen. Now, it looks like you have the makings of a classic arcade 2D scroller in the works. FED wwtdmpubicatonscom ( Pygame Modules Cl You can naw implement afew additions and utilise some previous tutorial code. The new elements are the Subprocess module, oF which one Function allows ustolauncha second Python script From within another and we're going to create a New Filecalled pygametxt py Siar) {import pygane inport time import. subprocess pygane.init© screen = pygane.display.set_mode((800, 250)) clock = pygane. tine.Clock() font = pygane. font .Font(None, 25) Pygane. time.set_timer(pygame.USEREVENT, 200) | def text_generator(text): tape for letter in text: ‘tmp += letter if letter I= « yield tmp ‘class DynamicTextCobject): def _init_(self, font, text, pos, autoreset=False): 7 ‘self.done = False self. font = font self.text = text self._gen = text_generator(self. text) self.p0s = pos self.autoreset = autoreset self.updateQ def reset(self): self..gen = text_generator(self.text) self.done = False self.updateQ def updateCself): if not self.done: try: self.rendered = self. font. rendernext(self.-gen), True, (@, 128, @)) except StopIteration self.done = True ‘time. sleep(10) subprocess. Popen(“‘python3 /hone/pi/Documents/ Python\ Code/pyganel.py 1”, shellsTrue) def dran(self, screen): screen.blit(self.rendered, self.pos) text=(“A long time ago, a barbarian strode from the frozen north. Sword in hand....”) message = DynamicText(font, text, (65, 120), ‘autoreset=True) while True: for event in pygame.event.get(): if event.type = pygane.QUIT: break if event.type = pygame.USEREVENT: message. update else: screen. fill(pygane.color.Color¢‘black”)) message. dran(screen) pygame.display.flipC) Clock. tickC60) continue break pygane.quit() When you run this code it will isplay along, narrow Pygame window with the intro text scrolling tothe right, After a pause often Seconds, itthen launches the main game Python script where you can move the warrior sprite around. Overall the effects quite good but there's always room Forimprovement. aR sworatdpubicatonscom — QUE) Using Modules Basic Animation Cy MS Cur aCe Roar ee Con eC eeu) PUP eur eed Mea Winans cusete me Cucasek saa Coole NEE NAe ceu Lae Te eRe RUC Ue RET Molen eaten clu te LIGHTS, CAMERA, ACTION ‘The Tkinter module is an ideal starting point for learning animation within Python. Naturally, there are better custom modules ‘out there, but Tkinter does the job well enough to get a grasp on what's needed. BEER {cts make a bouncing ball animation. First, we FATEREDD ser the new code between the ball will need to create a canvas (window) and the ball = canvas.create_oval(5,5,60,60, fil1="red") line and the gui .mainloop() line. Save it and Run. ‘You will now see the ball move from the top left corner ofthe toanimate: animation window, down to the bottom right corner. You can alter ‘SPORE the speed in which the ball traverses the window by altering the gui = TKO ‘time, sLeepC.@1) ine. Try (05). gui -geonetry(“800x600") guititleC“Pi Animation”) canvas = CanvasCgui,— width=800, hei ght =600, bas’ white”) ‘canvas .pack() ui .mainloop() FETTSPD seve and Run the code. You wil see a blank window appear, with ared bal sitting in the upper left ‘omner of the window. White this is great, i's not very animated. Let's add the Following code: The lines the part that moves the bal from one comer tothe other; ‘obviously with both a and b equaling 5. We can change things around abitalready, such asthe size and colour ofthe ball with the in: and ‘we can change the values of a and b to something else, balla = canvas.create_oval(7,7,60,60, fill='red') tor x An ranga(©, 109): Canvas move( ball 2,b) Sina: Sieept 05) FETTER (2t'sseeiF we can animate the ball so thatit bounces, around the window unti'you close the program: xa=5 ya = 10 hile True: ‘canvas .moveCbatl1,xa,ya) pos=canvas .coords(bal11) if pos[3] >=600 or pos[i] <0: -ya 800 or pos[0] <0: ya if pos2] gui update) time. sleep(.025) ETSI Remove the code you entered in Step 2 and insert the code from Step Sin ts place; again, between the ball = canvas.create_oval(S,5,60,60, fill=’red”) {and the gui .mainloopQ) lines. Save the code and Runit as normal if you've entered the code correctly, then you will se the red ball bounce off the edges ofthe window untlyou clase the program, SIE takes place within the While True loop. Fst we have the valves = screen.get_height(): stor[1] = @ star[0] = randrange(0,639) screen. set_at(star, (255,255,255)) STEER Nowadd the following def mainQ: pygane. init) screen = pygane.display.set_node((640,480)) pygane.display. set_caption(*Starfield Similation”) clock = pygane.time.ClockO init_stars¢screen) while True: # Lock the franerate at 50 FPS clock. tick(50) # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: return screen.fill((0,0,0)) rmove_and_draw_stars(screen) pygame. display. flip, if —name_ = main er ming ygane: ae) Exfecn = pyganedisplay.set_nede( (640, 480)) some aie Sete Steddacsonr) | Ante stars(screen) ‘hocks eLek(S0} ° ‘vent’ pyoame.event. gt): "aeene: type == pyoane utr sereen.£511((0,9.0)) stove: and_drou stara{ screen) Prosne- display. ip() an PEPPETD s2veand Run the code. You will agree that the simulated starfield code looks quite impressive. Imagine this a the beginning of some game code, or even the start to. presentation? Using a combination of Pygame and Tkinter, your Python animations wil lok Fantastic. vworatdepublicatonscom — QUES z=» Using Modules ) Create Your Own Modules ee rerun Cet s acm eLee Cla reac Toes Ca and import the parts you need as modules. Learning to build your own modules also Decal crea ums BUILDING MODULES ‘Modules are Python files, con ing code, that you save using a py extension. These are then imported into Python using the ‘now familiar import command. Leesa by eeatingaset of base matherais Now yu'e going ota the Function etnitons ous? functions. Multiply a number by two, three and Sues) ‘out of the program and into a separate file, ‘square or raise a number to an exponent (power). Create a New File Highlight the Function definitions and choose Edit > Cut. Choose File. inthe DLE and ener > Nev Fe and ne Edt> Patent nes window Younha ‘epee, one ith he futondetinton the oer wth thetincton als Under the above code, enter functions to callthe EWM iryou now try and execute the basic math py code code: ‘203i, the error 'NameError: name ‘timestwo' is not defined! wil be displayed, Thisis due tothe code no longer print Cinesten(2) Paine tothe aon dat print (square(4)) print Cpower(S,3)) "Pile S/noe’pa/beciments/Pyoren ‘Save the program as basic mathpy and execute itto get therresults. > Returnto ae ‘created window containing the Function definitions, and ClickFile > Save As. Name this imathpy and save it inthe same location asthe original basic_math.py program. Now close the minimath.py window, so the basic_math.py window is left open. ( Create Your Own Modules Cl Bscktotebacatnpyvindowatetapottte TER sn soucnnow cee arangeoffatenerts SUz?6 code enter: Sue) to determine what to do with the number and utlise the new rested function definions AF choice == 11": fron minimath import * This wll import the Function definitions as a module, Press F5 to save and execute the program to see itn action. EN elif choice = ‘27: print(timesthree(num1)) elif choice = ‘37: print(squareCnumi)) elif choice = ‘4 ‘nun2 = intCinput(“Enter second number: “)) ERC print(“Invalid input”) ie Est Farr in Grenson 6p FETS DD) You can now use the code Further to make the pragram alittle more advanced, utilising the newly created module to its Full Include some user interaction. Start by creating a basic menu the user can choose from: print¢“Select operation. \n”) enice« irputt-wenter chee 1/70/07 print(“1.Times by two”) rat = Snipa tree mer: >) print¢*2.Times by Taree”) print¢“3. Square”) print(“4.Poner of”) choice = input¢“\nénter choice (1/2/3/4): PETIT ow we can add the user input to get the number the code will work on: pum. = intCinputC*\nEnter number: “)) ‘This ill save the user-entered number as the variable num ESTSET DD Note that forthe last available options, the Power of choice, we've added a second variable, num “This passes a second number through the function definition called ower. Save and execute the program to see iin action, Ble Edt Format Bun Options Windows Help from minimath inport * print("Select operation.\n") fancies by to") » frint("2.Times by Thi irint("3.Square") print(v4.Poner of") choice = input(“\nénter choice (1/2/3/4):") punt = intCinput("\nenter number: ")) Python in Focus: Artificial Intelligence Artificial Intelligence (Al) and Machine Learning (ML) are the new hot topics of the IT industry. Al is fast becoming the working science fiction that it has been portrayed as in adele eh ae Despite how close Aland ML are, there are distinc differences between the two technologies. Al refers to the study of howto train a ‘computerto accomplice the things that humans can do significantly better and faster. Whereas, MLis the ability fora computer to learn from its experiences, so that the outcome and performance will, Ce eure cee eeu Pc nee Seud Serer mee rec Re ey eu eee ed ‘and, thanks to Python, thaf aap is getting loser every day. APPLICATIONS. Both Al and ML are hugely present.n today's technology. Where, ee Ne este te) pee re ee ae ett etree] Beceem tase Cras) enor ee ose eee ‘These devices have infiltrated most of our modern world, with «global coverage reaching 5.5 billion for 2019 and set to rise to over billion by the end of 2020, i's little surprise to discover that Al and Dee ene ee oi DE Gera ae) smartphone, the coding behind these devices has been developed totake individuals into account. These devices are designed to ee eet ei ee ae ee ‘advertising is moulded around our browser and search preferences, Pes eae ee ee eas eee nee eee Eee Ee er ere DIGITAL ASSISTANTS eee nes eee cree eerste ees are all coded using Python, and are designed to listen, learn and respond to what we ask of them. With Python, this level oF Ais surprisingly simple, thanks to the many libraries and customisation Be tee rea ea ee Forinteligent coders, cutting down on the development time in Ce ee epee eee complexalgorithms, these developers can devote significant time to eae sea Cg oe cee ne Python-riven Al code isgeading our voice, determining what itis eee onto one ners Tuma’ rer ea eet er ert) Sa ee eee Cee eee Peete tees ee ee Ce Pee an ee a nee seed ect as Pieters BEYOND THE SMARTPHONE Cee ee ns Sy have you entered a search string into Google, such as car parts fora Mk eel RUE eee eet erty Se ar ranEn e aeS your everyday computing tasks. ‘Another example of Al and ML working togethers Gmail's recent addition of ST ee see ee rr) ee ete ee reer an reratas Poe eee eter ent Re a es ee is Facial recognition another element of Aland ML that's been the target of Cee aera ae ere ee ere ‘on both smartphones and CCTV footage have improved dramatically ee eee ee ete Se eo ee ecg eae Pee en ee tien Ro cs ern Tesla's work on sel rving cars means they are getting closer to being the er see ened Pete rm ee een arenas Cra Mer ue ere rne Peres e sree Tm tee en ett C++, orsome other language, thats supporting the performance and ‘overall program in which the Al and ML are working Pe eee eater Pe eee reo Sie ue nue en processing, helping people with vstal and hearing Ce eral Pe uate Sue eee err) a ag ablity to travel. I¢snot.all about two Albots ere te ec ai eee) tS OF Al " De Ceara) Roper ey ‘androids is up for debate. There are plenty of arguments for and against CR believing that Al willbe the worst er ey Cute Our Snead eau Peete ts) Perna) eee er Rerun tid apne ee ee) ) eee Ss bi Sone.) Se Pines tg ve Ee ke =] a Ce) ee ee eee bi VAP SON f 8S) Cn er oy = See ei ages SS Seep ee ey ee oe Cheek ere — aa | Ch ef PEP G7 SO = aul) (nf smb f= baa Pan a tay Len em) Se iy Fo x sora] nfo fen ener ba nd ate] Tae q ree, , aia Cra er ee ee er BK WWW Es a. a Fe ae Hel. eee ectencisk-kg pee Ae NS n BS Sai Re err h bare ts PEL a ey ge ol. el a OPER ee Sevoenca Parsee re re FI eer ae ee . em Sra ee me) Bei agii dg. 22 : ES ee a Cres Barret tries ay GD: ca: ia San 1 = oe Sg | pe __ We've included a vast Python code repository for you to freely use in your own programs. There's plenty in here to help you create a superb piece of programming, or extend your project ideas. We've got code for making backups of your files and folders, number guessing games, random number generators, Google search code, game code, animation code, graphics code, text adventure code and even code that plays music stored on your computer. We've broken down some of the newer, and extended, concepts of the code to help you better understand what's going on, This way you can easily adapt it to your ‘own uses. This is an excellent resource that you won't Find in any other Python book. So use it, take it apart, adapt it to your own programs and see what you can create. Number Guessing Game Random Number Gener: Random Password Generator Playing Music with the Winsound Modul Text Adi ipt hon Scrolling Ticker Script Simple Python Calculator Hangman Game Pee ees eae er eee eee © Sete Rodale TL TNE eke eer ed) iia Bei une Cate es ets EM Utell go) fooled agy-1-] (ol Aol xo) read a file, write toa file, append to. Evel oe(-i cle -E- Mal (cM (imag Kagel ed , of adirectory’and much more. It’s Purl Ne deka Se Ce ene Ree fee nis parcof the code imports the necessary modules. ne OS and Subprocess modules deal withthe ‘operating system elements of the program. Each deF xXx Funct 1e code for each ions. Once the code within the pete, the code retur the users running. clears the screen, whereas in Linux and macOS, t Clear command wipes the sereen. IF the code tries hese are the options, From 1 to 12. Each executes the appropriate Function when the relevant number isentered. FILEMAN.PY Copy the code below into a New > File and save it as FileMan.py. Once executed it will display the program title, along with the current time and date and the available options. | Amport ehutt 1 | import os | import time | Amport aubprocess det Read) | patheinput("Enter the fle path to read:") | filesopen(path,"=") | ! t I ” | i | det weited: pathsinput("Enter the path of file to write or create:") SE o8.path. Sefile(path): peint('Rebuilding the existing Sie’) alse: rint((Creating the new fe’) eextainput (“Enter texts") ‘lezopen(path,"w") ‘ile. wrive(eext) ot aad ‘pathainput("Eater the Se path”) textainput (“Enter the text to add") filesopen(path,"a") ‘le write('\n'ttext) det delete) pathsinput(’Enter the path of file for deletion:") £¢ o8.path existe (path): print('File Found’) ‘os remova(path) prine('File has been deleted’) else: int('File Does not exist’) dor piztist() pathsinput(’Enter the Directory path to display:") sortlist=sorted(os.listdir(path)) i=0 whileticlen(sortlist) rintleortlistii}¥"\q") ied et check) Apsint(input ‘Check existence of \nl.File \n2 Directory\n')) SE spent: pathsinput("Eater the file path") ‘os.path.isfile(path) Lf os path Laftte(path)=tzue print('File Found’) rint('File not found!) it tpo=2: path=input (“Enter the directory path") (os path.tedir(path) Af os.path.isdir(path)=False: print (‘Directory Found’) Print (‘Directory Not Found’) input (‘Enter the source path of fle to moves") BBe=int input('L Rename \n2.Move \n)) Af meet: path2input(‘Enter the destination path and file names’) ‘shutil.move pathl,path2) print(‘File zenaned’) sf mra=2i path2ainput(‘Enter the path to mover) ‘shut l move(patht,path2) Print('File moved’) dee copy) pathisinput(‘Enter the path of the fle to copy or renane:’) ath2ninput('Enter the path to copy to:’) ‘shut l.copy (path path} print('File copied’) dee Makedie() patheinput ("Enter the directory nane with path to make \neg. c:\\Welio\\Wowdir \nWhere Newdir is new dizectory:") ‘ot nakedire(path) rint(‘Directory Created’) det Renovedir() path-input('Enter the path of Directory:") treedizaine(input('I Deleted Directory \n2.Delete Directory Tree \n3.Exit \n')) if treediz= ot-zndiz(path) Af treedixen2 ‘shutil,rmtroe(path) print (‘Directory Deleted’) Af treedixes: exit) det opentie() path-input ("Enter the path of program:") ‘os startille(path) except: rint('File not found’) rons white(eun==) yey: | os.system(’clear’) | except OSError: | es.system(‘els') print(\\m>>>oo5po9Python 3 File Manager manber BH 5 i ‘igh, ty again) | é 5 se gree = nde | ry ! ] ' SET | 3 I Mana + You guessed | rr] | Eeeectiy in gueneteed + “genes? | bs t Ve. t | ira) | print(‘Sorry, out of guesses. The number I was} a | thinking of is ° + number) Ho rough this is a reasonably easy to Follow program, there are ame elements to the code tat ae woth pointing out To besin 4 with, you need to import the Random module, as you're using é@ random numbers within the code. section ofthe code creates the variables for the number random number chosen by the computer, or the number of 4 1 player can tke, then along withthe variable values, you also need to am statements at the start ven in the pri re a ey oc eae pa val i | 1) i =) 4 Seater {etary wanda «Be wel done utp donuts hry guesses eyed op PI Fthelayer runout of guste, then the gore over curls 1) displayed instead, along with revealing the number the computer Fy ‘was thinking of. Remember, you do alter the values of the 8 5 a oe Code Improvements Since this s such assimplescriptto apply toa situation, there's plenty of room to mess around with itand make it more interesting, Perhaps you can include an option to take score the best out of three rounds. Maybe an elaborate way to congratulate the player Forgetting a hole in one’ correct guess on ther First ty, "Moreover, the number guessing game code does offer some room For implementing into your code na different manner. What we mean by thisis, the code can be used to retrieve a random number between a range, which in turn can give you the star of 2 character creation defined function within an adventure game. Imagine the start ofa text adventure written in Python, where the player names their character. The next step isto rllthe virtual randam dice to decide what that character's combat rating, strength, endurance and luck values are. These can then be. carried Forwardinto the game undera set of variables that can be reduced or increased depending on the circumstances the player's character ends up. Number Guessing Game For example, as per the screenshot provided, you could use something along the lines of: CR = randon.randint(l, 20) luck = random.randint(1, 10) Print("Your character's stats are as follows:\n") Print(‘Endurance:*, Endurance) Print(*Combat Rating:", CR) Print(‘Luck:", Lsck) ‘The player can then decide to either stick with their roll or try again forthe hope of better values being picked. There's ample ways in hich to implement this code into abasic adventure game. = vw bdmpublestons.com Random Number Generator User input and theability to RNDNUMGEN.PY IMU eleanor e leila elements with any programming language. It's what separates agood progrdm from a great program, one that‘allows the user eo Ie leet poe aa rel el fara plcorraiiol Itmight be simple but this litle piece of code will ask the user For two sets of numbers, a start and a finish, The code will then pluck out a random number between the two sets and display it. from random import * print *\nosp2s5>959Random Munber Generatorc>>>>>>9>Random Turtle Inagecceeecccee\n") nbi=int(input ("Enter the start number: °)) aub2aint(input("Enter the second number: “)) ‘mb3eint(input(“Enter the third number: ")) inbé=int(input("Enter the fourth number: ")) Furthermore, the core ofthe code can be used inatext adventure ‘game, where the character Fights something and their health along with the enemys, is reduced by random number. This can be mixed with the previous code from Page 90's Number Guessing Ga ed the stats For the adventure ‘turtle. forvard(nmbt) ‘game's character. turtle 1eft(50) turtle forvard(anb2) You can also introduce the Turtle module into the code and arte. 1eft(00) turtle. corward(anb3) turtle-1eft(90) ‘turtle. forvard(nmbé) turtle 2eft(90) perhaps set some defined rules fr drawing a shape, object or something based on a user inputted random value from a range ‘of numbers, ttakesalitle working ut but the effects certainly really interesting Whilst esa ttle rough around the edges, you can easily make it more suitable, Random Number Generator/Password Generator Random Password Generator We're always being told that our Passwords aren't secure enough; well here’s a solution for you to implement into your own future programs. The random password generator code below will create a 12-letter string of words (both cases) and numbers each time it’s executed. Secure Passwords There's plenty you can do to modify this code and impraveit further. For one, you can increase the number of characters the ‘generated password displays and perhaps you can include special characters tao, such assigns and symbols. Then, you can output the chosen password to affile, then securely compress it using the previous random number generator asa ile password and send it toa userfortheirnew password. ‘Aninteresting aspect to this code isthe ability to introduce a loop {and print any number of random passwords. Let's assume you have a listof 50 users fora company and you're charge of generating ‘random password for them each month. RNDPASSWORD.PY Copy the code and run it; each time you'll get a random string of characters that can easily be used as a secure password which will be very difficult For a password cracker to hack. Amport string import random def randompassword() charsestring.ascii _ uppercase + string.ascii _ lowercase + string digits sizes 8 return join(random.choice(chars) for x in range(size,20)) print randompassword()) ‘Adding a loop to print a password fifty times is extremely easy, for example import string import random det randospassord(): cchars=string.ascii _ uppercase + string.ascli _ lowercase + string digits sizes 4 return Yjoin(randon.choice(chars) for x in -range(siz0,20)) 0 white n<50: ‘print(eandompassword()) pens Thiswill output fifty random passwords based onthe previous | random selection of characters ‘wovabepublications com Se Ble Aa aa Toye TNE eke eer ed) eT a er eee area 5] roe au eeleR eT mite ie is mK TXT2BIN.PY aa ee poor Se Naturally we're using the format Function to convert the Bagh tae ie a [elo cs user's entered text string into its binary equivalent. If you PONT ROT CMM: wee chests ocaro, youn sun the biay ian online convertor occ! Cee eae textsinput(Enter text to convert to Binary: *) peint(’ ‘join(formatiord(x), ‘b’) for x in text)) file Edit Format Run Options windows Help print(>>>>>>>>>>Text to Binary Convertor osssppoootext to Binary Convertorccceccccce\n") conversionsinput("Enter text to convert to Binary: *) ‘size = (600, 00) ‘screen = pygane.display.set _node(size) Text to Binary Convertor Pygane display.set _ caption("Binary Conversion”) eee clock = pygane.tine.clock() ‘text _rotate degrees = 0 Binary=(’ ‘Join (format ord(x), in conversion)) wy fore while not done: for event in pygane.event.get() Af event type == pygane. QUIT SSS screen 611 90HrTE) font = pygane.font.SysFont('Calibri’, 25, True, False) text = font.render(Binary, Teve, BLACK) text = pygame.transform.rotate(text, text _ rotate _ degrees) text _Fotate degrees += 1 serecn.blit(text, (100, 50)) pygane.display.fip() ‘lock. tick(60) pygane.quit() Print(’ ‘join(format(ord(x), °b") for x in conversion)) vevoubdmpublationscom ere AU EU eMNeci-iene} folie heliteelel le Ne Waste file browser that's presented ina graphical usef interface using the Tkinter module.There's a lobyou can Tirol baalceeete Reale) -lal FILEBROWSER.PY Tkinter is the main module in use here but we're also using idlelib, so you may need to pip install any extras if the dependencies Fail when you execute the code. from tkinter import Tk from idlelib.treeWidget import Serolledcanvas, Filefreeltem, TreeNode import 0s oot = Tk() root.title("File Browser”) sc = Scrolledcanvas(root, bg="white”, highlightthickness=0, takefocus ‘sc.frame pack(expands1, fill="both”, side="left”) stom = Filetrestton(os.getewd)) node = TreeNode(sc.canvas, None, item) rnode.expandi) root. iainloop() (. Basic GUI File Browser ‘Advanced Filing = When executed, the code wll spay the current drectony’s itn open(name'e) a Users contents Fyouwantto see the contents of anther directory, you print(Omeriie.reed0) oxcer canrun the code from a command line within the chosen directory, just remember to callthe code From where it's located on your system, as per the second screenshot. You can also double-click any ofthe filenames shown in the directory tree and rename the. aie = 006.tS¢1e{ “File Opene:”) Label = ttktabel(root, text ="File This is an interesting piece of code and one that you caninsertinto Open’, foreground="red",font=("Helvetin”, 16)) your own programs. You can extend the cadeto include auser ——/abelpacki) Specified directory to browse, perhaps your own unique file icons too. you're using Linux, create an alias to execute the code and then you can run it from wherever yau aren the system. mn = Masten Eine("No files opened”) Windows users may have some trouble with the above code, an 7 alternative canbe achieved by using the Following c 2 ‘ile.add _ command(label = ‘open’, command = Opentile) fron tkinter import * ‘Sie.add~ conmand(iebel = "Exit", command = zon thinter import tek ambda:exit0) ‘ron tkinter.filedialog import askopentilenane rmens.add _cascade(iabel = ‘File’, mens = Se) root = TK( ) root.maintoop() ef Opens): ‘name = ackopentilenane(initialdiz="C:/" ‘letypes =((*Text File’, “.txt"), ("ALL Files","**"), title = “choose a file.” ) It’s not qute the same but this code allows you to open files, in your system via the Familiar Windows Explorer. I's worth ‘experimenting with to see what you can do with i. ‘wovabepublications com We've already seen the Turtle MOUSETURTLE.PY module.being controlled by the The first piece of code presents the standard Turtle window. tere Ur N ata oe lee holt mel AU) Press Space and then click anywhere on the screen for the TUS Re nM it orcas rome Messcnd alow use theirmotise asa drawing tool it can crash Python, ‘ within Python. We'have two possible. 3 code eS here, pick ea Piercy -ni9 For vies q LPO ea fe Example: i from turtle import Screen, Turtle sex screen) yertle = Turtle() dof 1010 sereen.onscreenclick(click _handle:) dof click _handler(x, y): screen.cnscreenclick(Wone) # disable event inside ‘event handle yertle.setheading\yertle.towards(x, y)) yertle.gototx, y) screen onscreenclick(click handler) # reenable ‘event on event handler exit screen.onkey(ki0l, “ ") # space turns on mouse drawing ‘screen. Listen() Clare Rees er screen.mainloop() a 2nd Code Example: from turtle import * ‘shape(“eizele”) pencelor("blue”) width) ‘ondragigoto) Listen() Ninja TurtleMouse This code utilses some interesting skills. Obviously it wll stretch your Python Turtle skill to come up with any improvements, which great, bt it could make For a nice piece of code to in nething a young child will use, Therefore itcan be on to get their teeth into; where the main characters nes or something similar. Mouse Controlled Turtle/ Python Alarm Clock Python Alarm Ever taken a quick break from working at the computer, then suddenly realised many minutes later that you've spent all that time on Facebook? Introducing the Python alarm clock code, where you can drop into the command prompt and tell the code how many minutes until the alarm goes off. ALARMCLOCK.PY This code is designed for use in the command prompt, be that Windows, Linux or macOS. There are some instructions on how to.use it in the main print section but essentially it's: python3, AlarmClock py 10 (to go off in ten minutes) import sys Amport string from tine import sleep sa = sys.argy Lea = len(sys.argv) Af tsa '= 2) print ("Usage: [ python3 ] AlarnClock.py duration _ in _ minutes”) print ("Example: [ python3 } AlarnClock-py 10") print ("Use a value of 0 minutes for testing the alarm imnediately.”) Print (‘Beeps a few times after the duration is over.”) print ("Press Ctrl-C to terminate the alarm ‘clock early.”) sys.exit() try: ‘minutes = int(ea(t]) except Valuezrror: print (‘Invalid numeric value (ts) for minutes” ¥ sa(1)) Print (‘Should be an integer >= 0") sys.exie(1) Af minutes < 0) print (‘Invalid value for minutes, should be >= 0") sys.exie(l) seconds = minutes * 60 Af minutes == 1 unit _ word =" minute” ‘unit _word =" minutes” Clock ey: Sf minutes > 0: Eint ("Sleeping for “ + str(minutes) + unit _word) sleep(seconds) print ("Wake up”) for 4 in zange(s): print (chr(7)), steep(t) except Keyboardtnterrupt: print (“Interrupted by user”) sys.exit() Wakey Wakey ‘There's some good use of try and except blockshere, alongside some other useful loops that can help you geta firmer Understanding of how they workin Python, The code itself canbe used ina variety of ways:ina game where something happens after aset amount of time or simply as ahandy desktop alarm clock for your tea break. Linux users, try making the alarm clock cade into an alias, so youcan runa simple command to execute. Then, why not integrate a user input at the beginning to ask the user forthe length of time they want until the alarm goes off, rather than having to include itn the command in. \Windows users, Python 3s the only version installed on your system then you ill need to execute the code without adding the 3to the end ofthe Python command. For example python Alazmclock.py 20 ‘Again, you could easily incorporate this into @ Windows batch fileand even set a schedule to activate the alarm at certain, times ofthe day vovoubdmpublations.com AYU sel eM ele Kon toe loleLUL Uae] scrolling text? Its uses are many: the beginning of a game or introduction to something epic, like thé'beginning lg INP USSU) itso a -el|s:¥- | ay ei cg something; such Err eA Pecos au list 4 im Eo ne Een eee Se it~ ee 0 sf von) =Towe Sasbceac) ole) vant eo) oN be) |i Ee) otto met 8 ata) adel aE ele A i a nae NT ‘peters " @ a Pi Pi i b a w I 9 po w Po 9 Qo oe ny ~ fs eee = vor aS EPICSCROLL.PY We've used the poem Cimmeria by Robert E. Howard for the code's scrolling text, along with a dramatic black background and red text. We think you'll agree, it's quite epic. import pygane 0s pg from pygane.locals import * po.inito text _list =” 1s of sombre hills; ‘The grey clouds’ leaden everlasting arch ‘The dusky streams that flowed without a sound, And the lone winds that whispered down the pa: Vista on vista marching, hills on hills, Slope beyond slope, each dark with sullen trees, Our gaunt land lay. So when a man climbed up A rugged peak and gazed, his shaded eye Saw but the endless vista ~ hill on hill, Slope beyond slope, each hooded like its’ brothers, Tt was a gloomy land that seemed to hold ALI winds and clouds and dreams that shun the sun, With bare boughs rattling in the lonesome winds, And the dark woodlands brooding over all, Not even lightened by the rare dim sun Which made squat shadows out of men; they called st Cimmeria, land of Darkness and deep Night. 3t was so long ago and far away forgot the very name men called ne. fand fint-tipped spear aze like a dream, And hunte and ware are shadows, Z recall Only the stillness of that sombre land; ‘The clouds that piled forever on the hille, ‘The dimness of the everlasting woods. Cimmeria, land of Darkness and the Right, Oh, soul of mine, born out of shadowed hill ‘To clouds and winds and ghosts that shun How many deaths shall serve to break at last This heritage which wraps me in the grey Apparel of ghosts? T search my heart and find Cimmeria, land of Darkness and the Hight! we spit (\a') Vertically Scrolling Text clase Credits ALong Time Ago. __(eelf, screen_rect, ist) sereen _ rect sole let = let self.cize = 16 The obvious main point of enhancement isthe actual text itself Replace iewith alist of credits, or an equaly epic opening a soryne tyr Patho game ndtv owt tthe SE EEEEEIEEEEIEIEEEEEEEEEEEE ‘mark with whoever playsit. Don't forget to change the screen ee resolution if needed; we're currently running it at 800 x 600. self tines = 0.0 self-delay = 0 ‘self.make_ surfaces() dof make _text(self message) font = pg.font.SyeFont(‘Arial’, self.size) ‘text = font.render{sessage,rue,self.color) rect = text.get _rect{center = (self.srect. centers, self.srect.centery + self.buff_centery) ) dof make _surtaces(selé) sele.taxt = (J for i, Line in enunerate(self.1st): 12 selé.make_ text(Line) Lpy += iselZ bute Lines self.text.append(1) def update(sels): Af py.tine.get _ ticks()-self.timer > self.delay: Self.tiner = pg.tine.get _ticks() for text, rect in self.taxt: recty -= 1 def render(self, surf): ere =p ipa.otme.09) for text, rect in self.text: seeversstiao™ surf.blit(text, rect) screen = pg.display.set _ mode((800,600)) screen _ rect = screan.get_ rect() lock = pg.time.Clock() running=True cred = Credits(scr sn _rect, text _ list) while running: for event in pg.event.get(): if event.type == QUIT: running = False screen, £11((0,0,0)) cred.update() ered. render(ecreen) g.display.update() clock tick(60) vw bdmpublestons.com ChE RWS aa) Toye Foyt eke ee eae) eed al fl Saree eee ry MUCUS (ee Rele eel) on the desktop of most operating systems but it's always handy to have one on top of the currently open NuntelMederriscnie MM nate cl a Python digital clock thatcan be a A om ‘peters ~ ee aT) DIGCLOCK.PY This isa surprisingly handy little script and one that we've used in the past instead of relying on a watch or even the clock in the system tray of the operating system. import time import tkinter as tk def tick(timel="): # get the current time from the PC ‘eine? = time. steftime(H:46:45') Af time? '= time: timel = tine? clock.config(text=time2) clock.after(200, tick) oot = tk.tk() clock = tk-Label(roct, font=(‘arial’, 20, ‘bold’), bgz/green’) clock pack{All="both’, expand=l) tick) ‘root. iainloop() Python Digital Clock Tick Tock Tiss apiece of code we've used many times inthe past to keep track oftime while working on multiple monitors and with just a quick lance to where we've placed iton the screen “The Tkinter box can be moved around without affecting the time, maximised or closed by the user at will We haven't given the “Tknter lock window a title, 0 you can add to that easily enough by snipping the code from other examples in this book. ‘Another area of improvementisto include this code when Windows or Linux starts, soit automatically pops up on the desktop. Se also if you're able to improve its Functionality by including afferent time zones: Rome, Pats, Landon, New York, Moscow and soon. } Another example, expanding on the original code, could be a digital stopwatch, For that you could use the Following Amport teinter Amport tine lass Stoptiatch tkinter.Fraze classmethod def main(cls) kinter.NeDefaultRoct root = thinter.Tk() root.title('stop Watch’) root.resizable(True, False) root.grid _colunnconfigure(0, weights) easier ‘Stopkatch(root, padding) laget geidintchprointer SEH, padding root.mainloop() et __init __(s0l£, master-None, ent=(), **kw) 1 3), pads. lf, ~~ label = thinter-Label(eelf, tm BGEal Tine) olf ___ ting = tkinter Stringlariself, “o1000") w display = tkinter Label (self, textstarv, comand-eelf, —— click) wolf. __ label. grid(zow=0, oltmn=0, stickyethinter., padding) elf. _ _button.grid{eow=i, coluansd, ‘columaepan=2,sticky=tkinter.NSEW, **padding) det _ _elick(eeis) if Sele. _ _button{'text’) == ‘start’: Tbietont'text'] = 'stop" Toatart = tine.cloek() Toounter = self after _sdle(eelf, _ pate) f,___button['eext’] = ‘start’ jelf after _cancel(self._ _ counter) det _ _update(cele): ‘ow = time.clock() ‘wovabepublications com ol — a ef) Toye TNE eke eer ed) ia ee Ieee © Playing Music with the (ol Ree lt mic leno mee r-In| MUSIC.PY Cn eS ‘The code utilises both the Time and Winsound modules, your own music: The code below defining the tone and pitch and inserting small pauses of 5 will playout Pachelbel’s Canonin D, ora saccond spat xinouna be j | Smpore tine . time.s1eep(0.001) Playing Music with the Winsound Module £ Sweet Music ‘Obviously the Winsound module isa Windows-only set oF Functions for Python. Open your IDLEin Windows and copy the code in. Press F5to save and execute, then press the Enter key, asinstructedin the code, to start the music for i in range (8): winsound.Beep( 1¢, 2+) winsound Beep( RC, t) winsound.Beep( hE, t) winsound.Beep( 6, t) time.sleep(p) "Naturally you can swap out the winsound.Beep Frequency and durations to suit your own particular musi or you can leave tas sand enjoy. Perhaps play around with the various methods to ‘make other music, winsound.Beep( 16, 2+) winsound Beep( 6, t) winsound.Beep( 8, t) winsound.Beep( hD, t) tine sleep(p) For example, players ofthe Nintendo classic game, The Legend (of Zelda: Ocarina of Time, can enjoy the game's titular musical winsound.Beep( 1A, 2+t) Intro by entering winsound Beep( A, t) winsound.Beep( hc, t) winsound.Beep( hE, t) — - == winsound.Beep( E, t) — ae ee i, Ss tS, cme Hey nae — a = ee a 2 Ss th Ses aay os es rine ee os oo oe ee os eS a os = --= ~~ ——— . = es — os citi — SS * insound.Beep( time.sleep(p) ‘The start ofthe code imports the Winsound and Tie modules; remember, thisisa Windows-only Python script. The variable t Issettng the duration while p equals.5, which youcan use for thetimesleep Function, ‘These variables set the Frequencies, with the corresponding ‘numbers, which can be used inthe next section of the code, \winsound.beep requires. frequency and duration within the brackets. The Frequencles come from the large set of variables called in the second section ofthe code and the duration is through the t variable set atthe start ofthe code. There's a halFsecond, using the variable p, pause between blocks of winsound)beep statements. ‘wovabepublications com cin) Sa er eee eee eR a ell aT =Towe ee a) Soa) Biotec ee way to build your Python coding ELISE eon ai Lola er time. This example'that we created Seat taee-lakoRr) ale) Aer ata da wilt 4 end [ UB to you © ADVENTURE.PY The Adventure game uses just the Time module to begin with, creating pauses between print functions. There's a help system in place to expand upon, as well as the story itself. import time print(*\n" * 200) pint ‘s>>sp>>0p Awesome Adventurecccecec”) rnane=input("> *) print(nane, “the barbarian, sword in hand and looking for adventure!”) tine. sleep(t) print(*However, evil ie lurking neazby....”) time. eleep(2) PEint("A pair of bulbous eyes regards the hero...") name, “prevail, and win great fortune...") ‘die by the hands of great evil...2”) time.sleep(2) eint("\n" #3) print (‘Only time will tell...”) time.eleep(t) print...) time. sleep(2) time. eleep(2) Print...) time. sleep(s) Eint(*\n” #200) peint(”” Little gold in your purse but your sword is sharp, and you're ready for adventure. With you are three other customers, A ragged looking man, and a pair of dangerous looking guards."") You find yourself at a amall inn, There's def start) print(*\n ~ D print(‘Do you approach the...”) print (*\n") rint("l, Ragged looking man”) print("2, Dangerous looking guards”) endlist=["1", "2 endegetend(endlist) Text Adventure Script Af ond ==": def getemd(cndlit) zagged() elif ond = 2" guards() elif ond == "help": def ragged): print(*\ninter your choices as detailed in Eint(*\n" * 200) the game.”) rint(""You walk up to the ragged looking man and print("or enter ‘quit’ to leave the game”) greet hin. return getend(cndlist) He smiles a toothless grin and, with a strange elif ond == “quit”: accent, says, print (”\n- = “Buy me a cup of wine, and I'll tell you of ‘tine, sieep(2) cD print(‘Sadly you xeturn to your homeland without, def guards(): exit) eint(*\n” #200) rint(/You walk up to the dangerous looking guards and greet them. S€__name_ ==" _main__ The guards ook up from their drinks and art ‘nazi at you. Swat do you want, barbarian?” One guard reaches for the hilt of his sword..."") time, sleep2) Adventure Time This, as you can see isjust the beginning ofthe adventure and takes up afar few lines of code. When you expandit, and weave the story along, youll ind that you can repeat certain instances such asa chance meeting with an enemy or the ike, We've created each of the two encounters as adefined set cof Functions, along with list of possible choices under the pane cmdlistist, and cmd variable, of which also a defined Function Expanding on thisis quite easy, just map aut each encounter and choice and create a defined Function around it, Providing the user doesnt enter quitinto the adventure, they can keep playing, There's also room inthe adventure Fora set of variables designed For combat, luck, health, endurance and even an inventory or amount of gold earned. Each successful combat situation can Feduce the main character's health but increase their combat skills endurance. Plus, they could loot the body and gain god, or earn gold through quests Finally, how about introducing the Random module. Ths will tenable you to include an element of chance in the game. For example, in combat, winen you strike an enemy you will do a random amount of damage as willthey. You could even work out the maths behind improving the chance ofa better hit based on your or your opponent's combat skis, current health, strength and ‘endurance, You could create a game of dce inthe inn, to see if you ‘win or lose gold (again improve the chances of winning by working ‘out your luck Factor into the equation, Needless to say, your text adventure can grow exponentially {and prove to be a work of wonder. Good luck, and have fun with your adventure. ‘wovabepublications com eRe) ae Ee eee a ene el) ra a Ieee ci i roe [2 You may be surprised to hear that one of the:snippets of code we're lier olla eo aos scrolling’ ticker. Whilst we've covered various forms of scrolling text previously, the ticker is something that seems to keep’cropping up. So, ca eo Ticker Time The obvious improvements to the Ticker code le in the speed of the text and what the texe will display Otherwise you can change the backaround colour of the ticker window, the Fant and the font colour, along with the geometry ofthe Tkinter window i you want to. Yetanother interesting element that could be introduced s one ofthe many text-to Speech modules available for Python 3, You could pip install one, import then asthe ticker displays the tex, the text to speech Function will readout the variable atthe same time, since the entice texts stored in the variable labelled 's The ticker example can be used For system warnings, perhaps something that will display actoss your work o home network detailing the shutting down ofa server ‘ver the weekend for maintenance; or even just inform everyone a to wi TICKER.PY We're using Tkinter here along with the Time module to determine the speed the text is displayed across the window. Amport time import tkinter as tk oot = tk.7k() canvas = tk.Canvas(root, root.title("Ticker Code”), hheight=80, width=600, bg="yellow”) ‘canvas.pack() font = (‘courier’, 48, ‘bold’ text _ width = 15 ‘Text blocks insert here. 1 = “This ie a scrolling ticker example. As you ‘can see, it’s quite long but can be a lot longer if necessary..." 22 = “We can even extend the length of the ticker message by including more variables... “ 33 = “The variables are within the s-valves in the code. ‘st = “Don't forget to concatenate them all before the For loop, and rename the ‘spacer’ s-variable too.” 4 pad front and and of text with spaces a5 =" text_ width f concatenate it all vata text = canvas.create _text(x, y, anchor='nw’, textes, font=font) axed dy = 0 # use horizontal movenent only ff the pixel value depends on dx, font and length of text Pixels = 9000, for p in range(pixels) # move text object by increments dx, dy 4 -dx -> right to left canvas.nove(text, dx, dy) canvas.update() # shorter delay ~-> faster movement. teime,sle0p(0.005) dprint(k) # test, helps with pixel value ‘root. ainloop() ( Python Scrolling Ticker Script/Simple Python Calculator Simple Python Calculator Sometimes the simplest code can be the most effective. Take for example, this Simple Python Calculator script. It’s based on the Create Your Own Modules section seen earlier but doesn’t utilise any external modules. CALCULATOR.PY We created some Function definitions to begin with, then lead ‘onto the user menu and inputs. I's an easy piece of code to follow and as such can also be expanded well too. print’ Simple Python Calculator def addtx, y): return x+y def subtracts, y): return x - y def multiply(x, ¥): return x * y def divides, y): return * / ¥ print("Select operation \n") print("1.add") print ("2 Subtract”) print (‘3 Multiply") rint("4.Divide") choice = input("\nEnter choice (1/2/3/4):") ‘puml = int(input("\aznter first number: °)) ‘nun? = int(input ("Enter second number: )) Lf choice == W's Print (numl,"+";mun2,"=", add(numl,mumn2)) elif choice == 12': Peint(quml,"-";num2,"=", subtract (numl,mum2)) elif choice == 3': ‘Print (numl,"*";mun2,"=", multSply (num mum2)) elif choice a= 4’: PEint(quml,"/";num2,"=", divide(numl,nun2)) else: print ("Invalid input”) Improved Calculations The obvious contender For improvement hereis using the Create Your Own Modules route and extracting the Function definitions asa module. You can then call the module and Focus onthe body ofthe code, ‘The other area of improvements code itself. Where there's Justa single shot at making a calculation, you could encase it in awhile 'oop, so once a value i presented the user is sent back tothe main menu. Perhaps, improvement to the Invalid Input section is worth looking into as well ‘wovabepublications com Se it~ ee 0 sf =Towe Ne ott e ea ee) Sed Te) eae er eee eee © Pe Deere eeica etc) ih euM een erg complex, displaying graphics, the Cul eL meme esto (Clim an eal word, a\huge bank of available words picked at random Ear) faolt alec eng ees It c) El yeoaey erica Prats ers NUS Fy ts Prine etal aA eo eS a oy Ch) 4 f = n7 HANGMAN.PY We've made a Hangman game board (the gallows) out of characters that can be displayed in the IDLE Shell, along with a huge bank of words to randomly choose from import random board = [0 > ppoppoplangmancecceeccee lass Hangman: def __ init __(self;word): self.word = word If.missed letters = (] self.guessed letters det quess(selt, letter): Af letter in eelfword and letter not in self. guessed _ letter ‘self.guessed _ letters append(letter) elif letter not Un self.word and letter not in f.missed letters self.nissed _letters.append(letter) ‘return False return True def hangman _over(sel£): return self.hangman__won() or (len(self.missed _ letters) = 6) ef hangman _won(self): Af \_' not dn self.hide _word(): seturn True return False def hide _word(selé): tn =) for letter in self.wor’ Af letter not in self.guessed_ letters: Sen else: tn 4= letter return ren def print _game_ status(sels): print (board{len(self.missed _letters)}) print (Word: ‘+ selfhide word()) print (‘letters Missed: *) for latter in self.missed letters: Print (letter,) print () print (‘Letters Guessed: for letter in self.quessed letters: print (letter,) print () def rand _word): ‘bank = “ability about above absolute accessible accommodation accounting beautiful bookstore calculator clever engaged engineer enough handsone refrigerator opposite socks interested strawberry backgammon anniversary confused dangerous entertainment exhausted impossible overweight temperature vacation scissors accommodation appointment decrease development earthquake environment brand environment necessary ( Hangman Game Script luggage responsible ambassador circunstance congratulate frequent’ split() return bank{random.randint(02en(bank))] dof main() ‘game = Hangman(rand_word() while not gane.hangnan _over(): ‘game print _ game _ status() user _inpat = inpat("\nEnter 2 letter: ') ‘gane Guess(user _ input) ‘gane.print _game_status() if gane hangman _won() print (‘\aCongratulations! You have won!"”) else: print (\nSorry, you have lost.’) print (‘The word wae ' + game.word) Print ("\nGoodbye!\n') Quit) Since this is the last example in our Python code repository, we thought we'd go out with abang and Feature the hangman gallows being drawn with each incorrect quess of the word. Don't worry fit looks misalignedin the text here this s merely due to the differences between using the Python IDLE editor and pasting the cade into a word processor (which Formats things different. There's plenty you can do to improve, enhance and expand on What we've presented here. You can include a routine that Fetus an error ifthe user enters a number or character, You canlnclude extra points For someone who guesses the entire word in one go rather than one letter at atime and you could perhaps add Chopin's Funeral March should you lase the game ‘or something celebratory you win, Consider replacing the bank of words too, They're Found under the bank ist, and could easily be swapped out for something ‘more dificult IF you download www github, com/dwyVenglish words you can find a text document with over 466,000 words. Perhaps you could swap the wordsin the bank to instead read the contents ofthe text ile def rand word): ‘with open(’/hone/pi/Downloads/vords.tet”, "rt") as fi ‘bank=£.readlines() return bank(zandon.randint(0,2en(bank))] ‘wovabepublications com Suc lpi) a Lees 9 Rae Uniestndroinn COE Linuxis a remarkably versatile and powerful operating system. It’s used throughout the programming and engineering world, in science, space exploration, education, gaming and everything else in between. It's the OS of choice For high-performance servers, it’s the backbone of the Internet and it powers the Fastest supercomputers in the world. Knowing how to use Linux, and how it’s structured, is key to being able to create better Python content. The Raspberry Pi, for example, uses a Linux-based OS and, as such, makes for an excellent coding platform, Regardless of whether you're using a Pi, like us, ora Linux Mint or Ubuntu, these pages will prove invaluable for your Python learning. Master Linux, master Python, and start engineering your coding Future. What is Linux? 140 _ Using the Filesystem 142 _ Listing and Moving Files 144 Creating and Deleting Files 146 Create and Remove Directories 148 Copying, Moving and Renaming Files 150 Useful System and Disk Commands 152 _Using the Man Pages 154 Editing Text Files 156 Linux Tips and Tricks 158 _AZof Linux Commands Glossary of Python Terms vowubdmpubteationscom QE What is Linux? SO ec senate etn cana coum eee eran Ee caats what exactly is Linux? Where did it come From and what does it do? Ina world where Aine foME- are Le@ SMM R Teun la Rell en Relat) Me Ac KK ColeL alent Reeeuerte dae UR nue s mela Linuxis a surprisingly powerful, fast, secure and capable operating system. It's used as the OS of choice for the Raspberry Pi the Form of Raspbian OS, as well as in some of the most unlikely places. Despite only enjoying 2 1.96% share (according to netmarketshare, Torvalds needed a system that could mirror Unix's performance and com) of the total desktop operating systern market, Linuxhas 8 Features, without the licensing cost. Thus was born Linux the dedicated Following of enthusiasts, users and contributors. Iwas _Unixlke operating system which used freely available code from ‘created in 1991 by University of Helsinki student, Linus Torvalds, _ the GNU project. This enabled users around the world to utilise the ‘who had become frustrated with the limitations and tcensing of the power ofthe Uniske system, completely free of charge, an ethos ‘popular educational system Minx, a miniature version ofthe Unix that sil holds today: Linux's Free to download, install and use. ‘operating system, in use atthe time, Linux is much ike any other operating system, such as Windows or Unix itself was released in the early'70s, asa multitasking, modular- _macOSin that t manages the computer hardware, provides an designed operating ystem originally developed for programmers interface forthe user to access that hardware and comes with ‘who needed astabe platform to code on. However, its performance, programs for productivity, communications, gaming, science, power and portabilty meant thatt soon became the system of |—_—_education and more. Linux can be broken up into a number of choice for companies and universities where high-end computing _signiicant elements: tasks were needed “The bootloader is the software that intalises and boots up ‘your computer. Itloads up the various modules the OS uses to begin to access the hardware inthe system, You can modify bootloader to load more than one OS installed on the system. ‘Thisis a module within Linux that provides a graphical output toyour monitor. t's referred to asthe Xserver or simply jst X.Xis an application that manages one or more graphical displays and one or more input devices (keyboard, mouse, etc) connected to the computer. Daemons are background services that startas the operating systems booting. These can enable printing, sound, ‘networking and so on. They run unobtrusively rather than Under the direct control ofthe user, often wating to be ‘activated by an event or condition, “The kemel s the core of the system and the single element thats actually called Linux. The Linux kernel manages the computer processor, memory, storage and any peripherals you have attached to your computer. It provides the basic services Forall other parts of the OS. ‘The Desktop Environment, or DE, isthe main Graphical User Interface (GUN that users interact with. I's the desktop, that includes internet browsers, productivity, games and whatever program or app you're using. There ae countless DEs ‘avaliable. Raspbian uses PIXEL \With Linux being an open source, free operating system, it also makes use ofthe tens of thousands of freely available applications. The likes of LibreOffice, GIMP and Python are just the tip of the icebera.

Vous aimerez peut-être aussi