100% found this document useful (2 votes)
2K views164 pages

Coding For Python - 2020-06

Python

Uploaded by

David
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (2 votes)
2K views164 pages

Coding For Python - 2020-06

Python

Uploaded by

David
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 164
Codin« for Pyt // you need to know about Coding al Peles: SFUTIT0100 DOWNLOAD Ca ere USBlack Dog Media Master Your Tech To continue learning more about your tech visit us at: [Link] 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 | [Link]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 Qees 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 Platformz= 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 [Link] 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 eePar 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 [Link], the compiler she developed became }BOL (Common Business-oriented Language), a computer language that's ee cdWhat 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) wonbampubtistionscomRTI 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 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 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. [Link].*; ‘lass. tnvoke { Oe ublic static void main( string (] args ) ¢ try Glass ¢ = Class. fornane( args[0] ); Method'm = [Link]( args{1], néw class Ot} Object rét = [Link]( 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 osae 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 oez= 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, [Link] 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 [Link](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 [Link] 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 resourz=» 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 [Link]. 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 [Link] 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) sirosicioncanHow 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 [Link] 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 CommandHello, 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//[Link]/ 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 [Link].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 ‘[Link]/3/library/[Link], which details many of the IDLE's Features sworabdrmpubicatonscom — ESED) 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 comHello, 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, 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: ssan (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 [Link] 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 bdmpublicationscomC) 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: seinenHello, 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: [Link]/'/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 OeC) 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 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/[Link]”, “r”) [Link]“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.”) ‘[Link]) 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: [Link](“This is a test. Normal service will shortly resume!") finally: print (“Content written to file successfully. Have a nice day.") ‘[Link]) 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 [Link] 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 [Link]©) ‘img = pygame. image. LoadC*RPi .pna”) white = (255, 255, 255) w= 500 eT h= 450 fee ‘screen = [Link]. [astern eran setnodeccn, h)> screen. fill(Cvitite)) screen. fill(viite)) screen. bliting, (0,0) Pygane. display. fiipC) hile True: for event in [Link](): if [Link] = 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()) 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 PeeteC2) 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 [PreUsing 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 89ED) 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 vmbdmpubicatonscomC 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 [Link](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/[Link]”, “w") [Link](calendar SUNDAY) [Link](c. formatmonth(2019, 1)) [Link]) ‘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)) [Link]) “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 [Link](“/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 [Link]( 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 [Link](*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 [Link](‘chromium-bronser “http:// ‘bdmpubLi cations. com/”*) [Link]¢“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/? + [Link]() 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: //[Link]”’) os. system(a + b) if not [Link]-exists(dst_dir): [Link](dst_dir) for file_ in files: srcfile = [Link](src_dir, file_) dst_fle = [Link]. join(dst_dir, file) if os. path.existsCdst_file): os. renoveCdst_file) [Link](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([Link]) ‘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 [Link] Uibrary/[Link] for alist of available Math module Functions. ora vémpublications comUsing 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 [Link]() *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) [Link]() y=(600°0.8) runningsTrue [Link]) while running: spritecx,y) gamewindow=pygane di splay. set_node((800,600)) ——aa [Link].set_captionC*Adventure Gane”) for event in [Link] .get(): black=(0,0,0) ‘if [Link]==pygame QUIT: white=(255,255,255) FSTeGEERD [ts cuickly go through the code changes. We've downloaded image caled [Link] 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 [Link] [Link](vhie) a Sprivecxy3 Braane: display vpdacec) merindowpyzane display set_mode((800,600)) Bese: diapiaysetcaption(-haventre cone") scke(0.0"0), ‘or event in [Link]. get): wntten( 255,235,255) i Gventypers@utT Sne-pysanesnage-load{~/hone/pi/Donnloads/[Link]") 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 [Link] import * pygome. init@) running=True ‘ganewindow=pygane. display. set_modeC(800, 600)) [Link].set_caption(“Adventure Gane”) black=(0,0,0) ihite=(255,255,255) ‘imgepygame image . load “/hone/pi/Downloads/spritel. png”) def sprite(x,y): ‘[Link], x=(800*0.45) y=(600*0.8) xchange=0 Gy imgspeed=0 while running: for event in [Link](): if [Link]=QU running=False ‘if [Link] == pygame. KEYDOWN: Af event .key==pygame. K_LEFT: xchange=-5 elif event. key==pygame. K RIGHT: xchange=5 ‘if event. type==[Link]: ‘if event. key==pygame.K_LEFT or event keye=pygame.K RIGHT: xchange=0 x 4= xchange [Link]) sprite(x,y) pygame. display. updateC) [Link]) 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 [Link]© screen = [Link].set_mode((800, 250)) clock = pygane. [Link]() font = pygane. font .Font(None, 25) Pygane. time.set_timer([Link], 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 ‘[Link] = False self. font = font [Link] = text self._gen = text_generator(self. text) self.p0s = pos [Link] = autoreset [Link] def reset(self): self..gen = text_generator([Link]) [Link] = False [Link] def updateCself): if not [Link]: try: [Link] = self. font. rendernext(self.-gen), True, (@, 128, @)) except StopIteration [Link] = True ‘time. sleep(10) subprocess. Popen(“‘python3 /hone/pi/Documents/ Python\ Code/[Link] 1”, shellsTrue) def dran(self, screen): [Link]([Link], [Link]) 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 [Link](): if [Link] = [Link]: break if [Link] = [Link]: message. update else: screen. fill([Link]¢‘black”)) message. dran(screen) [Link]) Clock. tickC60) continue break [Link]() 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] = 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 = [Link].set_node((640,480)) [Link]. set_caption(*Starfield Similation”) clock = [Link] init_stars¢screen) while True: # Lock the franerate at 50 FPS clock. tick(50) # Handle events for event in [Link](): if [Link] == [Link]: return [Link]((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’ [Link]. 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 — QUESz=» 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 [Link] 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(“[Link] by two”) rat = Snipa tree mer: >) print¢*[Link] by Taree”) print¢“3. Square”) print(“[Link] 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("[Link] by Thi irint("[Link]") print([Link] 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 PietersBEYOND 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¢[Link] 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 tidapne 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 eeseae 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. [Link] Copy the code below into a New > File and save it as [Link]. 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 [Link]. 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:") £¢ [Link] 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([Link](path)) i=0 whileticlen(sortlist) rintleortlistii}¥"\q") ied et check) Apsint(input ‘Check existence of \[Link] \n2 Directory\n')) SE spent: pathsinput("Eater the file path") ‘[Link](path)Lf os path Laftte(path)=tzue print('File Found’) rint('File not found!) it tpo=2: path=input (“Enter the directory path") (os [Link](path) Af [Link](path)=False: print (‘Directory Found’) Print (‘Directory Not Found’) input (‘Enter the source path of fle to moves") BBe=int input('L Rename \[Link] \n)) Af meet: path2input(‘Enter the destination path and file names’) ‘[Link] 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 [Link] (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 \[Link] Directory Tree \[Link] \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: | [Link](’clear’) | except OSError: | [Link](‘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 oeCode 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 = [Link](l, 20) luck = [Link](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 [Link]Random Number Generator User input and theability to [Link] 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. [Link] 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() [Link] _ uppercase + [Link] _ lowercase + string digits sizes 8 return join([Link](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=[Link] _ uppercase + [Link] _ lowercase + string digits sizes 4 return Yjoin([Link](chars) for x in -range(siz0,20)) 0 white n>>>>>>>>>Text to Binary Convertor osssppoootext to Binary Convertorccceccccce\n") conversionsinput("Enter text to convert to Binary: *) ‘size = (600, 00) ‘screen = [Link] _node(size) Text to Binary Convertor Pygane [Link] _ caption("Binary Conversion”) eee clock = [Link]() ‘text _rotate degrees = 0 Binary=(’ ‘Join (format ord(x), in conversion)) wy fore while not done: for event in [Link]() Af event type == pygane. QUIT SSS screen 611 90HrTE) font = [Link]('Calibri’, 25, True, False) text = [Link](Binary, Teve, BLACK) text = [Link](text, text _ rotate _ degrees) text _Fotate degrees += 1 [Link](text, (100, 50)) [Link]() ‘lock. tick(60) [Link]() Print(’ ‘join(format(ord(x), °b") for x in conversion)) vevoubdmpublationscomere AU EU eMNeci-iene} folie heliteelel le Ne Waste file browser that's presented ina graphical usef interface using the Tkinter [Link]'s a lobyou can Tirol baalceeete Reale) -lal [Link] 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 [Link] import Serolledcanvas, Filefreeltem, TreeNode import 0s oot = Tk() [Link]("File Browser”) sc = Scrolledcanvas(root, bg="white”, highlightthickness=0, takefocus ‘[Link] pack(expands1, fill="both”, side="left”) stom = Filetrestton([Link])) node = TreeNode([Link], None, item) [Link]) 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 = [Link]¢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 ‘[Link] _ command(label = ‘open’, command = Opentile) fron tkinter import * ‘[Link]~ conmand(iebel = "Exit", command = zon thinter import tek ambda:exit0) ‘ron [Link] import askopentilenane [Link] _cascade(iabel = ‘File’, mens = Se) root = TK( ) [Link]() 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 comWe've already seen the Turtle [Link] [Link] 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 [Link](click _handle:) dof click _handler(x, y): [Link](Wone) # disable event inside ‘event handle [Link]\[Link](x, y)) [Link], y) screen onscreenclick(click handler) # reenable ‘event on event handler exit [Link](ki0l, “ ") # space turns on mouse drawing ‘screen. Listen() Clare Rees er [Link]() 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. [Link] This code is designed for use in the command prompt, be that Windows, Linux or macOS. There are some instructions on how [Link] 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 = [Link] Lea = len([Link]) Af tsa '= 2) print ("Usage: [ python3 ] [Link] 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.”) [Link]() try: ‘minutes = int(ea(t]) except Valuezrror: print (‘Invalid numeric value (ts) for minutes” ¥ sa(1)) Print (‘Should be an integer >= 0") [Link](1) Af minutes = 0") [Link](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”) [Link]() 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 [Link] 20 ‘Again, you could easily incorporate this into @ Windows batch fileand even set a schedule to activate the alarm at certain, times ofthe day [Link]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 [Link] 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 [Link] import * [Link] 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 [Link] = 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 = [Link](‘Arial’, [Link]) ‘text = [Link]{sessage,rue,[Link]) rect = [Link] _rect{center = ([Link]. centers, [Link] + self.buff_centery) ) dof make _surtaces(selé) [Link] = (J for i, Line in enunerate(self.1st): 12 selé.make_ text(Line) Lpy += iselZ bute Lines [Link](1) def update(sels): Af [Link] _ ticks()-[Link] > [Link]: [Link] = [Link] _ticks() for text, rect in [Link]: recty -= 1 def render(self, surf): ere =p [Link].09) for text, rect in [Link]: seeversstiao™ [Link](text, rect) screen = [Link] _ mode((800,600)) screen _ rect = screan.get_ rect() lock = [Link]() running=True cred = Credits(scr sn _rect, text _ list) while running: for event in [Link](): if [Link] == QUIT: running = False screen, £11((0,0,0)) [Link]() ered. render(ecreen) [Link]() clock tick(60) vw [Link]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) [Link] 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? [Link](text=time2) [Link](200, tick) oot = [Link]() 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 [Link] classmethod def main(cls) [Link] root = [Link]() [Link]('stop Watch’) [Link](True, False) [Link] _colunnconfigure(0, weights) easier ‘Stopkatch(root, padding) laget geidintchprointer SEH, padding [Link]() 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=[Link], **padding) det _ _elick(eeis) if Sele. _ _button{'text’) == ‘start’: Tbietont'text'] = 'stop" Toatart = [Link]() Toounter = self after _sdle(eelf, _ pate) f,___button['eext’] = ‘start’ jelf after _cancel(self._ _ counter) det _ _update(cele): ‘ow = [Link]() ‘wovabepublications comol — a ef) Toye TNE eke eer ed) ia ee Ieee © Playing Music with the (ol Ree lt mic leno mee r-In| [Link] 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): [Link]( 1¢, 2+) winsound Beep( RC, t) [Link]( hE, t) [Link]( 6, t) [Link](p) "Naturally you can swap out the [Link] 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, [Link]( 16, 2+) winsound Beep( 6, t) [Link]( 8, t) [Link]( 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 [Link]( 1A, 2+t) Intro by entering winsound Beep( A, t) [Link]( hc, t) [Link]( hE, t) — - == [Link]( 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 * [Link]( [Link](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, \[Link] 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 comcin) 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 © [Link] 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”) [Link](2) eint("\n" #3) print (‘Only time will tell...”) [Link](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 comeRe) 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 [Link] 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 = [Link](root, [Link]("Ticker Code”), hheight=80, width=600, bg="yellow”) ‘[Link]() 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 = [Link] _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 [Link](text, dx, dy) [Link]() # 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. [Link] 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("[Link]") print ("2 Subtract”) print (‘3 Multiply") rint("[Link]") 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 comSe 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 [Link] 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 > ppoppoplangmancecceecceelass Hangman: def __ init __(self;word): [Link] = word [Link] letters = (] [Link] letters det quess(selt, letter): Af letter in eelfword and letter not in self. guessed _ letter ‘[Link] _ letters append(letter) elif letter not Un [Link] and letter not in [Link] letters [Link] _letters.append(letter) ‘return False return True def hangman _over(sel£): return self.hangman__won() or (len([Link] _ letters) = 6) ef hangman _won(self): Af \_' not dn [Link] _word(): seturn True return False def hide _word(selé): tn =) for letter in [Link]’ Af letter not in self.guessed_ letters: Sen else: tn 4= letter return ren def print _game_ status(sels): print (board{len([Link] _letters)}) print (Word: ‘+ selfhide word()) print (‘letters Missed: *) for latter in [Link] letters: Print (letter,) print () print (‘Letters Guessed: for letter in [Link] 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{[Link](02en(bank))] dof main() ‘game = Hangman(rand_word() while not [Link] _over(): ‘game print _ game _ status() user _inpat = inpat("\nEnter 2 letter: ') ‘gane Guess(user _ input) ‘[Link] _game_status() if gane hangman _won() print (‘\aCongratulations! You have won!"”) else: print (\nSorry, you have lost.’) print (‘The word wae ' + [Link]) 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/[Link]”, "rt") as fi ‘bank=£.readlines() return bank([Link](0,2en(bank))] ‘wovabepublications comSuc lpi) a Lees 9 RaeUniestndroinn 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 QEWhat 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 [Link] 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.

You might also like