KEMBAR78
Python For Beginners 9th Edition 2022 | PDF
100% found this document useful (1 vote)
76 views94 pages

Python For Beginners 9th Edition 2022

The document provides an extensive guide for beginners on using Python and navigating Windows 11, covering essential features, security, and various applications of Python in technology. It emphasizes the importance of understanding programming fundamentals and offers insights into the evolution of coding and its relevance in modern computing. Additionally, it highlights Python's versatility in areas such as data analysis, web development, and artificial intelligence.

Uploaded by

greg
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 (1 vote)
76 views94 pages

Python For Beginners 9th Edition 2022

The document provides an extensive guide for beginners on using Python and navigating Windows 11, covering essential features, security, and various applications of Python in technology. It emphasizes the importance of understanding programming fundamentals and offers insights into the evolution of coding and its relevance in modern computing. Additionally, it highlights Python's versatility in areas such as data analysis, web development, and artificial intelligence.

Uploaded by

greg
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/ 94
February 2022 Update a For Beginners AiTeo mal Tarte LLSMOQGNIM ) Getto grips with althe essential core features. ‘and functionalty Expert tutorial on protecting you" persona data from Fackers and viruses w | iscoven [ teaan ase Improve your rong bse gin new sills on ul confidence a Black Dog Media PRINT yn FEATURED INSIDE: Navigating the Start Menu Connecting to the Internet How to personalise Windows 11 Web browsing with Edge Using OneDrive Cloud Storage Video chatting with Skype Email, Social Media & Messaging Improving Windows 11 security Wi-fi and Personal wi-fi hotspots Speeding up your computer Troubleshooting & User Advice and much more... Click the link to BUY NOW from AMAZON ae Available in all good bookshops 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. ' Pee ce Saas 4 10 ABrief History of Coding aay tt aCe UNO et ae Me DUS en Lemar ues eer ec stot Hello World 26 Equipment You Will Need 28 — Getting to Know Python 30 Howto Set Up Python in Windows 32__ Howto Set Up Python in Linux 34 Starting Python for the First Time 36 Your First Code 38 Saving and Executing Your Code 40 Executing Code from the Command Line 42 Numbersand Expressions Using Comments Working with Variables User Input Creating Functions Conditions and Loops Python Modules Python Errors Combining What You Know So Far Pythor Black Holes Working with Data Cas melts 66 Tuples asaya Ceca eos Ce eae Pe ste Creer ed es ean eens neta) i Ey a Shedstore rt a Tey with the help of our Code Portal, Featuring code for games, tools and more. Fanta: g a & g 2 ee 3 P nF see Peery eT " Getting Started eM a ates Tce IA) PE eate cica mete hen cesta t ant Pec een cm acn tees Cottier ciated: cid ne ttis Seto Re Se LT erly Mies CA ei eC Terra Seu ua tel uc el ee ey SE EO te Cae ee UCU Oa Cus and Functional, yet also easy to follow cr Sn aan ned interesting and cutting-edge technologies in the world. It’s the code that binds supercomputer algorithms together; it’s Pee ee eee er iccu ys A, and the likes of Alexa and Siri, Cortana and the Google Assistant all utilise Python for their powerful voice Pee eae EUR Ree) incredible language to learn. leer eeu Ens Thee eT cer) ene eat Con 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 froma video game to a critical element on-board the International Space Station. How do you become a Piette ira ‘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!” —— Shee: a Being able to follow a logical pattern and ‘see an end result is one of the most valued skills oF programmer. ¢ 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 a very different scene to how itis today. 8-bit computers that you could purchase as a whole, as opposed to beeing 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, 2 large plastic box. However, it wasnt so much the new technology that ‘computers then offered, moreover it was the fact that For the frst 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, thelr ‘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. It wasnt 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 ed 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 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 such a 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 willbe able to construct and Follow code. ‘Second to logicis 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 a 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 asmall element of that final product, being able to Understand what everyone else is doing will help you create something that’s ultimately beter 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 tobe abletto 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 lear, 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, t's up to you how Far to 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, is amodern concept that’s only really happened in the last Fifty years or so. However, that assumption is quite wrong, coding has actually been around For quite some time. Cel M MMM EMM M COR LOMO OM M COM MORO a CeO a 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. Fcult to pinpoint an exact Sie eee Eee iene Sema need Cee eee CoO aoc Perera Greets eee eee interchangeable cylinders automatically Steet) 85t Joseph Marie Jacquard invents 3 Sueur! eee Deemer eo Ce ome nc reciente her writing, detailing 3 method of calculating Bernoulli Numb ing the engine. This is ed as the First program. Not ble at the time. tee War, significant advances Cau Des ented eer aun ey eee coe Cees Pea ery Stn ee Cees ee re Rea ‘Assembly Language (ASM) or eee ieee Ree ts Cie Pree ees term Autocode, Soon languages Be eee Nectar ae From the 1970s, the development ofthe lkes of C SQL, Cwith Classes (C++), MATLAB, Common Lisp and more, came tothe Fore. The 80s was undoubtedly the golden age of the home ‘computer, atime when silicon processors were cheap enough for ‘ordinary Folk to buy. Thisled to @ boom in home/bedroom coders with the rise oF &-bit machines, Computer programming ‘was mainiy utilised by Universities, the military and big corporations during the ‘60s ‘and the 70s, Anotable step toward amore user friendly, orhome user language was the development of BASIC (Beginners All-purpose Symbolic instruction Code) the mid-sixtes, ‘The Internet age brought a wealth of new euro people access tothe tools and knowiedge ese aa Not only could a user learn how to code, Pen cgey Bee eee gr ‘Admiral Grace Hopper was part oF the team that developed the UNIVAC | computerand she eventually developed a compiler forit.n time, the compiler she developed became COBOL (Common Business-oriented Language), a computer language that’s stilin use today, ex=I==D 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 characteristics that help make it such an important language to learn. Gite rae ore moe eg ane uid ‘of instructions has a considerable impact on our modem digital scenes. This is wh it's such an important language to learn. ea ie Meare eee ert Ae ae Lia ee epee eer educa aise acy artificial Intelligence and web-based applications, the only limit to erento Tre eee eee nea ere erg CG eet eee ne natu genset ee enue eae Se ee ea oe aon RCo eee Rue enact ee need without having to cross multiple language barriers; Python Gere ee het eons cca BIG DATA Cee te te ou rs Basically, it means extremely large data sets that are availabe for analysis to reveal Pe ee a eee ened its not just imited to those areas, big datas currentiy being used in variety of industries, from social media to health and welfare, engineering to space exploration Bee Python plays a substantial ole inthe world big data. t's extensively used to analyse huge chunks ofthe available big data and extract specific information based on ney oe eat ery eee eee ee et ee ee ieee ance ed Pee eat Se ae ee ee Seen eet eee eee a anes teeter ye eee etc) petrecieaeni raerorpiiainintrrre espe ery” Manner handles the raw data, bt Python s present to help sft through the data so scientists “ eer ene tena eee ae meus Cee ace tca) ARTIFICIAL INTELLIGENCE. Artificial Intelligence and Machine Learning are two of the ‘most groundbreaking aspects of modern computing. Alis the Ree eno ieesCunLy ‘machine is doing something intelligent, working and reacting in simitar ways to humans. Machine Learning isa subset oF Al Pee Cece te asta tetocecnes enero ecco eT esd intent on wiping out human civilisation. Indeed, Al can be nr nee eae eee cs the ‘machine’, or more accurately the code, needs to learn Poe acre ccc Ld the inputis likely to require, or do, next. Se ee 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 See Osa eae targeted advertising and behind the code and algorithms that predict what you're looking Fo, is Python, Gea Se eur) other things to anaeyourmusia habs and ES Cee sees) pailaesraermaett eon Danner ac eutney Poeaeeihentaret iy y 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 @ 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 we and even apps built within other websites. = go * Po /ii lm ila Eee! Athough you won'ind too many triple-A rated games coded using Python, you may be surprised to learn that Pythons wed as an ‘extraon many ofthe highanking modern games Vultiplayer Online Role ng Game) games available utilise Python as a companion language forthe serverside elements, These include: code to search for potential cheating, load balancing across the a skill matchmaking and to check whether the pli client side game matchesthe servers versions. There's al Python module that can beincludedina Minecraft cd blocks, send ms ‘ofthe background complexities ofthe game. ‘As you can see, Python is quite a versatile Deu oe Mc ea See re ee oe Soe ons eee ee ES arse See ee ete ea Coy tee ae Python in your comer. Cote) ®) 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. ® ea ‘Alexa, Amazon's Virtual Personal Assistant, uses Python to help with speech recognition. Data analysis and ‘Machine Learning are the two most used Python examples, m PYTHON AND LINUX SKILLS ARE THE THIRD As ofthe end of 2018, Disney Pixar uses Python Python was the most MOST POPULAR nits renderman software discussed language on TT. SKILLS IN to operate between other Cc the Internet, THE UK. graphics packages. Se IN ny Yo, Rou Gy Yay % § - % = %, = %, $ “i \ uy sy “Hamayy™ “Ay y™ gy OVER 75% OF 90% OF ALL IT's estIMATED RECOMMENDED FACEBOOK POSTS THAT OVER 75% OF CONTENT FROM NETFLIX ’ARE FILTERED NASA'S WORKFLOW 1S GENERATED FROM THROUGH PYTHON: [AUTOMATION MACHINE LEARNING ~ CODED MACHINE SYSTEMS ON-BOARD CODED BY PYTHON. LEARNING. THE ILSS. USE PYTHON. 16,000 ttitiiti feetiitt ‘There are over 16,000 Python jobs posted every six months in the UK. QS ail Python Data Science is Google isthe top (Python in Numbers Cll PYTHON SKILL-BASED ¢ POSITIONS ARE THE & 6th: MOST SOUGHT-AFTER JOBS IN THE UK. Data Science, Blockchain New York and San thought to become the ‘company for hiring Python ‘and Machine Learning Francisco are the top ‘most sought-after job in developers, closely are the fastest growing Python developer cities the coming years. Followed by Microsoft. Python coding skills. inthe world. 195% OF ALL BEGINNER CODERS START WITH ‘AND STILLUSE, PYTHON AS THEIR PRIMARY OR ‘75% OF ALL PYTHON DEVELOPERS USE PYTHON 3, WHEREAS 25% STILL USE THE OUTDATED PYTHON 2 SECONDARY LANGUAGE. VERSION. Python developers enjoy an average salary of 79% OF ALL 149% OF WINDOWS. PROGRAMMERS USE 10 DEVELOPERS. PYTHON ON A DAY-TO- USE PYTHON 3 DAY BASIS, 21% USE AS THEIR MAIN ITAS ASECONDARY PROGRAMMING LANGUAGE. LANGUAGE. BR) cetinastartes ) Why Python? There are many different programming languages available for the modern computer, and some still available For older 8 and 16-bit computers too. Some of these languages are designed for scientific work, others for mobile platforms and such. So why choose Meee teased PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, staving 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, i0S 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 a generation _to.acar, settop 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 biliant: 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 of the device and that core ‘every piece of digital technology we use today. Some wenton to _can be built using a variety of programming languages. become chief developers for top software companies, whereas ‘others pushed the available hardware to itsimits and Founded the The languages in use today iffer depending on the situation, the billion pound gaming empire that continually amazes us. platform, the device's use and haw the device wl nteract with its ee eee Fe eat Mano ried ba Gon Ret Se wv OB Bace# > 0@ oa” certssontacatrons dy oid Arrayctrl::childLostrecua() i iffeursor > 0} Ref eshow cursor): cert chi dbestFocue() oid scrayctrLs:Paint(Oraut w) ( urfitnet bine} Pbottim =o: f header -OntSerolt(); zn < coluen.cotcanetiy iarel Reader eaeasaeht Srarese Teregrad" [jn'ow conn crtcount Ssmeen i Sia on rec Lor fe = Blend scoloroisabed, Scatortaper tah {lor fc = slend(scoloroissbled, scolorpaper): Sea seat Secu Mittatt « catcoue 9 ¢ hen Stop Seatinar Gl «eb teats Tiftreon > stoecep ieee Sora 5 ttttnay tins open iss 4. colum.cetcaunt(): gore wader carriages Scene ce Meno tase rica Em = header Tab(j) cathargin(); ton if (oD sazeren) break Srastoe 1041 0 1000000 ‘environment or users. Operating systems, such as Windows, macOS ‘and such are usually a combination of C++, Ci, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available anguages such as HTML, Java, Python and so on, More general-purpose programming s used to create programs, ‘apps, software or whatever else you want to call them, They're ‘widely used across all hardware platforms and sult virtually every conceivable application. Some operate faster than others and some {are easier to learn and use than others. Python is one such general- purpose language. Python is what's known asa High-Level Language, in that it ‘talks! tothe hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless ‘more interactions, Whilst it's not a streamlined as a Low-Level Language, which can deal directly wth memory addresses, cal, stacks and registers, its benefits that it's universally accessible and easy to learn. 7FiTe: Trvoke java Knport java. lang.reflect.*: class tnvoke public static void main Cass c = Class.fornane( args(0] ); ethod'm = c-getmethod( args [1], néw class string ( args Object ret = m.invoke( null, null system.outprintin yvoked starts method amof class: "+ args(0 "ith no args\nresults: "+ ret); catch ( Classnotroundexception e // Class. forname( ”) can't find the class catch’ ( NoSuchMethodexception e2 7] that method doesn't exist + args(1! Gavch ( Filepataccessexception 3 Tiwe don't have permission to invoke that inethod atch ( tnvocationtargetexception ef 77'an exception ocurred while invoking that method System.out.printin Snethod threw an: get Targetexception +e Javaisa powerful language that’s used in web pages, settop boxes, a ‘TWsand even cars. Python was created over twenty six years ago and has evolved to ‘become an ideal beginners language for learning how to programa computer. I's perfec For the hobbyist, enthusiast, student, teacher and those who simply need to create their own unique interaction between either themselves or apiece of extemal hardware andthe computer self Python is Free to download, install and use and is availabe For Linux, Windows, macOS, MS-DOS, OS/2, BeOS, IBM series machines, and even RISCOS. Ithas been vated one ofthe top five programming languages in the world and is continually evolving ahead of the hardware and internet development curve. So to answer the question: why Python? Simply put, its Free, easy to learn, exceptionally powerful, universally accepted, effective and a superb learning and educational tool 40 LET py=is 26 For b21 To 10 32 ces 25 Cer 30 30 ores LET py=p ige IF INKEYS5"o" THEN LeT py=P NEXT on [BASIC was once the starter language that early ‘S-bithome computer users learned, Python is a 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: THE POWER OF PI While having a Far more powerful coding platform on which to write and test your code is ideal Een) A COMO CCME- TNO rCO CCMA d C0) 'snot often Feasible, Most of Pea e entre nT aris ee Se eat help out. Re ciara eeen curene ‘rite and test your code is ideal it's not often Feasible. Most of us eee eset ene reer ee ee est ees Sa eect ed has created, of rather re-created, the Fascination we once all had ‘about computers, how they work, how to code and foundation level electrons. Thanks to its unique mix oF hardware and custom Pee a Sueur Pte ete rs DOS a eee eer ‘code with other programming languages, it’s Python that has been Ee eae ete ee its recommended, default operating system. Raspbian sa Linux Coe areata ceL teeter ec ta Pee eee een programming, as opposed toa fresh installation of Windows 10, ‘hich has no Python-specific base. However, the Raspberry Pi Foundation has gone the extra mile to include a vast range of Pores ee ee any Paes etic ee ene ent aor instructions on how to set one up (by using one of our excelent Raspberry Pi guides found at wwrw.bdmpublications.com) and you Cree ene onl rs ‘Significantly there's alot more to the Raspberry Pi, which makes ete ae ae eee oer) Seo ee er eed eee eee ate ere een emer sy Pee eta ou ec ‘r device, on your home network. For example, once you've set up Se ent Sen eee ea eet router. As longa the Piis connected, you wll be able to remotely Pe tee eS Peng ea es Duele eae id keyboard, mouse and monitor, plus, you wont need to allocate Pete ea et eee teen eee eet For space and money, then for around £60, buying one ofthe many, Seca) ree eee eta peer ere Cu latest Raspbian 05), acase, power socket and cables, thisis good eee Renee en ar aad Penne a Cea en ns eee ec Se ne ee eee ty Raspberry Pi Foundation has included out of the box. The reason Ca eae ee ete User, whether that's coding, electronics, or some other aspect of ‘computing, To achieve that goal the Pi Foundation includes different IDEs forthe user to compile Python code on; as well as both Python ee ere een ees) Peet ines There are other advantages, such as being able to combine Python. Perera nese cee Ted developed by MIT, fr cildren to understand haw coding works) and being able to code the GPIO connection on the Pito further control Ar cee ae cee Pee eg ure eee ets Circuitry that offers different electronics, robotics and motorisation projects to the Pi), which can be accessed via Python code. Cee ae Cue ea Pets octane er reasons we've used the Raspberry Pas our main Python codebase er tte eee a ae eed nee eens eda eee ‘macOS.IFthe code requires a specific operating system, then, don’t Resa included with the Os! r Caren a Introduced on 24th June 2019, the Raspberry Pi4 Model is significant leap in terms of Pi performance and hardware cations, twas also one ofthe quickest models, aside from the original Pi, to sell out. en meen a choice of 1GB, 2GB, or 4GB memory versions the Pi 4s on to becaringatrucdestnp corpus ado the PA launched withthe startling decision to include dual monitor support, inthe form ofa pair of two micro-HOMI ports. Youll als finda pair PUNT ena Inaddtion to releasing the Pi 4, the Raspberry Piteam also compiled ‘a new version of the Raspbian operating system, codenamed Buster, Inconjuncton with the new hardware the Pi boasts, Buster does offera few updates Although on the whole t appearance and operationto the previous version of ‘Updates are mainly inne wth the 4k display and playback, g ianew set of graphical drivers and performance enhancements. In short, what you see inthis book will work with the Raspberry P 4 and Raspbian Buster! Once set up, you can remotely connect to the P's desktop en ates $s Bluetooth 5.0, and a GPU thats capable of ancl 4k resolutions and OpenGL.ES 30 graphics. Inshor, the Pi isthe most powerful ofthe current Raspberry Pi ‘models: However, the different memory versions have an increased (ost. The 168 £5 £34, GB is £44, andthe AGB version wil setyou back £54, Remember to aso Factor in one ortwo micro HOM! ables wth your order. Cote) Using Virtual Machines A Virtual Machine allows you to run an entire operating system from within an app CBN rece) MUNA Y |B Col E-12) CACM osteo) 9) CRN RMA RS aU KEE LAL 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 efficient, isolated duplicate of areal computer machine’ Thisbasically means that a virtual machine is an emulated computer system that can operate in ‘exactly the same way as a physical machine, but within the confines of a dedicated virtual machine operator, or Hypervisor. ‘The Hypervisr itself an app that will allow you to installa separate operating system, crating a virtual computer system within itself, complete with access to the Internet, your home network and 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, will be set-aside For use in the virtual, machine and therefore won't be available tothe physical computer Until the hypervisor has been closed down, This resource overhead canbe crippling for the physical machine if you donttalready have enough ‘memory, or harddrive space available, or your computer has a particularly slow processor. While it's entirely possible to run Virtual machines onas little {85 2GB of memory it's not + advisable. Ideally, you wil i need a minimum of 8GB (of memory (you can get away with 468, but again, your physical computer will begin to suffer with the loss of memory to the virtual machine), a least 25 0 50GB of Free space on your hard drive and a quad- ore processor (again, you can havea dualcore CPU, buttthat can cause a bottleneck on your physical computer) Coding for Linux it OurLinux titles contain steps on how to install a hypervisor and 0s. ‘The limit to how many different virtual machines you host on your physical computer's 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 Ses You're able to install Linux, and code inside a virtual machine on a Windows 10 host. VIRTUAL OS From within a hypervisor you're able torun a number of different. ‘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, but isnt so good at Android or macOS. (QEMU!s good For emulating ARM processors, therefore ideal for Android and such, but it can be iffcut to master. There are plenty of hypervisors available to try for Free, with an equal amount commercially availabe that are significantly more powerful and offer better Features, However, For most users, bth beginner and professional, VirtualBox does a good enough job. Within a hypervisor, you're able to set up and install ary ofthe newer distributions of Linux, or if you feel the need, you're also able to install some of the more antiquated versions, You can install early versions of Windows, even as Far back as Windows 3 complete with DOS 6.22 -although you may Find some Functionality ofthe VM lost due tothe older drivers (such as access tothe network) \With this in mind then, you're able to have an installation of Linux ‘Mint, or the latest version of Ubuntu, running in an app on your Windows 10 PC. This isthe beauty of using a virtual machine. Conversely iF your physical computer has Linux asits installed ‘operating system, then with a hypervisor you're able to create 3 Windows 10 virtual machine - although you will need to have a licence code available to register and activate Windows 10. Using virtual machines removes the need to dual boot. Dual booting ishaving bwo, or more, physical operating systems installed on the same, or multiple, hard dives on a single computer. As the ‘computer powers up, you're given the option to choose which OS you want to boot into. While this sounds like a more ideal scenario itisn't always as straight Forward as it sounds, asall the operating systems that are booted into will have Full access to the computer's entice system resources. ‘The problems with duat-booting come when one ofthe operating systems s updated. Most updates cover security patching, or bug Fixing, however, sme updates can alter the core -the kemel, of the OS. when these changes are applied, the update may alter the ‘way in which the OS starts 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, youll need to access the Master Boot Record and ater the configuration to re-allow booting nto the other systems. There's ‘also the danger of possibly overwriting the fist installed OS, or ‘overwriting data and more often than not, most operating systems >) Whit sa perfectly fine envionment snot too user-friendly s leave the command tne fornow. Ener exit to eave and clse the Command Prompt wind 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. Fstyouneedto acetain which version of Python ue" is currently installed in your Linux system. To begin wth, op nto a erminl session from your dst’ menu, or hethe Grvaeer keys davidedavid-Mint:~ View Search Terminal Help re Next enter python ~-vereion inathe Terminal susPe screen. You should have the output relating to version 2xoF Python inthe delay. Mos Linux distro come with both Python 2 and 3by deft, as there's peny of code out here sillaaiabiefor Python 2. Now enter pythons =-version, davidedavid-Min Help sty View Search Poy File Edit Terminal Daun tics Pre Bey Dace) Inour case we have both Python 2 and 3 installed. Sue AS long as Python 3.x.x is installed, then the code in curtutorale wil work t's alvaye worth checking to see the dito hasbeen updated wth the latest version enter sudo apt-get update GE suds apt-get upgrade toupcatethe tem avideeavieine ~ BEEP orce the update and upgrade completes, enter: python? ~-version again to se if Python 3.xis. Updated, or even installed. As long as you have Python 3.x, you're running the most recent major version, the numbers ater the 3. ingicate patches plus Further updates. Often they're unnecessary, butthey can contain vital new elements, However you want heats, cating edge UEP 5 version, you'll need to build Python From source. Start by entering these commands into the Terminal: eudo apt-get install build-eesential checkinstall sudo apt-get install 1ibreadline-gplv2-dev Libncursesw5-dev Libsel-dev Lbaglitea-dev tk-dev Libgdbm-dev Libes-dev 1ibbz2-dev How to Set Up Python in Linux Senvpyeriniwes toner sdgotote | EERIE forbecub et oedtoezr te ours SUEPG Python download page: https://www.python.org/ a command into the Terminal: downloads. Cick onthe Downoads alowed bythe buton under the Python Source window, This opens a donnloed dog bo, choose a location, then start the download process. The IDLE can then be started with the command: 4dle3. Note, that IDLE uns a different version to the one you installed from source sudo apt-get install idles “dvidedavi Min: —/Downleadeythen 7.2 Inthe Terminal, go tothe Downloads Felder SUED byentering: cd Downloade/. Then unzip the contents ofthe downloaded Python sourcecode with tar vt bython-3.¥-1 ear oc eplace the Y's withthe version numbers Youive downloaded), Nowenterthe newly unzipped oier wih yehen-3.¥.¥/ SPEED ouitatso need MP (Pip nstalsPacages, whichis S v 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 3x willbe available via the Programming section in your distro's menu, ride in:Download yon 372 FETED within the Python folder, enter: /configure sudo make altinatall = ‘This could take a while, depending on the speed of your computer. Once finished, enter: pyehon3..7. --veraion to check the latest installed version, You now have Python 3,7 installed, alongside older Python 3.xx and Python 2, Installation of Python on macOS can be done in much the same way as the Windows installation. Simply go to the Python ‘webpage, hover your mouse pointer over the Downloads link and select Mac 0S 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 Me wea) ) BE) 26210 ) Starting Python for the First Time The Raspberry Pi offers one of the best all-round solutions on which to learn and code, nna Tun cos eun Cece omen cticeisel hata latest stable version of Python 3, which makes it a superb coding platform. STARTING PYTHON Everything you need to begin programming with Python is a ble From the Raspberry Pi desktop. However, ifyou want, drop into the Terminal and update the system with: sudo apt-get update. EERE With the Raspbian desktop loaded, click on the EGER (orexample,in the shell enter: 242 Menu button Followed by Programming > Python ‘After pressing Enter, the next ine displays the 3 (DLE). This opens the Python 3 Shel. 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. FETED Theshelliswhereyou can entercodeandseethe RSW The Python Shell acts very much like a calculator, responses and output of code you've programmed since code is basicaly 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, fi RS SE Sw ten or tn print (*Hello everyone!") While that's very interesting, it's not particularly exciting, Instead, try this: Just enter itinto the IDLE as you've done in the previous steps f . . . (_ Starting Python for the First Time Cll PEPE The Python IDLE isa configurable environment. you don't ike the way the colours are represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don't recommend that, a you won't be seeing the same as our screenshots. ao Sa oa PETPD Thisica ittle more tke it, since you've just produced ‘your First bit of code. The Print command is fairly self-explanatory, i prints things. Python 3 requires the brackets as ‘well as quote marks in order to output content tothe screen, in this ‘ase the Hello everyone’ bit. >>> print("Hello everyone!") Hello everyone! >>| Yury hve noticed the colour coding within Sue 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 [[-eetoor [use tor Texans | Ughtres[Erormesssos | syseamneror Eee ust lke most programs available, regardless of the ‘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 Timananen st secon Seems | ‘ThePython DLE isa power interface andone SUzP0 that’s actually been written in Python using one ofthe salable CU took you want toknow te many ns and outs ofthe hel we recommendyoutake a few moments to view www.docs.python.org/3/library/idle.html, which details many of the DLEs features, Cee ED) stoi) Your First Code 11a al ROU R YE] Le Ane UaR OU M ele)(e el meee Acne Melia Male} everyone!”)' Function from the previous tutorial. However, let’s expand that and look at entering your code and playing around with some other Python examples. 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. FATE RED you've closed Python 3 IDLE, reopen itin FaTeGE DD You cen see that instead ofthe number 4, the ‘whichever operating system version you prefer. In ‘output isthe 2+2 you asked to be printed to the the Shell, enter the familiar followin: screen. The quotation marks are defining what's being outputted to the IDLE Shel to prin the total of 2+2 you need to remove the quotes: Jats encrdretospeasinine — ETERP voucen conve anh ping 2.454283 Buse Shell as blue text, indicating output from a string. 2%) and so on to the Shell. An easier way is to use a It's fairly straightforward and doesn’t require too much explanation. —_ variable, which is something we will cover in more depth later. For Now now enter \What you have done here is assign the letters a and b two values: 2 and 2. These are now variables, ‘hich can be called upon by Python to output, add, subtract, divide ‘and so on For as long as their numbers stay the same, Try this: print (a) ie ket Oud tay tes dees te Fetes o cea ferme tention, Conroe PEPE) Nowletsadd a sumame: surname="Hayward” ‘You now have two variables containing a first name and a sumame and you can print them independently |e eo i ‘The output of the last step displays the current BD hes of both a ond incvualy 2s you've asked them to be printed separately. fyou want to add them up, you can. use the Following Eint (a4b) ‘This code simply takes the values ofa and b, adds them together and outputs the result. ee oe aoe en wee te we were to apply the same routine as before, ua? using the + symbol, the name wouldn't appear corretyinthe output inthe Sel Try print (name+surname) — ‘You need a space between the two, defining them as two separate values and not something you mathematically lay around with, ESTES) Youcan play around with ctferent kinds of variables and the Pri Function. For example, you could assign variables for someone's name: FETS ERED | Python 3 you can separate the two variables, with a space using a comma: print (name, surname) _ ‘Alternatively, you can add the space yourself print (name+" "+surname) ‘The use ofthe comma is much neater, as you can see. Congratulations, you've ust taken your fist steps into the wide Zz » Hello, World Saving and Executing Your Code While working in the IDLE Shell is perfectly Fine for small code snippets, it's not Cesium Cn ca ecu ta nance uN Mcrae olst 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. FRR cane merm accu msc, ERB voxcn cc urbesane car coomunpie ERD increase sep ite sitnteak eon vinetietzistane husteraerbLcehernsenin tobe waewat ssnoringew es sore you can enter the code needed to create your Future programs. execute the code you need to first save it. Press FS and you get 2 Save...Check box open. ER Te ee The IDLE Editor is, forall intents and purposes, a FTeEE DD Clckonthe Ok button in the Save box and select a simple text editor with Python features, colour New File From the Shell) Enter the following and save tas hello.py: astython* bovis e=*cool print(a, b,c) ‘Youwilluse this code in the next tutorial Talay enafpDoamewaPyinon icheogy Gal) > 4 tat rma ie ten ats Be 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 inthe GUL at the command line level Python nix, comes wth Si executing code via the comma oosiinoot REESE nowsovre ste conan we cant line. One of the sue Python. For Python 3 you need to enter the {put you into the h Python 2, whilst the other uses the Python 3 libraries command python3 and press Enter. Thi igh, drop into the command ine or Terminal on command line version ofthe Shell, with the Familiar three right your operating system, Facing arrows as the cursor (>> em Frome toenter the: ve dat previousty, such as: print (a) Command Line returned search; You can see that it works exactly the same, and macOS users Can get access tothelr command line by clicking > utiles > Terminal Executing Code from the Command Line FETED Nowenter:exit() to leave the command ine Python [EEEIM the result of running Python 3 code from the session and return you backto the command Python 2 command line is quite obvious. Whilst it prompt. Enter the folder where you saved the code from the doesn't error out in any way, due to the differences between t previous tutorial and|st the available Files within; hopefully you way Python 3 handles the Print command over Python 2, the result should see the helo.py File isn’t as we expected, Using Sublime For the moment, open the hello py ie PSTD Fromwithin the same folder as the code you're PED since Sublime Text isn't available forthe Raspberry ‘going to run, enter the following into the Pi, you're going to temporarily leave the Pi for the -ommand tne ‘moment and use Sublime as an example that you don't necessarily ‘heed to use the Python IDLE. With the hello.py file open, ater itto include the Following: python’3 hello.py This will execute the code we created, which to emind you is b nane=input “what is your name? *) as"Python” print (*Hello,", name) berier e="cool!* 2 print (a, by ¢) ESTED Naturally, since this is Python 3 code, using the FRED Seve the hellopy file 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. iFyoulike, ry the same cade with: with Python 2 by entering: python} hello.py python hello.py The result willbe the original Python is cool statement, together with the added input command asking you Fer your name, and displaying it in the command window. Etat Numbers and Expressions We've seen some basic mathematical expressions with Python, simple addition and the like. Let's expand on that now and see just how powerful Python is as a calculator. You 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 with most, ifnot all, programming languages, maths isthe driving force behind the code. BET SEED Open up the GUI version of Python 3, as mentioned ‘You can use all the usual mathematical operations: ‘you can use ether the Shellorthe Editor. For the divide, multiply, brackets and soon. Practise with a time being, you're going to use the Shelljust to werm our maths Few, For example: muscle, which we beieveisasmallgland locatedatthebackoFthe brain or not Inthe Sellete the Following: Yexive no doubt noticed, ston produce Bue = muse decimal number. In Python these are called Floats, —— or lating poincarthetic. However Fyou need anintegeras, prose oa decimal answer, thenyoucan urea double lth sone7s4aea73aaae4za1 You can see that Python can handle some quite large numbers. Seana ee ae) 20/3 Will isplay 3333333333, which is of course 3.3-ecurring, IFyou now enter: 2083 ‘This wll display 1, which isthe remainder left over From dividing 10 into 3 ‘You can also use an operation to see the remainder left over from division. For example: Numbers and Expressions ell PEP This willbe displayed as’0b11, converting the integer into binary and adding the prefix Ob to the Front. F you want to remove the Ob prefix, then you can use: format (3, *b") ‘The Format command converts a value, the number 3, toa Formatted representation as controlled by the Format specification, the’ part. eS ae ERD oes aarti ovo ‘out the power of something you can use a double multiplication 2 Essentially, it's 2x2x2 but we're sure you already know the basics behind maths operators, This is how you would work tout in Python. Numbers and expressions don'tstop there. Python has numerous builtin Functions ta work out sets ‘of numbers, absolute values, complex numbers and a host of mathematical expressions and Pythagorean tongue-taisters. For ‘example, to convert anumber to binary, use: bint) ‘Boolean Expression logical tterent hat wil Suz? either be true or false. We can use these to compare dataand testo see fs equa lesthanor eater than, Ty es ina New Fle: ans be7 print (1, print (2, print (3, print (4, print (5, print (6, print (7, print (8, print (9, Execute the code from Step 9, and you can see 3 Suzdo series of True or False statements, depending on the result ofthe two defining values: 6 and 7. t's an extension of ‘what you've looked a, and an important part of programming, ED) at Using Comments When writing your code, the Flow, what each variable does, how the overall program will operate and so on is all inside your head. Another programmer could follow the code line by line but over time, it can become difficult to read. #COMMENTS! Programmers use a method of keeping their code readable by commenting on certain sections. Ifa variable is used, the programmer comments on what it’s supposed to do, for example. It's just good practise. FR ry reainga new nance ofthe LE Eaton Resoe the code and exeate ie Youcanse thot he (File > New File) and create a simple variable and output in the IDLE Shell is still the same as before, print command: despite the extra lines being added. Simply put, the hash symbol (#) denotes inc ef ter the programmer an hero horn em, andoaers of hats ging on without thee beng Sware Print (“the value of A is,", a) ‘Save the file and execute the code. ~ fe it Sein toe soe ee Ce Camera gy henalplOouen Fyn Cakvoonrens pal) = © ® at Fart Bin Stine Yn th SE cinsccicutcamicic pecacets REED iascnncve vovescn once ED oiscss cere ere ecto wasn eye ‘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 ines of Whilst we know that the variable As 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 lines long, instead of just our seven. You can see how handy comments ae. Essentially, the new code together with comments could laok ike: Siar 4 Set the start value of A to 10 ae10 # Print the current print ("The value of A i ¥ Player lost a life! aval # Inform player, and display current value of A (lives) print (*You've just lost a life!*) print (*You now have", a, “Lives left!*) Using Comments Ci PEPER 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: ac10 # Set the start value of A to 10 print ("The value of A is,", a) # Print the current value of A aea-l # Player lost a life! print ("You've just lost a 1ife!*) print ("You now have", a, “Lives left!") # Inform player, and display current value of A (lives) ‘The comment, the hash symbol, can also be used to Su comment out sections of code you don’t want to be ‘executed in your program. For instance, iFyou wanted to remove, the first print statement, you would use: # print ("The value of A is, 7 Set the start value oF A to 10 10. Print the current value of A prinecThe value of A & Player lost’ life! 1 inform player. and display current value of A (lives) pranc-Tou've just lost 2 Prine("You non have". = ‘lives eft") BR voucan ue commentsin different was For Bue? ‘example, Block Comments are a large section of text that dtals what's going on inte code, suchas teling the code reader wha variables you're planning on sing ¥ 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 smell} # works really well. You also use three single quotes to comment ‘outa 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't slept or washed in weeks. Despite being very smelly, the code at least works really well. ED) tt Working with Variables We've seen some examples of variables in our Python code already but it’s always worth going through the way they operate and how Python creates and assigns certain Neo NTU oom VARIOUS VARIABLES You'll be working with the Python 3 IDLE Shelt in this tutorial, If you haven't already, open Python 3 or close down the previous IDLE Shelt to clear up any old code. In some programming languages you're required to.usea dollar sign to denote a string, whichis variable made up of multiple characters, such asa name oF person. In Python this isn't necessary. For example, in the Sell enter: nane="David Hayward" (or use your own name, unless you're also called David Hayward) [Get Sod og pine een Per a Sa re TP FETED You've seen previously that variables can be concatenated using the plus symbol between the variable names. In our example we can use:print (name + *: + title}. The middle part between the quotations allows us to add a colon and a space, as variables are connected without spaces, so we need to add then manually “i 6S Sel ue tee ree ESTEE Youcan checkthe typeof variable in use by Ce eaten thevarabl side the braces nou example, ths would be: type (name). Add a new string variable: See) cco) TE EDD ois wihinanotherverable For [ example, combine both name and ttle vaiblesinto anew varableweuse: charactersname + *: "+ title Then output the content ofthe newvatebe as print (character) Numbers arestoredsderent verabes age=t4 ‘type (age) Which, as we know, are integers. However, you can’t combine both strings and integer type variables in the same command, as you ‘would a set of similar variables. You need to elther turn one into the ‘other or vice versa. When you do try to combine both, you get an, ‘error message: Bey Working with Variables PPI This presents a it of a problem when you want to ‘work with a number that’s been inputted by the User, asage + 10 won't work due to being a string variable and an integer. Instead, youneed to enter: Ant(age) + 10 “This wil TypeCast the age string into an integer that can be ‘worked with et for mre nfm. ede eee ret te ets or ee ty ‘This isa process known as TypeCasting. The Python codes: Siar print (character + * is “+ strlage) + * years” ola.) ‘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 toprint separately >>> print (name + age) ‘Traceback (most recent call Last): File "", line 1, in ‘brine’ (nane * age) ‘Typetrror: Can't convert "int object to str implicitly 23S"prine (enaracker #5 32" + str(age) +." years 01d") David Hayward: Descended fron Vikings is 14 years old Do> print (character, "is", age. “Years old.) David Hayward: Descended trom Vikings is 48 years old. ‘Another example of TypeCasting is when you ask For input from the user, such asa name. for example, STEP7 enter: ages input ("How old are you? *) ‘All data stored from the Input commands stored asa string variable. ‘le Eat shel Debuy Options wows tp ‘The use of TypeCasting is also important when MED Sess wit eating pin arthmetc remember: ‘numbers that have a decimal pointn them. For example, enter: shirt-19.99 Now enter type (shirt) and youll see that Python has allocated the number as a float, because the value contains a decimal point. ee eo Relea Se aoe aay mtieensec™ more information. |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 oat to an integer, Python will always round down to the nearest integer, called truncating; in our case instead of 19.99 itbecomes 19, ‘le Eat Shel Debug Options windows ip [repens cere. cer (ee't.5.4} on ina Tipe Scoot ow of are"yout 23 oe fypeteey sso D roger or “cana” fr more sntormation Python 3.4.2 (@etault, Get 19 206, TBSTET) (eec'4.9:13 on tim tree en eredsta” oF “Hicense()" for nore information. se Shecahiry my (Hello, world User Input We've seen some basic user interaction with the code From a Few of the examples earlier, so now would be a good time to Focus solely on how you would get information from the user then store and present it. 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. FATED Fit’snot already, open the Python 3 IDLE Shell, FETeGE DD Now that we have the user's name stored in a and start a New File in the Editor. Let's begin with couple of variables we can call them up whenever something realy simple, enter: ‘we want: TEED See and execute thecode, andasyoualieadyno BRS) run the code and you can see a sightissue, the ‘doubt suspected, nthe IDLE Sell the program will fullstop after the surnamefollows a blank space. ‘askFor your firstname, storing its the variable firstname, followed To eliminate that we can adé a plus sign instead ofthe commain by your surname; also stored nits own variable (surname). the code: ‘You don'talways 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: Print (*Hello. what's your name") namesinput () serinput py - /home/pi/Documents/Python Code/ust [Ele Eat Format Gun Options windows Help Drint(-Hello. what"s your nane?™) ‘anes input() User Input TEED What youve created heres a condition, which we will cover soon. in short, we're using the input from the user and measuring it against a condition, So, i the user enters David as their name, the guard wil allow them to pass unhindered. Else, iFthey enter a name other than David, the guard challenges them toafight. ‘The code from the previous step is often regarded as being alittie neater than having a lengthy Siar ‘amount of textn the input command, but i's not arule that's set in stone, 0 do as you lke in these sitvations. Expanding on the code, try this namesinput () ‘le Git Famat fin Sten dows BEER estas you learned previously, any input from a User is automatically a string, so you need to apply “TypeCastin order to tum itinto something else. This creates some Interesting additions to the input command, For example: # Code to calculate rate and distance print ("Input a rate and a distance") rate = float (input (*Rate: *)) FRTeGEAD {52 900d start toa text adventure game, perhaps? Now you can expand on it and use the raw input From the user to flesh out the game a litle: inclement sr, 00 may pss") PEPPER 70 Finalise the rate and distance cade, we can add: distance = float (input (*Distance: » print ("Tine:", (distance / rate)) Save and execute the code and enter some numbers. Using the float(input element, we've told Python that anything entered sa Ett) Creating Functions Now that you've mastered the use of variables and user input, the next step is to tackle Liven me UN Elle NA er RUA een Mage eee een aa eel) enables you to define your own Functions. FUNKY FUNCTIONS ‘Afunction is a command that you enter into Python to do something. It's a little piece of self-contained code that takes data, ‘works on itand then returns the result. EATER ¢snotjust data thata Function works on. They can BEES You can pass variables through Functions in much do all manner of useful things in Python, such as the same manner. Let's assume you want the sort data, change items From one Format ta another and check the numberof letters in a person's surname, you could use the Following length or type of items. Basically, afunctionisashort word that's _code (enterthe text editor for this example): followed by brackets. For example, ten(), list() or type. nanesinput (“Enter your surname: *) - — aod Lo i Se gsi rie ent fo mae neat Press F5 and save the code to execute Aficionado vata weson ETREEB ton estes ouncons bution frco Buse it depending on what the Function is programmed Sue) many to get into in the limited space available here. todo and returns the end value. The data being worked on goes However, to view the ist of builtin Functions available to Python 3, inside the brackets, sof you wanted to know how mary letters ‘navigate to wunw.docs python.ora/3/library/Functions html. These are in the word antidisestablshmentarianism, then you'denter: __are the predefined functions, but since users have created many ‘Jen(*antidisestablishmentarianisn") and thenumber 28 more, theyrenot the only ones available. ‘would return FETED A ccitional functions can be added to Python BEE 10 use afunction froma module enter the name of through modules. Python has avast range oF the module followed by afullstop, then the name ‘modules available that can cover numerous programming duties, _of the Function, For instance, using the Math module, since you've ‘They add Functions and can be imported as and when required. For _just imported it into Python, you can utilise the square root function, ‘example, to use advanced mathematics Functions enter Todoso, enter import math ath. sqrt (16) Once entered, you have access toallthe Math module functions. _Youcan see that the code is presented as module function(data). FORGING FUNCTIONS ‘There are many different functions you can impart created by other Python programmers and you will undoubtedk Bae Ce eam sey eee aN Ce gnu! PIR choose File > Now File to enter the editor let's PER 0 modify t further delete the Hellot“Davie’ line, eee eter en ertn Dean eane seme ied ae Toe eee ae Vi Brine (ietior Pres reece ati eee inane Reese acces Gem rens ay ate tercht oo import the module then use the Function. Try this one, and modify omer Fietlo ("Davia") ‘This will now accept the variable name, othervise it prints Hello Dae ame eee ag Ges rg ie ey ED) tt Conditions and Loops Conditions and loops are what make a program interesting; they can be simple or rather complex. How you use them depends greatly on what the program is trying to achieve; they could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS. Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking iF something is TRUE, then doing something else if tisn’t. LevsceateanewPxthonprogromthatwilask SBE now youcan use of statement tocheck the thesertoinpurawordthencheck Rose Fis wort engin voble seul four and prs afourdetter word or not. Start with File > New File, and begin with friendly conformation if it applies to the rule: themputvarble ‘The double equal sign something else, rowsecanceseanewssstethensetheen EREESP recon atte erdofalayten ths Sue function and pass the word variable through it to. mee) ‘statement is true do everything after the colon get the total number of letters the user has just entered: that's indented. Next, move the cursor back to the beginning of (Conditions and Loops Cll BEIM 055 F5 and save the code to execute it. Enter FETE Now expand the code toinclude 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 t's the word isfourletters. added a condition for three-letter words: Now press FS again and rerun the program but ths time enter a Five-etter word, The Shel will display that i's not aFourletter word. "Please enter a four-letter word: “) helen (word) if word length print (word, “is a four: done.*) elif word_length print (word, ‘is a three-letter word. Try again.") else eter word, Well print (word, “is not a four-letter word.) LOOPS: TC ene eae ee sem NRO et ee block of cade a number of times, usually with the support of a condition. STEP1 Ye eee step 3 Bue this will check to see iF something is TRUE, then run Gee ees ee z eee PEPER The citference betweenitandwhileiswhen while IM the E engl nee Ciera ene ee eaters Z peer maanierfaeeer Rem nemeat:

You might also like