0% found this document useful (0 votes)
161 views

2022-07-23 Python For Beginners

Python

Uploaded by

Anzu Hossain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
161 views

2022-07-23 Python For Beginners

Python

Uploaded by

Anzu Hossain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 94
eat moe Te Leear: V Clear Full Colour air Want to master your Code? Then don’t miss our NEW Programming & Coding magazine on Ei Readly now! Click our handy link to read now: Python For Beginners Starting something new can be daunting, Learning a skill or mastering a new piece of hardware is tough. Even tougher if you have no-one at hand to help. Conversely as the complexity of our consumer technology increases, the size of the requisite instruction manual decreases or in some cases it simply disappears. At numerous times in our lives we have all been “beginners”, there is no shame in that fact and rightly so. How many times have you asked aloud, “What does this button do?”. “Why doesn’t that work?”. “What do you mean it doesn’t do that?”, "HELP!". At the start of any new journey or adventure we are all beginners but fortunately for you we are here to stand beside you at every stage. Over this extensive series of titles we will be looking in great depth at the latest consumer electronics, software, hobbies and trends out of the box! We will guide you step-by-step through using all aspects of the technology that you may have been previously apprehensive at attempting, Let our expert guide help you build your technology understanding and skills, taking you from a novice to a confident and experienced user. Over the page our journey begins. We would wish you luck but we're sure with our support you won't need it. Hello World 26 28 30 32 34 36 38 40 a2 Equipment You will Need Getting to Know Python How to Set Up Python in Windows How to Set Up Python in Linux Starting Python For the First Time Your First Code Saving and Executing Your Code Executing Code from the Command Line Numbers and Expressions =o renee Das: eee Sanat 10 ABrief History of Coding Cae turmetal arse ON Ta ee MURS oud aun iss 22 Creating a Coding Platform Using Comments Working with Variables User Input Creating Functions Conditions and Loops Python Modules Python Errors Combining What You Know So Far Python in Focus: Stitching Black Holes Working with Data Us meena Cae eae gies Cea eae ie Pues e iran cd Sagres ged cy eee 86 RTM aur y Python in Focus: Gaming MT i ae ase ae Sa aT 5 § s = g 3 = with the help of our Fantastic Code Portal, featuring code for games, tools and more. eee im a Re ru | i) a Getting Started EEC cusresty sectarian) ONE aor eel eo RU eS Recreate nt emcee nee ss Cache miei tiene cel eater Ithas been devised to work on a human level, so it's readable PC enemies ok eer secy Nea dere er ec criceeeey Oe eee teen ee cane eaie| Ete e toro Price SG a nau ne ius eeu Pat tenes ecu eau en Ca Dee ea ee en ae cues used in the space industry, and in science and engineering. ener eine acai Assistant all utilise Python For their powerful voice recognition technology. It's simply an amazing, versatile and incredible language to learn. Seen cen ccm ance rue) Cee eee Being a Programmer Letelel Le ACC) CR eore a AE EIN econ ET Leet) 18 Ten RAT) Cetera M mecca omen i een aclite nie core cE Meglae-10-(uat ulola mofo Ke MaMa aL s[olgt-] Os) 95-16 Bo =] Moon (elt cela E| programmer though? ‘Times have changed since programmir but the core values still remain, “It's up to you how far to take your coding adventure!” om = S eee mn om as Being able to follow a logical pattern and ‘see an end results one ofthe most valued skills oF a programmer. C Being a Programmer Cll 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 asa 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 alarge plastic box. However, it wasn't so much the new technology that ‘computers then offered, moreover it was the Fact 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 atthe time, many users decided they wanted to create their own content, their ‘own games; or simply something that could help them with their homework. ‘or home finances. The simplicity ofthe &-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 t wasn't long before the bedroom coder was a thing of the 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 wito could Fashion a sprite on the screen and make it move at the press of akey. Naturally, time has moved on and with itthe technology that we use However, the fundamentals of programming remain the same; but what ‘exactly doesit take to be a programmer? ‘The single most common trait of any programmer, regardless of what they/re doing, isthe 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 sucha person, itis possible to train your brain into this way of thinking. Yes, it takes time but once you start to thinkin this particular way you will be able to construct and Follow code. ‘Second to logics 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 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, asa programmer, you will be part ofa team ‘of other programmers, and more than likely part of an even bigger team ‘of designers, al of whom are creating a Final product. While you may only be expected to create a small element of that final produc, 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 will interact 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, it's up to you how Farto take your coding adventure! A Brief History of Coding It’s easy to think that programming a machine to automate a process, or calculate a value, eMule eed Leno A) Coe aN Coe assumption is quite wrong, coding has actually been around For quite some time. RRR MMMM MCMC OMOM OROCLO Essentially all 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 50 AD 1842-1843 1930-1951 dated to about 67 ancient Greek analogu and orrery used to pre ‘The Bani Mis brothers, three Persian Een nite ecm eters Cer eet Cees eee eens Erne enero teaia Sc Ce eee eae een punched holes to create the textile desig. east Geena cea en eats Ada Lovelace tran the memoirs of th her writing, detailing ‘method of calculating recognised asthe First ‘computer program. Not Pt nt From the 1970s, the development ofthe likes of C, SQL, Cwith Sees ‘lasses (C++), MATLAB, Common Lisp and more, came tothe Cue eu oe Fore. The 80s was undoubtedly the golden age ofthe home. eens ‘computer, atime when silicon processors were cheap enough for Cente ‘ordinary Folk to buy. This led to.a boom in home/bedroom coders, Pee eee en feaes with the rise oF bit machines. Reeth eae com Cee ey esr ny rie Cees ‘Computer programming ‘was mainly utilised by ‘universities, the military and bg corporations during the 60s ‘and the 70s. Anotable step toward a more user-friendly, ‘or home user, language w the development of BASIC (Beginners Altpurpose ‘Symbolic Instruction Code) in the midsinties. ‘Objective-C Dee eee ad eee errs) terres eerie aoe saseseae MAAN MR Yee ea ree Dee eee get a eee ee Deere se Per asetens Coleg eer ‘Admiral Grace Hopper was part of aces the team that developed the UNIVAC ie | computer and she eventually Ce Me rr) developed a compiler fori eens the compiler she developed became eer rts COBOL (Common Business-oriented Ee ee Orr eal Language), a computer language: Ere ners stillin use today. What can You Do with Python? Python is an open-source, object-oriented programming language that's simple to understand and write, yet also powerful and extremely malleable. It’s these Centrale CeMegr an MUL ete TM UN oceans Urcel ane Python's ability to create highly readable code within a small set lots of examples of this, where Python is acting behind the ‘oF instructions has 3 considerable impact on our modern digital _scenes. Ths is why it’s such an important language to learn, ‘world. From the ideal, Fist programmers’ choice tots ability to itt ‘create interactive stories and games; from scientific applications to ences eer ss ee ia er ays Dee ener ar eee ang ‘many different situations and roles, Even certain aspects of the ‘coding world, that require more efficient code, still use Python, MMe prec cue cae ‘and as a bridge between other programming languages. This way, Reena ey eee ee ace ty Fats Demat tere teeter ncn Peer eae eera er ment Big datas a buzzword you're tkely to have come across inthe last couple of years. Eee ert et ee See patterns, trends and interactions between humans, society and technology. OF course, its not just imited to those areas, big datas currently being used ina variety of Industries, From social media to health and welfare, engineering to space exploration Sn Python plays a substantial role inthe world of big data. I's extensively used to analyse hhuge chunks ofthe available big data and extract specific information based on hat the user/company requites from the wealth of numbers present. Thanks to an Cee ee ee ee eer ae aa eee ey Ce eee ce ane) useable for humans. ee ere eter ere eee eaten tan ee ee et ea ou ese ecu eo eu cay =e Pe seeroeer torent re en ee , Sec oe cena ioe Eee erent Tent es Ct ee pets i: ete 12 vwbdmpublcations com ARTIFICIAL INTELLIGENCE Atifcal intelligence and Machine Learning are two ofthe Ce eel eet ue eA umbrella term used for any computing process wherein the ‘machine is doing something intelligent, working and reacting ee oc eet se Pe ee ee eT ne teers Cea eer eee cue Ce as ae eae Ee ce eu eee ee eee Tee ee ay from the actions of some Form of input and anticipate what ea et Dace note ROG Instagram and so on. Have you ever looked up a celebrity on Instagram and then discovered that your searches within other social media platforms are now specifically targeted toward similar celebrities? Thisis a prime example of using Alin targeted advertising and behind the code and algorithms that Peete odor is SC cute rr) ther things to analyse your musa nabs nd SY) offer playlists based on what you've listened to padeeearaerni en eee ee earn bceeu eel tin 1 WEB DEVELOPMENT \web development has moved on considerably ince the early days of HTML scripting ina limited text editor. The mary frameworks and web management services available now ‘means that building a page has become increasingly complex. ‘with Python, the web developer has the ability to create dynamic and highly secure web apps, enabling interaction with ‘other web services and apps such as Instagram and Pinterest, Python also allows the collection of data from other websites and even apps built within other websites. Foi atl ay x Eeed Athough you wontfind too many triple-A rated games coded using Python, you may be surprised to learn that Python is used as an ‘extra on many ofthe high ranking modem games. aPython: ne, Many map editors are Pythor ‘come acrosstif you build any mods For ames, such as The Sims. misations tothe mpatible and 1 Game) games available utilise Python as a companion 9 de elements, These include: code to search For potential cheating, rs pla ‘As you can see, Python is quite a versatile Dee ea ay Ne ote red ‘able to take you into the next generation of Saeco ened eooie See Le Ce ee ees eng CED z= Getting Started ) 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. ap ‘Alexa, Amazon's Virtual Personal Assistant, uses ea, Python to help with speech recognition. Data analysis and Machine Learning are the two most used Python cca In PYTHON AND LINUX SKILLS. ARETHE THIRD 7 ., ‘yttonvesthemost _-- MOSTPOPULAR ints tendermon oftware discussed language on LT. SKILLS IN to operate between other hee SUC opis pecages sp - SOU yy os uni ~ Te, K 4 i 4% 2 ar 4 “% 2 & 2 2 w 75% > 90% ) €75% > = (a (a 0-5 % = S% = % = % F % % ¢ re “ys “Margy “Ment OVER TSH OF 50% OF AL irs ESTATES RESONMENDED rACeBOOR boars THAT OVER TC OF conTENT FROM NETPLK ane PUnERED NARS OREO cENERATED Pa Tange ETON AUTOMATE Coon BY PrHION ree THE SS, USE PYTHON. 16,000 fostosinene” feitiitt 6th teitiitt — ta : “MOST: SOUGHT-AFTER re are over 16,000 Python jobs posted every six months in the UK. JOBS IN THE UK. ‘\ G il i. Python Data Scienceis Googles the top Data Scence,Blockchain New York and San thought tobecome the company for hiring Python and Machine Learning Francisco arethe top ‘most sought-after job in developers, closely are the fastest growing Python developer cities the coming years. followed by Microsoft. Python coding skis. inthe word Python developers enjoy an average salary of = = == £60,000 ~(esx) Can) Crs) (ion) <> == za 95% OF ALL BEGINNER 75% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS: CODERS START WITH DEVELOPERS USE PROGRAMMERS USE 10 DEVELOPERS ‘AND STILLUSE, PYTHON 3, WHEREAS PYTHON ON A DAY-T0- USE PYTHON 3 PYTHON AS THEIR 25% STILL USE THE DAY BASIS, 21% USE AS THEIR MAIN PRIMARY OR. ‘OUTDATED PYTHON 2 ITAS A SECONDARY PROGRAMMING. ‘SECONDARY LANGUAGE. ‘VERSION. LANGUAGE. LANGUAGE. Getting Started Why Python? SEE ins eee eae seen a kcn rs tcn Pees een kaa cece lucia Tene ees | 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 until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. “These pioneers of programming carved their way into anew Regardless of whether you use an Android device, iOS device, PC, Frontier, Forging small routines that enabled the letter'N'to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device builtin ‘across the screen. Itmay not sound terribly exciting to generation toacar set-top box or thousand other connected and smart’ that's used to ultra high-definition graphics and open world, multi» appliances, behind them allis programming, player online gaming, However, Fortysomething years agoit was blindingly brillant. Allthose aforementioned digital devices need instructions to tell them what to do, and allow them to be interacted with, These Naturally these bedroom coders helped form the Foundations for __instructions form the programming core ofthe device and that core ‘every piece 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 to's limits and founded the The languages n use today differ depending on the situation, the billion pound gaming empire that continually amazes us. platform, the device's use and how the device wil interact with its arene Setcursor(p.y): ouoie | crtsontdeettcietl: oon oid Arrayctrl::chiLdLostrocue() ‘amore ‘ ifleursor >= 0) Befreshion cursor): centrchatabosteocust): Sears Paeee recta” Gratertmnse | void _Arrayctrl::Paint(Orave w) ( Stes Shonen ‘eTIMTnG( Paine Siete Gre Sheitie = eetlonds He stenoses cobotton Sseseece Star i recocn Br int a pm Sic, Het ig theadrsetaerott 0; nent Gren Far({e'= 0; 3¢ < column. cetcaune(); jst) ( [Siriouiae |G new vo av cx header. ceviabmadth(jai:) overheat GPCL ast ews verearad + Ue colum,ceteount() = 2)) >= 0) Somme sma reas 1 econ, fer ce v1 [Sessa rch Esler. fe. slendsclorisabled, scntrPaer; 4 A ee sate! catcaneg) ones 1 ese. gical eles Ero ity 9 1) Senn Beer far a : 00 11 1 gis Gee ce ort aati rcatomareson th aie O11 9 1 | a caenien | |Q Gtehm.ce, Ant on = columishsmrain: 90 48 Promessh Be eset 1 OT Weta Sri 01 O00 O10 T0101 00 oT000000 T1101 0 ‘environment or users. Operating systems, such as Windows, macOS. ‘and such are usually a combination of C++, CH, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and so.on, More general-purpose programming is used to create programs, ‘apps, software or whatever else you wanttto cal them. They/re ‘widely used across al hardware platforms and suit vitually every ‘conceivable application. Some operate Faster than others and some are easierto learn and use than others. Python is one such general purpose language. Python is what's known asa High-Level Language, in thatit ‘talks! to the hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless ‘more interactions. Whilst ts nat as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, ts benefits that i's universally accessible and easy to lear. [//Fi Te: tavoke java Finport java. lang-reflect.*; class _tavoke Public static void main( string [] args try Glass ¢ = Class. forname( args[0] ); flethod'm = c-getmethod( args{1}, new Class Object ret = m.invoke( null, null ); systen.out. princi Thvoked static method: " + args(2 + of class: " + args{o) with no args\nresults: "+ ret); catch ( ClassNotFoundexception e 77 Class. fornane(.) can't find the class arch” C Nosuchtethodexception e2 7 that method. doesn't exist Gaceh'¢ Tlepataccessexception 3 Fi*ve don't Rave permission to Snvake that fethod Beech ( rnvocationrargetexception 4 Zan exception ocurred white tnvoking that System. out print Tn Shethod threw an: " + ed, getTargetexception( ")): Javaisa powerful , a language that's usedin WE web pages,settop boxes, \ TVsand even cars. Python was created over twenty six years ago and has evolved to become an ideal beginner's language For learning how to program 2 ‘computer. t's perfect forthe hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves ora piece of external hardware and the computer itself. Python i free to download, install and use and is available for Linux, Windows, macOS, MS-00S, 05/2, 8e0S, IBM iseries machines, and even RISC OS. Ithas been voted one ofthe top five programming languages n the world andis continually evolving ahead of the hardware and Internet development curve. So to answer the question: why Python? Simply pu, i's Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational too. 42 LET py=15, 38 FoR b2i To 10 32 ces 28 CET py=rnT cRNDs28) 30 Let Bx=0. so 108 Pri y 170 xr boE No” ge $="2" THEN LET py ve ge IF INKEYSs"o" THEN LET py=P a 235 FOR n=1 TO 100: NEXT n ia0 iso 180 iss 190 200 210 220 300 BASIC was once the starter language that early ‘bit home computer users learned. Python s a more madern take on BASIC, it's easy to learn ‘and makes for an ideal beginner's programming language. e 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 ‘While having a far more powerful coding platform on which to write and test your code is ideal, it's not often Feasible. Most of usare unable to jump into a several hundred-pound investment when we're starting off and this is where the Raspberry Pi can berets PS ea cae cay Re ee ee ees ‘are unable to jump into a several hundred-pound investment when Rees ie ea ea ee itd So eg ne ce has created, of rather re-created, the Fascination we once all had ‘about computers, how they work, how to code and foundation level electronic. Thanks to its unique mix of hardware and custom software, ithas proved itself to be an amazing platform onwhichto eae tee ite hile you're able, with ease, to use the Raspberry Pi to learn to Ce ete ur on eee ie ca) Cae asec ee ree ers Pee eaten ere ee ett 05, or to be more accurate, it'sa Debian-based distribution of Linux. This means that there's already a built-in element of Python programming, as opposed to 2 fresh installation of Windows 10, cae ea ent eng) one a eet os eae eee eee Pe etn orem atc instructions on how to set one up (by using one of our excellent Pee eee Mens en er ei can start 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 ‘code in Python. The Piis remarkably easy to setup as aheadless node. This means that, wth a Few tweaks here and there, you're able toremotely connect to the Raspberry Pi from any other computer, ee ee cent Se een ea teu ets power socket anywhere in yourhouse within range of your wireless outer. As long asthe Plis connected, you willbe able to remotely Se ea ee Pena aE oe te Pe ae oe Pee eee eens see ord sufficient space to accommodate those extras either. F you're pushed Forspace and money, then for around £60, buying one of the many Sec kits available il provide the Pi witha preoaded SO card (with the Pees eRe tere eee ey et) idea as you could, with very litte effort leave the i plugged into the wall under desk, wile stil being able to connect to tand code. Seu ne en ee easy Cae a eet ee ead atari ete ty Re ee ete ets computing, To achieve that goal the Pi Foundation includes different Pet gen arc ean) Pe ei ere eee ena elon peat There are other advantages, such as being able to combine Python code with Scratch (an Object-Oriented programming language developed by MIT, for children to understand how coding works) and being able to code the GPIO connection on the Pito Further control anyattached robotics or electronics projects, Raspbian also includes Ree eg ee ere Ceti ee ee ey projects tothe Pi), which can be accessed via Python code. Consequently the Raspberry Piisan excellent coding base, as well Peeps homed tric sa een rr eee ee ee rd fietinaece ees ee eae Pi, you're also able to use itn Windows, other versions of Linux and 1macOS. Ifthe code requires a specic operating system, then, don't Pert sas Everything you need to learn to code with Python is included with the Ost vgs eae Introduced on 24th June 2019, the Raspberry i 4 Model Bi ‘significant leap in terms of Pi performance and hardware specifications. twas also one ofthe quickest models aside from the tiginali,to sellout. \with anew 1.5GHz, 64-bit, quad-core ARM Cortex-AT2 processor, and ‘a choice oF 1GB, 2GB, or 4G8 memory versions the Pi is one-step closer to becoming a true desktop computer. In addtion, the Pi4 launched with the starting decision to include dual-monitor support, inthe Form ofa pair of two microHDMI ports. Youlaso Find a pair CNN Inaddition to releasing the Pi4, the Raspberry Pi team also compiled ‘anew version ofthe Raspbian operating s em, codenamed Buster. {nconjunction with the new hardware the Pi4 boasts, Buster does ‘offer few updates. Although on the whole t's very similar in ‘appearance and operation tothe previous version of Raspbian. The ‘updates are mainly in-tne with the 4K’ display and playback, giving the id.anew set of oraphical drivers and performance enhancements, ot, what you seein this bot 4 and Raspbian Buster! ok will work with the Raspberry Pi P eeraer e Pi (5 ‘oF USB 3.0 ports, Bluetooth 50, and a GPU that’s capable of handing 4K esolutions and OpenGLES 3.0 graphics. Inshort, the PI isthe most powerful ofthe current Raspberry P ‘models, However, the different memory versions have an increased cost. The 1GB version costs €34, 2GBis £44, and the 4GB version will, setyou back £54, Remember to also factorin one or two micro-HDMI ‘ables with your order. Cece mane Using Virtual Machines Pt en ES Mona M Ne ke eee UNE Net oe MAM ot ea tc Cet ae eset cen! isolated environment. In short, it’s an ideal way to code. ‘Sounds good, but what exactly is a Virtual Machine (VM) and how does it work? ‘The official definition ofa virtual machine is'an efficent, icolated ‘duplicate of a real computer machine’. This basically means that a virtual machine isan 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 Hypervsor. ‘The Hypervisor itself isan app that will allow you to installa ‘separate operating system, creating a virtual computer system within itself, complete with access to the Internet, your home networkand soon, ‘The Hypervisor will 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, willbe set aside For use inthe virtual ‘machine and therefore wor't be avaliable to the physical computer Until the hypervisor has been closed down, This resource overhead canbe crippling For the physical machine if you don't already have enough memory, or hard drive space available, or your computer has particularly slow processor. while i's Coding for Linux ant entirely possible to run ‘Soot ar (he F vireual machines on as little 85 2GB of memory, i's not . advisable. Ideally, you wil need a minimum of 8G8. ‘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 ‘ean have a dual-core CPU, butthat can cause a bottleneck on your physical computer). ‘will (Our Linux titles contain steps on how to installa hypervisor and 0s. ‘The imitto how mary 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 stil leaving enough For your physical computer to operate on, You're able to install Linux, and code inside a virtual machine ona Windows 10 host. VIRTUAL OS From within a hypervisor you're able to una numberof diferent ‘operating systems. The type of OS depends greatly on the hypervisor you're running, as some are better at emulating a particular system over others. For example, VirtualBox, a free and easy to use hypervisor from Oracle, is great at running Windows and Linux virtual machines, butsr’t so good at Android or macOs, QEMU is good for emulating ARM processors, therefore ideal For ‘Android and such, butt can be difficult 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 job. Within a hypervisor, you're able to set up and install any ofthe newer distributions of Linux, orifyou Feel the need, you're also able to install some ofthe more antiquated versions. You can instal early versions of Windows, even as far 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 network). With this in mind then, you're able to have an installation oF Linux Mint, orthe latest version of Ubuntu, running in an app on your Windows 10 PC. Thisis the beauty of using a virtual machine Conversely if your physical computer has Linux as its installed ‘operating system, then with a hypervisor you're able to create 3 Windows 10 virtual machine ~ although you will need to havea licence code available to register and activate Windows 10, Using virtual machines removes the need to dual-boot. Oualboating ishaving two, of more, physical operating systems installed on the same, or multiple, hard drives on asingle computer. As the ‘computer powers up, you're given the option to choose which OS. you want to boot into. While this sounds ike a more ideal scenario iRisn't always as stright forward as it sounds, as all the operating systems that are booted into will have Full access to the computer's entice system resources. The problems with dual-booting come when one of the 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 starts up, meaning the intial 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, oul ned to access the Master Boot Record and alter the configuration to re-allow booting into the other systems. There's ‘also the danger of possibly overwriting the first installed OS, or ‘overwriting data and more often than not, most operating systems don't play well when running side-byside. indeed, while good, dual- booting has more than its Fai 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 on a single computer. Even old operating systems can be run inside virtual machine. Virtual machines can be as simple, or as complex as your needs require. ADVANTAGES FOR CODERS For the coder, having a 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 a Linux distro in a hypervisor, you're able to quickly and effortlessly power up the virtual machine and test your cade ina completely different operating system. From this, you're able to iron out any bugs, tweak the code soit works better ona different platform and ‘expand the reach of your code to non-Windows users. ‘The advantage of being able to configure a development environment, in specific ways for specific projects is quite invaluable, Using a vitual machine setup greatly reduces the uncertainties that are inherentto having multiple versions of programming languages, libraries IDEs and modules installed, to ‘support the many different projects you may become involved in as ‘a coder. Elements of code that ‘talk’ directly to specifics of an| ‘operating system can easily be overcome, without the need to clutter up your main, host system with cross-platform libraries, ‘which in tun may have an effect on other libraries within the IDE. ‘Another element to consider is stability. IF you're writing code that could potentially cause some instability tothe core OS Hello, world ») Getting to Know Python Python is the greatest computer programming language ever created. It enables you to fully harness the power of a computer, in a language that’s clean and easy IRON Ea Tel Tete 1aTe WHAT IS PROGRAMMING? It helps to understand what a programming language is before you try to learn one, and Python is no different. Let’s take 3 look at how Python came about and how it relates to other languages. ‘A programming language {sa list of instructions that <2 computer follows. These instructions can be a simple 2s displaying yourname cr playing a music file, or ascomplexas building a whole virtual world. Python is programming language conceived in the late 1980s by Guido van Rossum ‘at Centrum wiskunde & Informatica (CW in the Netherlands as asuccessor to the ABC language, Guido van Rossum, the father of Python. PROGRAMMING RECIPES 933i. Programs are like recipes for computers. A recipe to bake a cake could go like this: 5 hdd S00 williaitres of mlik Put 100 grams of selF raising flourin a bow, ‘Add 100 grams of butter to the bow. ‘Add 100 mililtres oF milk Bake for halFan hour, CODE Just ke a recipe, a program consists oF instructions that you Follow inorder. A program that describes a cake might run lke this: T fica = 200 whe ty Pewter = 50 ce ‘bow! append [flour, butter, mill ) sake..cook (bowl) PROGRAM COMMANDS. ‘You might not understand some of the Python commands, like bowlappend and cake.cook(bowl) The firsts alist, the second an object; well look at both in this book. The main thing to know is that it’s easy to read commands in Python. Once you learn what the commands do, i's easy to figure outhow a program works. HIGH-LEVEL LANGUAGES Computer languages that are easy to read are known as “high-level” “hiss because they Fy high above the hardware (also referred to as the metal’). Languages that “fly close to the meta," ke Assembly, ‘are known as “lowrlevel’. Low-level languages commands read abit likethis:msg @b ,oxa len equ $ - meg PYTHON 3 VS PYTHON 2 ee enre Ca A nee WORLD OF PYTHON TE eee oe Cae Toa ae oy Gere errs Pe rseg aes Posse Crd PYTHON 2.X Taunehed in 2000 and has since then’ Bis PIG Ge ( Getting to Know Python ell ZEN OF PYTHON Python lets you access al the power of a computer ina language that humans can understand. Behind all this is an ethos called "The Zen of Python." This isa collection of 20 software principles that influences the design of the language. Principlesinclude "Beautiful isbetter than ualy’ and “Simple isbetter than complex." Type import thie into Python and it wll display all the principles. Dae eau uti eu eee Seu eur Cpe od eer ae Ce ry aaah eee ae Pee eet. seas PYTHON provide smo Soeied Se es an oe Cie greener Python 3's growing po Ps ee oer ie ene ZZ dy Hello, World How to Set Up Python in Windows Windows users can easily install the latest version of Python via the main Python Downloads page. Whilst most seasoned Python developers may shun Windows as the platform of choice For building their code, it’s still an ideal starting point for beginners. INSTALLING PYTHON 3.X Microsoft Windows doesn’t come with Python preinstalled as standard, soit will be necessary to install it yourself manually. Thankfully, it's an easy process to Follow. Staréby opening your web browser to www.python. BALD orc ovrioady Look forthe button detalinathe Download lnk For Python 3.x Pythons regularly updated, changing the ast ig for each bugfix and update Therefore, dont worry if youssee Python 3.8, or more, as ong asit's Python 3, the code inthis book will work fine. Click the Download button for version 3.xand save the file to your Downloads Folder. When the files downloaded, double-click the executable end the Python installation wizard wil launch. From here, you have two choices Install Now and Customise Installation. We recommend opting for the Customise installation link eon =a Install Python 3.8.0 (32-bit) techy i enh ng Se Choosing the Customise option allows you to specify certain parameters, and whilst you may stay with the defaults, t's good habit to adoptas, sometimes (not with Python, thankfully, installers can include unwanted additional Features. On the frst screen available, ensure all boxes are tcked and click the Next button, Optional Features creat J) foo ronnie Gyno Berson i mn Cnn by munch nn put BEEP Te next page of options include some interesting additions to Python Ensure the Associate file wth Python, Create Shortcuts, Add Python to Environment Variables, recompile Standard Library and instal For All Users options are ticked. These make using Python later much easier. ck nstall when youre ready to continue, froma a ‘Advanced Options Bitrate ‘ms nena rtp Dada penne ri imenpisintes ny (seed eg ater e205 re) out | Coeoen seni yoen How to Set Up Python in Windows [> clck es and Python wilbeginto install Once theInstalations_programming journey. Dott worry your version sewer, 3 ong Complete, the nal Python wzard page willow youto view the asi'sPython 3xour code works nde your Python 3 interface. lates release notes and follow some onine tutorials o Setup was successful Scour, seme” itmaea tr wee put " windows aa TERED 2Fore you close the install wizard window BETTER | younow click on the Windows Start button again, however, it's best to click on the link next to the and this time type: CMD, you'll be presented with shield detailed Disable Path Length Limit. This wil allow Python _the Command Prompt link. Clickit to get to the Windows command to.bypass the Windows 260 character imitation, enabling you to__ line environment. To enter Python within the command line, you execute Python programs stored in deep folders arrangements. __needto type: python and press Enter. Click Yes again, to authenticate the process, then you can Close the installation window. © Disable pathlength limit Cose BRE iis 10 userscan now find theinstaled Python The commandline version af Python werk in The first ink, Python 3.x (32-bit) will aunch the command tine Step 8 note the three left Facing arrows (>>). Whistt’s a perfectly version of Python when clicked (more on that ina moment). To open fine environment, i's not tao user friendly, so leave the command the IDLE, type IDLE into Windows start. line for now. Enter: ext () to leave and close the Command Prompt window. ee ee] Hello, World How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it’s often difficult to nail down just one-way of doing something. Different distributions go about installing software in different ways, so For this particular tutorial we will stick to Linux Mint, PID Fist younced toascertain which version of Python REEMA Once the update and upgrade completes, enter: 's currently installed in your Linux system. To begin python --version again to see if Python 3x ‘with, drop into a Terminal session from your dstro’s menu, or hiethe updated, or even installed. As ong as you have Python 3.x, you're CUrtsaltsT keys. running the most recent major version, the numbers after the 3. indicate patches plus Further updates, Often they/re unnecessary, davidedavid-mi but they can contain ital new elements, Fle Eat view Search Terminal Help PETTSP RD Next enter: python --version into the Terminal screen, You should have the output relating to version 2.x of Python in the display. Most Linux distro come with both Python 2 and 3 by default as there's plenty of code out there stillavalable for Python 2, Now enter: python3 --version. davidedavid-Mi Fle Edt View Search Terminal Help STs nore However, if youwant the latest, cutting edge ka A cord ue version, you'll need to build Python from source. Daren ies ge Start by entering these commands into the Terminal LJ sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev ~ + SS Seay Saal tay la day TERCU inourcasewe hve both Python 2and installed. Libysbm-dey Libce-dev 1ibbe2-dev SNPS) ‘As long as Python 3.x.x is installed, then the code in ‘our tutorials wil work.’ always worth checking to see ifthe distro hasbeen updated with the latest versions, enter: audo apt-get. update && sudo apt-get upgrade to update the system, vided ating ~ open up your Linux web browser and goto the SUED 2 sron dowrioad poe: hips /wnpython oral downloads, Click onthe Downloads, followed by the button under the Python Source window. This opens a downlosd calogue bo, choose locaton, then stare the download process, inthe Terminal go athe Downloads Folder Sue? i by entering: cd Downloads /. Then unzip the content ofthe downloaded Python sour code with: tar rE ython-3 ear (eplacethe Y'suith the version nimbers Souive downloaded), Now eter the new unippes older with: yehon-3 9.97 FEED Within the Python Folder, enter: Jeonfiguee audo make altinetall ‘This could take a while, depending on the speed of your computer. Once finished, enter: python’ .7. =-versionto check the latest installed version. You now have Python 3,7 installed, alongside older Python 3.xx and Python 2. How to Set Up Python in Linux sudo apt-get install idle For the GUIIDLE, youll need to enterthe following ‘command into the Terminal The IDLE can then be started with the command: idle, Note, that IDLE runs different version to the one you installed from source. ‘dave avid Min: -/Downlone/ython 372 Youll ato need PP (Ppt Packages hich's UEP O a tool to help you install more modules and extras. Enter: sudo apt-get install python3-pip (Once PIP is installed, check for the latest update with: pip3 install --upgrade pip When complete, close the Terminal and Python 3. willbe available via the Programming section in your distro's menu. evisadvi tin -/Domianurthan 372 Installation of Python on macOS can be done in much the same way as the Windows installation, Simply goto the Python ‘webpage, hover your mouse pointer over the Downloads link and select Mac 05 X from the options. You will then be guided to the Python releases for Mac versions, along with the necessary installers For macOS 64-bit for OS X 10.9 and later. => Hello, world ») Starting Python for the First Time The Raspberry Pi offers one of the best all-round solutions on which to learn and code, in particular, Python. Raspbian, the Pi's recommended OS, come pre-installed with the latest stable version of Python 3, which makes it a superb coding platform. STARTING PYTHON Everything you need to begin programming with Python is available from the Raspberry Pi desktop. However, if you want, drop into the Terminal and update the system with: sudo apt-get update. BPR i scrnasscecninil sicnie (BEB ca ounce ne ear Find the Python 3 IDLE Shel from within the Windows Start button relevant output. menu and via Finder goumepau ESTEE The Shelliswhere youcanentercode andseethe [ESSAI The Python Shell acts very much lke a calculator, responses and output of code you've programmed since code is basically a series of mathematical, into Python. Tis isa kind oF sandbox, where you're able to try out interactions with the system. Integers, which are the infinite ‘some simple code and processes. sequence of whole numbers can easly be added, subtracted, rmultipied and so on, 34 Siar) While that's very interesting, i's not particularly ‘exciting, Instead, try this: print ("Hello everyone!*) Just enteritinto the IDLE as you've done in the previous steps, ‘The Python IDLEs a configurable environment. IF you dont lke the way the colours ae represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don’t recommend that, as you won't be seeing the same as our screenshots, hiss alittle more lke it, since you've just produced your frst bit of code. The Print command is fairly self-explanatory, itprints things. Python 3 requires the brackets as ‘ell as quote marks in order to output content to the screen, in this ‘ase the ‘Hello everyone bit. >>> print("Hello everyone!) Hello everyone! >>] You may have noticed the colour coding within Saag the Python IDLE, The colours represent different ‘elements of Python code, They are: Bleck Data and Variables Green-Strings Purple—Functions Orange Commands ‘Blue — User Functions Dark Red - Comments Light Red Error Messages IDLE Colour Coding [-eatour [ve ror examptes | Ce ee Purple | Funatons | eat) _peineo Barked | Conor trea [Ener messsoes | _syntaesevor ESE est like most programs available, regardless of the ‘operating system, there are numerous shortcut keys avaliable. We don't have room for them all here but within the ‘Options » Configure IDLE and under the Keys tab, you can see a list of the current bindings. etal Fimskecme emer ae ee BETSEB) the Python DLE isa powerinterface andone that’s actually been written in Python using one of the available GU! toolkits. If you want to know the many ins and ‘outs ofthe Shel, we recommend you take 3 few moments to view worw.docs.python.org/3/library/idle.html, which detalis many oF the IDLE's Features, ( Starting Python for the First Time eC ED istonoia ) Your First Code fool ARON A ¥-L Rc INL ee UR Volt MALTY reel eors (RULE MELA a0) Sn w atau Totter me td Cate uharenl Ceea Pennine eu eUM etn Mien temaiatscisces 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. I you've closed Python 3 IDLE, reopen it in You can see that instead ofthe number 4, the whichever operating system version you prefer. In ‘output isthe 242 you asked to be printed to the the Shell enter the Familiar Following: screen. The quotation marks are defining what's being outputted to the IDLE Shell ta print the total of2+2 you need to remove ust as predicted, the word Hello appearsin the You can continue as such, printing 2+2, 46442343 Shell as blue text, indicating output From a string. ‘and soon tothe Shell. An easier way isto use a les arly straightforward and doesnt require too much explanation. variable whichis something we will overin more depth ater. For Nowy now, enter: Your First Code (9 BATES What vou have done heres assign the letters Eee Now lets adda surname: ‘and b two values: 2 and 2, These are now variables, aes ‘which can be called upon by Python to output. add, subtract, divide ‘and soon for as long astheir numbers stay the same. Try this: Levan ‘You now have two variables containing a first name and a surname nam and you can print them independent nd you can print them independentiy The output ofthe last step displays the current IF we were to apply the same routine as before, values of both a and b individually, as you've asked using the + symbol, the name wouldn't appear them to be printed separately. Ifyou want to add them up, you can correctlyin the outputin the Shell. Ty it Use the following: ‘You need a space between the two, defining them as two separate ‘This code simply takes the values of a and b, adds them together _values and not something you mathematically pay around with, New File. This will open a new window ‘with Untitled as its name. Thiss the Python IOLE Editor and within it you can enter the cade needed to create your future programs, The IDLE Editor is, for allintents and purposes, @ simple text editor with Python Features, colour Siar ‘coding and so on; much inthe same vein as Sublime. You enter ‘code 2s you would within the Shel, so taking an example From the previous tutorial, enter: Print ("Hello everyone!*) bear ended uhesouirainpor-o ness Pomcehenon ‘lick on the OK button in the Save box and select a destination where youl save all your Python code. ‘The destination can be a deviated folder called Python or you can ust dump it wherever you like, Remember to keep a tidy drive though, tohelp you outiin the Future BETTER {tera name for your code, ‘print helo For example, and clk onthe Save button. Once the Python cade is saved it's executed and the output will be detailed in the IDLE Shell n this case, the words ‘Hello everyone!” This is how the vast majority of your Python code will be conducted. Enter itinto the Editor, hit FS, ‘ave the code and look at the output in the Shell. Sometimes things will differ, depending on whether you've requested a separate ‘window, But essentially that's the process. I's the process we will Use throughout this book, unless otherwise stated. \F you open the file location ofthe saved Python code, you can see that itendsin a.py extension, ‘Thisis the default Python file name. Any code you create willbe ‘whatever.py and any code downloaded from the many Internet Python resource sites wil be py. Just ensure that the code is written for Python 3 Saving and Executing Your Code e Let's extend the code and enter afew examples at) i fro mm the previous tutorial: asa be2 nane="David* surname="ayward” SS print (a+b), IFyou press FS now you'llbe asked to save the file, again, ass been modified from before. BEER you click the Ok button, the file will be ‘overwritten with the new code entries, and executed, withthe output inthe Shell It’s not a problem with just these Few lines but if you were to edit a larger ile, overwriting can become an issue. Instead, use File > Save As From within the Editor to-create a backup. EEZD rt BEgD = anew file. Close the Editor, and open 2 new instance (Fle > New File From the Shel). Enter the following and save itas hello py: eeteoolt* print (a, b,c) ‘Youwill use this code in the next tutorial. Talay. hanalpiDosmanaiinonGcrlopy O42) Hello, World Executing Code from the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made in the GUI at the command line level. cuting code vi Sua?) Python. For Python 3 y aysiswith Python 2 whist the other uses the yt command pythons and pres Enter This wl ptyou it the and soon Festthoughdopintothe command tne or Teinalon command ine version ofthe Sel, withthe fair three ight Your operating Sater fac ar Ea Fromhere! looked at ously, such as Raspberry Pi: Windows users wil = need to click the Start button and ao = print (a) You can see that it works exactly the same. Go > Utities > Terminal ee Executing Code from the Command Line Now eter: ext oleae the command ne Python The result of uming Python 3 ade Fom he SIPS session and return you back to t SUBS if Python 2 command tne is quite obvious, Whilst it prompt. Enter the Folder where you saved th doesn't error out in any way, due to the differences between the previous tutorial andlistthe available files within; hopefully you way Pythan 3 handles the Print command over Python 2, the result should see the hellopy file. isn’t as we expected, Using Sublime for the moment, open the hello.py fie FEED Fromwithin the same folder as the code you're PEPER Since Sublime Text isnt available forthe Raspberry going to run, enter the Follawing into the Pi, you're going to temporarily leave the Pifor the command tine: ‘moment and use Sublime as an example that you don't necessarily need to use the Python IDLE. With the hello.py file open, alteritto include the Following: python? hello.py Thiswill execute the code we created, which to remind yous es nane=input (“What is your nant as"Python” print (*Hello,”, name! berier e="ecol" 2 print(a, b, ¢) FETTER Naturally, since thisis Python 3 code, using the PEPER B) Seve the hellopy ile and drop backto the syntax and layout that's unique to Python 3, It only command line. Now execute the newly saved ‘works when you use the python3 command. IF you tke, trythesame code with: ‘with Python 2 by entering python hello.py SSE The result willbe the original Python is cool statement, together with the added input command asking you For your name, and clsplaying it in the command window. Eta Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the Reese ae ees h ee nice erect crm ll can work within the IDLE Shell or in the Editor, whichever you like. IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as languages, maths is the driving force behind the code. ‘most, ifnot all, programming PETER per up the Gulversion of Python 3, as mentioned REE You can use all the usual mathematical operations: you can use either the Shell or the Editor. For the New File) and create a simple variable and print command: Save the file and execute the code. ‘rer py-hoplOccare Pon Comseanrerspy(942) = 8 0 at Fame Bn Sto es FR cringe code wile theline:The lve oF A SEP is, 10 into the IDLE Shell window, which is what we expected. Now, addsome ofthe peso comments you'd nomaly seeincoe Resave the code and execute it: You can see that the ‘output inthe IDLE Shell sstil the same as before, despite the extra lines being added, Simply put, the hash symbol (#) denotesa line oftext the programmer can insert to inform them, and others, of what's going on without the user being aware. E Ta ernment ramegscie eto ae on Let's assume that the variable that we've created isthe number of tivesin a game. Everytime the player des, the value is decreased by 1. The programmer could Insert a routine along the lines of: oy Whilst we know that the variable is tives, and that the player hasjust lost one, a casual viewer or ‘someone checking the code may not know. Imagine for a moment that the code is twenty thousand lines long, instead of just our seven. You can see how handy comments ae. Siar saat hts Sow # Set the start value of A to 10 as10 4 Print the current value of A print ("The value of A is,, a) # Player lost a life! aca-1 # Inform player, and display current value of A (ives) Print ("You've just lost a life!") Print ("You now have", a, “Lives left!*) Essentially, the new code together with comments could look ike: You can use comments in different ways. For ‘example, Block Comments are a large section of text that details what's going on inthe code, suchas telling the code reader what variables you're planning on using: 4 This is the best gane ever, and has been developed by a crack squad of Python experts who haven't slept or washed in weeks. Despite, being very smelly, the code at least W works really well. Using Comments e FETED ine comments are comments that follow a section (of code. Take our examples from above, instead of inserting the code on a separate line, we could use: asl0 # Set the start value of A to 10 print ("The value of A is,", a) # Print the current value of A ava-i # Player lost a life! print ("You've just lost a life!™) print ("You now have", a, “lives left!*) # Inform player, and display current value of A (lives) EERE The comment, the hash symbol, can also be used to ‘comment out sections of code you don't want to be executed in your pragram. For instance, if you wanted to remove the first print statement, you would use: # print ("the value of A is,", ab 7 Set the start valuw of A to 10 210, 2 Prine the current value of A Je prantc*The value of A is,", af = Player lost a 13 Inform player. and display current value of A (lives) prancc“Tou've just lost a, Life!” Print(-You non have", 8, “Lives left!) PEPER) You also use three single quotes to comment ‘outa Block Comment or multitine section of comments. Place them before and after the areas you want to ‘comment for them to work: ‘This is the best game ever, and has been developed by a crack squad of Python experts who haven’t slept or washed in weeks. Despite being very smelly, the code at least works really well. ee egy ee el SL C) Hello, world Working with Variables RET LTa oN clu) (Ne AVIA] Mole a a earonaeo)s Rela =l\ go. oO Merete nei Rear ene aren berces tubs ute SINT Aco RVI 10) VARIOUS VARIABLES ‘You'll be working with the Python 3 IDLE Shell in this tutorial. you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. EETESERD '250me programminglanguagesyou'e required REM You've seen previously that variables can be touse a dollar sign to denote a string, which isa concatenated using the plus symbol between the variable made up of multiple characters, such as a name of a person, variable names. n our example we can use: print (name +": In Python ths isn't necessary. For example, inthe Shell enter: + eXtLe). The middle part between the quotations allows us to name="David Hayward” (or use your own name, unless you'e adda colon and a space, as variables are connected without spaces, also called David Hayward). so we need to add ther manually ae Eat Sob De te ro eee eT “le Git Sel UE Seen rns ee ee wm me notin, ED iaicroncvenpecrorsienaaty EES vcs oue2 issuing the type () command, placing the name of Suits combine variables Uaiafebi baletneteion narvannstentibe, salinesthervesia tr Dan oJ now singvessoe Ba ca trample to comtine othrame from Vikings”. and title variables into anew vonebewee character=name +": "+ title cerca eeranrer ie reverie s print (character) Nurbers ae tore as fret vores age=44, ‘Type (age) Which, as we know, are integers However, you can't combine both strings and integer type variablesin the same command, as you Siar ‘would a set of similar variables. You need to either turn one into the ‘other or vice versa, When you do try to combine bath, you get an ‘error message: This @ process known as TypeCasting. The Python codeis: ‘or you can use: print (character, “is*, age, "years old.") Notice again that in the last example, you don't need the spaces between the words in quotes as the commas treat each argument to print separately >>> print (mane + age) Traceback (most recent call Last): Pile S rine’ (name + age) Typetrror: Can't convert “int* object to str inplicitly Sprint (character +" 3s"! + str(age) +" years old." David Hayward: Descended fron Viking years ole. Soo prune (character, "is", age, “yt ‘Another example of TypeCasting is when you ask for input From the user, such as a name. for example, center: ages input (*How old are you? *) {All data stored from the Input command is stored as string variable. "roe (hon sid are You? SS ow SES ae you! a claattsee"> iT Working with Variables ‘This presents abit ofa problem when you want to Sia) ‘work with anumber that's been inputted by the User, as age + 10 won't work due to being a string variable and an integer. Instead, you need to enter: int(age) + 10 ‘This wil TypeCast the age string into an integer that can be ‘worked with, ei eer ht rb STEP 9 ‘The use of TypeCasting is also important when dealing with Floating point arithmetic; eemember: ‘numbers that have a decimal point in them. For example, enter: shirt-19.99 Now enter type (ahixrt) and youtl see that Python has allocated the number 3s a float, because the value contains 8 decimal point. Ys spy age” Merete” or *Lcene()* for more internation. \When combining integers and Floats Python Say usualy converts the integer to afloat, but should the reverse ever be appliedit's worth remembering that Python doesn't return the exact value. When corwerting a loatto an integer, Python will always round down to the nearest integer, called truncating; in our case instead of 19.99 it becomes 19. | Ble Eat Shel eboa Gptens window tay Pere an eer Tea as eae eee : e Va AED CU Lae eee UC Ce chs [OR oO reese eee oe oe Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction Oy rey 4-43 Pie Ma a meolouls OTT) UNEP da lelit tem (ola alo ma 1A We have everything for all of your needs. Just open https://avxlive.icu Hello, World ED) tatoos) User Input NREL o dey el nee eee ane eels Mico eC oy eMC aeteese ea Marae Cl caiimeccny eM a ceca 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. Fit’s not already, open the Python 3 IDLE Shell, Sica and start a New Filein the Editor Let's begin with something realy simple, enter: PB seve and execute the code, and as you already no SAD ci supected, inthe LE hel the progr il ask for your first name, storing it as the variable firstname, followed by your surname; also stored inits own variable (surname). Now that we have the user’s name stored ina couple of variables we can call therm up whenever we want rine oncont, Frater" hope owe me tay“) Run the cade and you can see a slight issue, the SUaPS) full stop after the surname follows a blank space. Toeliinate that we canada plus sign instead ofthe comma in thecade Seerane toes Oe OT spite watt ‘You don't always have to include quoted text withi the input command, For example, you can ask the Siar ‘user their name, and have the input inthe line below: Print (*Hello. What's your name?") nane=input () userinput.py - home/pi/Documents/Python Code/us) ‘Ble Edt Format Bun Options windows Help Int(*Hello, What's your nane?=) oi The code from the previous step i often regarded {as being a litle neater than having alengthy ‘amount of text the input command, butts nota rule that's set in ‘stone, 0 do 2s you lke in these situations. Expanding on the code, try this It's good start toa text adventure game, pechaps? [Now you can expand on it and use the raw input From the user to flesh out the game alittle: ‘seiepupy-amelp/Oocurens/Pyon Coseusemptpy(s42) = © ™ ‘Gat Fem in pt from te User Input ‘What you've created here is a condition, which we will cover soon. n short, were using the input from the user and measuring it against a condition. So, iF the user enters, David as their name, the guard will allow them to pass unhindered Els, iFthey enter a name other than David, the guard challenges, them toa fight. Bia) FETED ust2s you learned previously, any input froma user is automatically a string, so you need to apply a ‘TypeCastin order to turn itinto something else. This creates some interesting additions to the input command. For example: PEPPER Tofinalise the rate and distance code, we can add: Save and execute the code and enter some numbers. Using the Float(input element, we've told Python that anything entered isa Hello, World Creating Functions NoMa] AoA CME oe Leh ap OLY Mel RUT) EL OR UMD ULM ea Moo eno e=Lad( eM ee Cmte eet eee inten ts oTaen enables you to define your own functions. FUNKY FUNCTIONS ‘Afunction is a command that you enter into Python to do something. It's alittle piece of self-contained code that takes data, ‘works on it and then returns the result. I's not ust data thata function works on, They can do all manner of useful things in Python, such as sort data, change items From one Format to another and check the length or type of items. Basically, a Function is ashore word that's Followed by brackets. For example, len), ist() or type(). ‘A function takes data, usually a variable, warks on AED erencing on what he functions progremmed to do and,eturns the end value. The data being worked on goes inside the brackets, so if you wanted to know how many letters {are in the word antidisestablishmentarianism, then you'd enter: Len (“ant idisestablishnentarianien") and the number 28 ‘would return, Ey PET SSE RD ou con pass variables through Functions in much, the same manner, Let's assume you want the numberof lettersin a person's surname, you could use the Following code (enter the text editor For this example): nanesinput ("Enter your surname: *) count=len (name), print ("Your surname has", count, “letters in ice) Press F5 and save the code to executelt. BEEP cron has tens offunctionsbultintot, far too many to getintoin the imited space avaiable here. However, o view thelist of builtin functions avaliable to Python 3, navigate to wor docs python ora/braryifunctions nem. These are the predefined functions, but since users have created many more, they're not the only ones available. FETED cidtional functions can be added to Python through modules. Python has a vast range of ‘modules available that can cover numerous programming duties. “They add functions and can be imported as and when required. For ‘example, to use advanced mathematics Functions enter: import math Once entered, you have access to all the Math module Functions. es ( Creating Functions BETTS) 0 vse a function from a module enter the name of the module Followed by afull stop, then the name of the Function. For instance, using the Math module since you've just imported it into Python, you can utlse the square root function, Todo so, enter: math. sqrt (26) You can see that the code i presented as module function(data}. Freee 2S =s FORGING FUNCTIONS ie uueE a ore aia ciea ree een eee Co a inte epee Me Meee! STEP 1 Pee LIBEL OSA Ime ne ier ee eee Riad STEP 2 Peter fact Hello (name) Reto ("avid") Ea oe Bee Wo ue ea eee ne ren ee aes the Following: rom Helio tnzore Fall STEP 4 eet nuns ay hello to David This is how modules and functions work esi he eee (ees wi Cu ors Cnet Eta Conditions and Loops eo EM ee SEE CET Net eee eT CK Ie aT Common etu cuneate acter unite rene is they could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS ns simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking if something is TRUE, then doing something else iF itisn’t. PETER DD Lets create a new Python program that will ask PETSSE DD Now you can use an if statement to check fthe the user to input aword, then checkitto see iF it's ‘word length variable is equal to four and print a ‘a fourletter word or not. Start with File » New File, and begin with friendly conformation if it applies tothe rule: the input variable: ‘The double equal sign something ese. FR Now wecan create a new arable, then use the en Thecolonat the endofFtels Python thats SUE? function and pass the word variable through it to SUMS) ‘statement is true do everything after the colon get the total numberof leters the userhas jst entered: that’s indented. Next, move the cursor back to the beginning of the Editor: fri mgt tet ey Fa Conditions and Loops eC STIS P1es5F5 and save the code to execute it. Enter FETTER Now expand the code to include another conditions. ‘a fourletter word inthe Shell to begin with, you Eventually, it could become quite complex. We've should have the returned message that it'sthe word isfourletters. added a condition for three-letter words: Now press FS again and rerun the program but this time enter a Five-letter word, The Shell wil display that it’s not a four-letter word a four-letter word: *) if word length print (word, "is a fou one." elif vord_length == 3 print (word, “is a three-letter word. Try again.) else print (word, “is not a four-letter word.*) letter word. Well LOOPS. ee es SM se aie Csr ate amen east re aiE canta STEP 1 GMa Baerga tag i COU ested code print word) PETER The sitterence between if andwhiteisuien while MBI the For loop can also be used inthe countdown, OO ng te aie Cee ries Bear Iga tues Sse g een Ces reat Pee ee) Hello, World Python Modules MASTERING MODULES ‘Think of modules as an extension that’s imported into your Python code to enhance and extend its capabilities. There are countless modules available and as we've seen, you can even make your own ED Scistgoct te butin taco wiin ncn BEBREB terest aerate Ouse te tomake more sophisticated programs. As you are aware, modules Python. To install a module we can use PIP (Pip Installs Packages) are Python scripts that are imported, uch as import math, Close down the IDLE Shell and drop into a command prompt or Terminal session. Atan elevated admin command prompt, enter: pip install pygane Some modules, especialy onthe Respbery Pi instalation equresan elevated status SuaP2 are included by default, the Math module being a SUMS) iue it installing components at different locations. prime example. Sal, other modules arentalays valble.Agood Windows wserscan seach for CMD a the Sat buton and ight trample onnorPipltfors sthe Pygame module whichcontins lek theres then cle Run s Adminstrator Linux and Mac users many Fanon tohelp reste gare, Tr mpor pygame Canuse the Sudo command; wthsude pip instal pactge, Close the command prompt or Terminal and relaunch the IDLE Shell, When you now enter: Anportpygame, the module willbe imported into the code ‘without any problems. Youll find that mest code downloaded or ‘copied From the internet will contain a module, mainstream of Unique, these are usually the source of errorsin execution due to them being missing Siar Be The modules contain the extra code needed to achieve a certain result within your awn cade, as ‘we've previously experimented with. For example: see anon Brings in the code from the Random Number Generator module, like ‘You can then use this module to create somet for i in range( print (random.randint (1, 25)) —= ‘This code, when saved and executed, will display ten Sis random numbers from 1 to 25. You can play around ‘with the code to display more or less, and from a great or lesser range. For example: = om for 4 in range(25): print (random.randint (1, 100)), Python Modules ‘Multiple modules can be imported within your code, Sia) To.extend our example, use: import: random import math for 1 in range(S): print (random.randint (1, 25)) print (math.pi) ae ‘The result sa string of random numbers followed by the value of Pias pulled from the Math module Using the print(math.p}) function. You can also pullin certain Functions from a module by using the from and import commands, such as: from random import xandint for 4 in range(S): print (randint (1, 25)) STEP 9 “This helps create amore streamlined approach to Say programming, You can also use import module*, ‘which wil import everything defined within the named module, However, it's often regarded as a waste of resources but it works nonetheless. Finally, modules can be imported as aliases: import math as m print (m.pi) Ff course, adding comments helps to tell others what's going on, UW tetnte cites BaF - a x Hello, World Python Errors een iets Winey ela yored Cera cont eer e- UN arom Vell Reels MT) ek ceed tock oeoenatel iui a nhs BR ean ee Cl ele cnet eure coloured areca lcs DEBUGGING Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important thing is to keep looking, experimenting and testing. Eventually your code will be bug free. ‘Thankfully Python ishelpful when it comes to Code isnt as lud asthe written word, no matter Sse} Sica how good the programming language i. Python is certainly easier than most languages but even its prone to some annoying bugs. The most common are typos by the user and whilst ‘eagy to find in simple dozertine code, imagine having to debug rmult-thousand ine cade. ae ee pene Saree, SB se, Se 0 & a Se es “The most common of errorsis the typo, as we've ‘mentioned. The typos are often at the command level: mistyping the print command for example. However, they also ‘occur when you have numerous variables all of which have lengthy names. The best advice isto simply go through the code and check your spelling. Siar ue Eat 2 Gay Gens nds Ea displaying error messages. When you receive an red text from the IDLE Shell, it wil define the error itself along with the line number where the error has occurred. Whilst in the IDLE Editor thisisa litle daunting For lots of code; text editors, help by including line numbering, ‘Syntax errors are probably the second most ‘common errors you'll come across asa programmer. Siar Evenif the speling is correct, the actual command itself is wrong, InPython 3 this often occurs when Python 2 syntaxes are applied The most annoying of theses the print Function. n Python 3 we use print("words", whereas Python? uses print “words”. ‘B at Soh Db pons ards He ee Ea aa Be a TIT esky brackets are also a nuisance in programming Siar errors, especially when you have something like: print (balanced_check (input ())) Remember that For every (there must be an equal number of feterenee =) , 5 enaacter tn reference tes) ack append cheracter) C Python Errors eC ‘An excellent way to check your code step-by-step isto use Python Tutor's Visualise web page, found at www pythontutor.com/vsvalizehtmlmade=edit. Simply paste your code int the editor and click the Visualise Execution button torun the code lne-bytine. This helps to clear bugs and any misunderstandings There are thousands of online Python resources, UES code snippets and lengthy discussions across Forums cnhow beso achieve something Whit 99 percent oes good ‘code, don't always be lured into copying and pasting random code Imoyouredtor More often thn ot, ewovt work and the worst, parts thatyou hover earn anything jorczmlany upset epenyueser ne cra obese Indents area nasty part of Python programming that alot of beginners fall foul of Recall the Flop From the Conditions and Loops section, where the colon means. ‘everything indented folowing the statement is to be executed as long asit's true? Missing the indent, or having too much of indent, will come back with an error. © crete anne =) Planing makes for good code. Whistle old Sus) ‘school, it's a good habit to plan what your code wll before sting down type out Uitte variables ht wil beused and the modes too then write ova srp8 for any ver interaction or outputs Purely outof interest, the word debugging in computing terms comes from Admiral Grace Hopper, who back in the 40s was working on a monolithic Harvard "Markl electromechanical computer. According to legend Hopper Found a moth stuck ina relay, thus stopping the system from ‘working, Removal of the moth was hence called debugging. Hello, World Combining What You Know So Far MAY Mr-rlaal-teken Mure Ke lm ene Lee(a eed le See) EMule cekeel eRe] we've looked at so far, and apply it to writing a piece of code. This code can then be used and inserted into your own programs in Future; either part of it or as a whole. PLAYING WITH PI For this example we're going to create a program that will calculate the value of Pito a set number of decimal places, as described by the user. It combines much of what we've learnt, and a little more. ‘Start by opening Python and creating aNew File in the Editor. First we need to get hold of an equation that can accurately calculate Pi without rendering the computer's (CPU useless for several minutes. The recommended calculation Used in such circumstances isthe Chudnovsky Algorithm, you can find more information about it a en.wikipedia.ora/wiki/ CChudnovsky_algorithm, Bisa ‘You can utilise the Chudnovsky Algorithm to create iid your own Python script based on the calculation. Begin by importing some important modules and Functions within the modules: from decimal inport Decimal, getcontext Amport math ‘This uses the decimal and getcontext functions from the Decimal ‘module, both of which deal with large decimal place numbers and naturally the Math madule. BR TeSE DD Now you can insert the Pi calculation algorithm part ofthe code, Thisis aversion ofthe ‘Chudnovsky Algorithm: ef calctn): = Decimal (0) pi = Decimat (0) eno = Decimal (0) k=0 for k in range(n): © = (Decimal (-1)**%) + (math. factorial (Decimat (6)*e)) * (13591403 4545140134+k) eno = math. factorial (3*K) * (math. factorial (k) **Decinal (3)) * (640320%* (3¥%)) pi += Decimal (t} /Decinal (deno) pi = pi * Decimal (12)/ Decimal (640320¢*Decinal (1.5)) pi = tpi return str(pi) The previous step defines the rules that make eure) up the algorithm and creates the string that will ‘eventually display the value of Pi, according the Chudnovsky brothers algorithm You hve no doubt ready surmised att would be handy to actualy output the valve of itothe screen To rectify that you can add; print (eale(1)) PSPS You can save and execute the code at ths point if you lke. The output will print the value of Pi to 27 decimal places: 3.141592653589734207668453591. Whilst pretty impressive on its own, you want some user interaction, to askthe User as to how many places Pi should be calculated, Youcan set aninput ine before the calculation Sua Def command. It needs to be an integer, as it will other defaltoa sting. We can cal enumberofgts and use thegetcontert Function nunberofdigits = int (input ("please enter the nunber of decimal place to calculate Pi to: ")) getcontext () .prec = nunberofdigits (- Combining What You Know So Far eC PETE Youcan execute the code now andit asks the user ERNE Now weneed to import the Colorama module how many decimal places they want to calculate Pi (hich will output text in different colours) along to, outputting the result nthe IDLE Shell. Try twith 1000 places __with the Fore function (which dictates the foreground, ink, colour) butdontt go too high or else your computer willbe locked up in andthe Time module to starta virtual stopwatch to see how long calculating Pi ‘our calculations take: import time ESTEE 2 of programmingis (mu inport colorana being able to modify code, ea from colorana import Fore making it more presentable. Let's include ‘an element that times how long it takes our ‘computer to calculate the Pi decimal places ‘and present the information in a different ‘colour For this, drop into the command line ‘and import the Colorarma madule (RPI users already have it installed} pip install colorama Jen To nish our code, we need to inale the t= ecinal (0) SUP TD Colorama module and start the time Function at pi = Decimal (0) thepoinewhere the calculation starts anduwhen kfnshes Theend dena = Decina (0) result sacolouedink displayinghow long the processtock (nthe k= 0 “Terminal or command ine) EET © = (Decimal (-1) **K)* (math. factorial (Decimal (6) *k))* (13591409+545140134*k) eno = math. factorial (3*k) * (math factorial (k) **Decimal (3)) * (640320** (3K) ) pi += Decimal (t) /Decimal (deno) pi = pi * Decimal (12) / Decimal (640320**Dacémal (2.5)) nunberofdigits = int (input ("please enter the number pi = tpi of decimal places to calculate Pi to: *)) return str(pi) getcontext () .prac = nunberofdigits from decimal import Decimal, getcontext import mach import time Amport colorama from colorana import Fore colorama.init () print (eale(2)) start_time = time.time() print (Fore.RED + "\ntime taken:", time.time () - ef calc(n): start_time) Python in Focus: Stitching Black Holes One of the biggest scienti engineering and space-based projects came to a head in 2019, revealing humanity's First glimpse at the universe's most elusive object: a black Life) (Mel aia eLenrlmelol a ceLeleh aaa aaleliya Imaging a black holes pretty difficult. The very nature of a black hole means that nothing can escape its immense gravitational eee emer nee eet DO ee ee ee Ce a eee eee ay theory of general relativity predicts that a sufficiently compact mass eee eect rs ees eee eas ‘Although the event horizon has an enormous effect on the fate and. Se eee eee a oer eee id ‘appear to be observed. In many ways, a blackhole acts ike an ideal black body, asit reflects no light. Moreover, quantum Field theory EVENT HORIZON TELESCOPE Cee ee acre et eed este a ns as ‘ky is referred to by the amount ofthe sky they take up - units oF ee eer) See eee eee ers ‘symbol’, full ice is divided into 360° and a right-angle measures ‘90°. One degree can be divided into 60 arcminutes (abbreviated 60 ‘arcmin or 60). An arcminute can also be divided into 60 arcseconds Cert ea) For example, looking at the moon, whichis roughly 31 arcminutes, Cee ce ae ec ue og enc ces Peete ceca SS ee tee eed Re eee esa ue eee ‘ize of 40 microarc seconds, of one millionth of an arcsecond. So, inorder to see it, we would needa telescope with a diameter of pee oe ee eerie ns Seen ee cae oe Perec ec eee ery take images of the black hole over a period of around six months. Crete a eee eter Pen erie ee ete From one telescope array tothe next as the Earth rotated. in curved spacetime predicts that event horizons emit Hawking radiation, with the same spectrum as a black body of a temperature inversely proportional to its mass. This temperature ison the order ST e en gas Cee nea Peon tees ested , and mathematics written down on paper, speculated only by the ee ere ee eee Breese ene core ete ere aie Pee eee net age ere ea es eer ets eee us: Stitching BI BIG DATA AND PYTHON RESULTS. SD ee ee nie ee io eC ene a eet ee a ee ir a eee ea! ee Re eee me ee eu eee ee ree Cees also state, give it couple of years and theyll be able to increase the ener ot) Ce eee eee ae eer nee eee eer ed eet eee Allthiss thanks to some clever Python code and some very brilliant Peeters Coe gay ee eae See eed and Astropy, plus some unique custom Python code —which can be ore Ma een Working with Data h Data ROO Working with Data Pee T Cur neue cd Ee eel eet g uo eee ce ea you can create lists, tuples, dictionaries EU Rusu uno Uta uae you can use them to forge exciting and PE Ig econ RCo a hey Pe eee ue anal et M cen satel Peetu ean cs Meter carl ace a ferret oe cy => Working with Data Lists Lists are one of the most common types of data structures you will come across in PACER occa cue eat scr ut er cess! as a whole, or individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. A list can be strings, and lists within lists. \tegers and also variables. You can even include Functions in lists, Alstsaseaeneofdatasabescaectns You TRIBE Youn so ces rnc te etem nal Susi) create the name of your list Followed by an equals SIE using the minus sign before the item number [-1], sign, then square brackets and the items separated by commas; _orthe second to las tem with [2] and soon. Tryingto reference an rote that strings use quotes: item that sntin the lst, suchas [10] wil return an error: munbers = [1, 4, 7, 21, 98, 156) ‘numbers [-1] mythical_creatures - ["Unicorn’, "Balrog", mythical_creatures{-4] svampize”, "Dragon, *Minotaur"] BEER nce you've defined your list you can call each PPP D Slicngissimilarto indexing but you can retrieve by referencing its name, followed by a number. Lists multiple itersin a ist by separating tem numbers start the first item entry as 0, followed by 1, 2, 3 and so on, with a colon. For example: For example: ‘numbers (2:31 = ‘Will output the 4 and7, being tem numbers 1 and 2. Note that the ‘To.call up the entire contents ofthe lst. Fetumned values don't include the second index position (es you _— ‘would numbers{t:3] to return 4, 7 and 21). Tocallthe third om zero tem inthe (21 nis case i or ae j

You might also like