0% found this document useful (0 votes)
376 views195 pages

The Complete Coding Manual - 5th Edition, 2020

Uploaded by

csystems
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
0% found this document useful (0 votes)
376 views195 pages

The Complete Coding Manual - 5th Edition, 2020

Uploaded by

csystems
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/ 195
The Complete Sorelle] fark "B® pbfekec(a.tve Suen Saas) Pe ees Build Your eno EN ea Manual Gees FRITZ!Box _ Manual Minna Tvs Saul © a The Complete Linux Manual The Complete Coding Engineer your Future; learn to code! er CM nS Bo em oe Cu neta a sts 6 Pec process enables you to interact with a device 21,500 tines ofcode Cee eo ete aa ESR Oe te ue at) Pell ean Reese ne ge are layers of code that define everything that happens. And you can learn how it all works. Coding requires patience, imagination and great tutorials to help you understand what to enter, and what exactly is eae tt eee AE provides you with a solid Foundation, on which to begin learning how, to code, before moving on to introduce more complex techniques and Bene eats reece Sua kes This manual is your guide to discovering the boundless world of code BEC s eden bi Cet s eee ated Python in Num Why Python? Equipment You Will Need Getting to Know Python How'to Set Up Python in Window How to Set Up Python in Linux Working with Variables User Input Creating Functions ‘onditions and Loops Python Errors Combining What You Know So Far Dictionaries pitting and Joining Strings Formatting String} Date and Time Opening Files Writing to Files Exceptions hon Graphics lendar Modul Random Module Tkinter Module Pygeme Module Create Your Own Modul w Crt Facts & Figures Equipment You will Ne 1 Set Up C++ in Window Set Upc: Mac Up C++ in Linux Other C++ IDEs to install Program Structure of a C+ Program Compile and Execute Using Comments, Variables Data Typ: Strings C++ Maths User interaction Character Literals Defining Constants File Input/Output ex: “~ eee While Loop For Loop Do... While Loop IF Statement If. Else Statement Getting an Output Playing with Variables Batch File Programming Loops and Repetition Passing Variables to Python Retro Coding Text Animat Creating a Loading Screen with Python For Animation Common Coding Mistakes Python Beginner's Mistak C+ Beginner's w Where Next? Sree , Foundations \ - ~ Coding Foundations ( MR ea acoso Coc aussie BSCE ens Eu) Ce Eel) Mesnard) Peres tects SUC NULL ud In this section, we look at what you will Peed ned enue kates mcr hus become a programmer in twenty-four eMC Mn ae Sete Pee sua ae little help, you can master the basics and start your coding journey. msoubsmablcationscom A Brief History of Coding It’s easy to think that programming a machine to automate a process or calculate a value Poiana he cuce cl eeciiea rete etre PSU ene Ree ee SCE eset eho Eon uo RC RRR MC RRC ne Essentially all forms of coding are made up of ones and zeros, on or off states. This works Petar ee eet tee acs ST ee there sgifcantadvances CE eae Sears roe te! Pec ney Pye ery eerie butwasmede amousby Alan ees cone et eee cet ete mea) Face ena Net eee yd ee atc eee eas ere eee er) Ree eterno cra Pee eects Coenen) See oeeren arene Emenee ecto eer Ste ts Ces cetiees Perea Ly Pres Se er ene nae Dee eer Peer er ed ere Te aan Rectan tee teres eee reece peered eet ee ecu ns eee sr eee AT nT Pee ac cs te genericterm Autocode, Soon Peer ee ae and ALCOL 58 were developed. ‘Admiral Grace Hopper was par oF eee eee i computer and she eventually Ae ao Cees COBOL (Common Businessoriented preee ea tee tees aes E> Coding Foundations Being a Programmer Be Ee One ame CeCe ce eT Cet a ate oe teenie Wn ane ki occu toa critical element on-board the International Space Station. How do you become a Pca id ‘Times have changed since programming in the“B0s, but the core values stilieemain. “It's up to you how far to take your coding adventure!” Being able to follow a logical pattern and see an end results one of the most valued skils oF programmer. ( Being a Programmer Ez 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 tis today. sit computers that you could purchase as awhole, as opposed to beeing in kitForm and youhaving to soléer the parts together, were the stuff of dreams; and getting your hands on one was sheer bss contained within large pasticbox. However, it wasn't so much the nev technology that computers then offered, moreover it was the Fact that forthe First time lever you could control what was being viewed on the television. Instead of simply playing one ofthe thousands of games availble atthe time, many users deided they wanted to create their own content, their ‘oun games; o simply something that could help them wit their homework. corhome finances. The simplicity ofthe &-bichome computer meant that {zeating something from afew lines oF BASIC code was achievable and so the frst generation of home-bred programmer was born. From that point on, programming expanded exponentially wasrtLong before the bedroom coder was ating ofthe past and huge teams oF Sesigners, coders, artists and musicians were invoivedin making a single game. This of course led to the programmer becoming more than simply ‘someone who could Fashion a sprite onthe screen and makeit move atthe press of key Naturally time has moved on ae with tthe technology that we use, However, the fundamentals of programming remain the same; but what exactly does it take to be programmer? ‘The single most common taitof ary programmer, regardless of what they're doing, ithe ablltyto see a logical pattern. By thiswe mean ‘someone who can logically folow something from start to finish and envisage the intended outcome, While you may not Feel you're sucha person, itis possible to train your bain into this way of thinking, Yes, ie takes time but once you start to thinkin this particular way you willbe able toconstruct and Follow code. ‘Second to logic is an understanding of mathematics. You dont haveto be ‘ata gerius level but you de need to understand the rudiments of maths. Mathsis allabout being able t solve a problem and code mostly fallsunder the umbrella of mathematics, Being able to see the big pictures certainly beneficial For the made programmer. Undoubtedly, asa programmer, you wil be part of ateam of other programmers, and more than Ukely part ofan even bigger team Of designers al of whom are creating afinal produc. While you may only be expected to create 3 small element of that final produc, being able to understand what everyone else is doing willhelo you create something that's ultimately better than simply being lacked in your vm coding cubicle. Finally there's als a level oF creativity needed to bea good programmer. ‘Again though, you dont need to bea creative genius, just have the Imagination to be able tosee the end product and how the user will interact witht There i ofcourse a ot more involved in being a programme’ including learning the actual code itself However, with time, patience and the determination to lear, anyone can become a programmer. Whether ‘you want tobe part of triple-A video game team or simply create an ‘autemated routine to make your computing life easier, i's up te youhow Far to take your coding adventure! tinatictoccon CE It would be impossible to properly aT) - ee Bed False PenCNa icicle tein} == "MIRROR 7". AGAR EER CcneGh=. *Gullvs ses nari Sota and ways in which to ‘talk’ to a computer ae = False or device and set it instructions are being ia cam xt ES ee eee ene nnn Ce use_z = Cadet eM nn ten mau hel een te mn ASCs art meee eens "_ob.select= 1 me ee a rose ee Mea nee las “Selected” + str(modifier, rror_ob.select = 0 » bpy.context.selected_ob: Peis) jects [one.name] .s@ select exactl} <= aS al nae ENE) ee chee Senin ee eect For accessing and manipulating databases Although SOL isan ANSI (eee see ate ere ee ad eee ee ae eters Eon ore etre eat eer eee ngs Beas wnierigari e Dee eran Sea eran ae peach elt 2 meer SS SS erent Seis! 7 2) Saale Gels ivcn! is aan ‘itis an elegant object-oriented language that enables developersto ne ey ree et amr ag Framework You can use Cito create Windows client applications, XML erent tere een ech eee Curly-brace syntax of CA will beinstantly recognisable to anyone Familiar with C, eee a thon” ee te ee errant ec) py Fa ae aaentet eae om Ne a eearletmra ronan ; eee eS Seems oe a) language. thas imperative, obectoriented and generic programming tae ee ce ine oun) ‘embedded, resource-constrained and large systems, with performance ffidency Pre eget cS Flexible language; essential parts of Ruby can be removed or redefined, a wil Careers ee eee uu eee een ‘ange of tasks including system administration, web development, ‘network programming, GUI development and me. ts major Features are that its easy to use, supports both procedural and objeccoriented (00) programming, has powerful builtin support For text processing and has one Cheeta mts Perret erent een ener ey | "Tin Fence nreatirmerer ee tree naltes 7 , Copa eee ee ieneret en ene se ere coterie eee ee ae eet eee es persecute Se Coding Foundations Creating a Coding Platform ) Pre ce eae eerie ca) peesne eu isis], te Pt Mona ae) Fave some offclty follow some ofthe best programme thinkin you 8-5 machine, 50 there's hope ye star learning how to round today strte reed to purchase any extrasoftware in order to self changing from the vironment and using a collection 6, tools ta write your code. t's al nthe end and as you become more wil start to use eiferenttoolsto get the Poeun windows 10's the mest used operating systemin 7 the word, soit’ nacural i thatthe vastmalortyof F coding tools are written for Micrasof's leading operating ster, However, dart discount macOS ad especially nun. 1macO5 users enjoy an equal number of coding toolstotheir Windows counterpats. Infact you wilprobaby find thet 3 let of professional coders use « Mae aver #PC, simply because ofthe Fac that the Mac operating system is bul on top oF Unix the commonsdtine OS that powers much of the wore's Fissystemsand servers). This Unix layer lets you test programs Inalmost any language without using a specialised IDE. Ln however, iby far one f the most popular and Important, coding operating systems availabe, Not only does ithave a Univlke backbone, butalc it’ also free to ‘download install and use and comes with mast ofthe toels necessary to start learning how to code, Linux powers most of E theserversthat make upthe internet. 's usedon nearly all oF E the top supercomputers, aswel as specially in orgarisations suchas NASA, CERN and the military andit forms the base oF ‘Anero:ponered devices, emart TVeand inca systems, Linus, ¥ asa coding platform,isan excellent idea andit can beistaled ¥ nde a vrtal machine without ever affecting the installation | of windows ormacos. Hy THE RASPBERRY PI E youhavent already heard ofthe RaspbemyPi, then Ewe suagest you head over to wnwwraspberypiora.ané 5 checkitout inshort, the Raspherry Pisa small fully Functional computer that comes with its own customised Linux-based operating system, preinstalled with ¥ eversthina younced tostart learning howto codein Pythen, 44, Scratch and more, Iesincreibty cheap, costing around €35 and alovs you to use Eeferent hardware, nthe Form of robotics and electronics projects, aswell as fferin complete desktop experience. “Although net the mast powerful eamputing device nthe vert the Raspbery Fahas lot oie for, especialyn tors f being ‘one ofthe best coding pltforns avaiable YOUR OWN CODING PLATFORM. \hicever method you choose, remember that your cading platform will probably change, as you gain experience and favour oe language over another. Dont be aad to experiment along the way, as youll eventually create your aw unique patForm that can handle all the code you enter into. Wut munter n= iNeed. ( Creating a Coding Platform Ez” Avictualmachne apiece ofsofmare that alows youto rstalla Fully working, operating sytem vthinthe confines othe software isa Theinstaled OS wllalocate user-defined resources from the host computer prowding memory harddvespace et, aswellas Sharing the hast computer's inte connection. Theadvantageofaviruel machine sthatyou cen work vith Lins, forevample without £ Raecingyeur arent, inetd nos O5. Themeane thatyou can have Windows 10 running, aunch you vitualmachine lent, beot into Linuxand use allthe Functionality of Ln while sl beng able touse Windows. This of course, makes ita Fantastic coding platform, as you can have cifferen installations of operating systems running from the host computer while using cifferent coding languages. "You can test your cade withaut Fear of breaking your host OS and i's easy to return toa previous configuration without the reed to reinstall everything agai, ‘virtualisation ithe key to most big compares now. You wil probably Find, For example, rather than having a single server ‘sith an instalation of Windows Serves theIT teamhave Irstead opted Fara vitualsed environment whereby each Windows Serverinstance isa tualmachine running from several powerful machines, Ths cuts down onthe umber ‘of physical machines allows the tear to better manage resources and enables themto deployan entire server ecicated oa particular taskinafaction ofthe time. The NEONA2C+4is an etraorinary simall computer ram mink dovelope, MIND, Measuring jst 138. 138» 20mm, ths Inet N4200 CPU ‘Poweree, Windows 10Propresnstaled comauter sone ofthe best coding platforms weve come across. The beauty, oF couse, lesin the fact that with increased storage ane memory avalable, you abe to create computer that can easly host multiple vitual machines. The tual machines can over Liu», Android and other operating systems allowing you towriteand test cross platform code without fear of damogin, ‘rcs problems, with other production or home computers. The MINK NEON#2C- stant at around €250, with the base $3208 eMC and 4G8 of memory. Youll med to acd another hundred and fifty, oro, oinreasethe specications but considerthatalcerse for Windows 10Pro alone costs £219 From the Micosof Store and you can begin tose te benefits CFopting foc amare impressive harvare foundation ove the kas ofthe RaspberyP. Introducing Python Dare nee Oe eae nay Deu ned eeu euset eee! Cs ne NE Cree eet Ete ced Dt es aL Seer oot Se meat ease you into the world of Python, ES a SUS Ree ar Pr Taran a EO ie Pe aC Py Meme tary tu Cece aan td hiroding ; UM naman ido Vy There's a Fading seni 4 PUthon ap” co lot to like about one P&S From apse Python, but don't just ing Circus Y take our word for it. Here are some amazing facts-and Figures surrounding one of the most popular Programming languages of recent years. ® ee ‘Alexa Amazon's Virtual, Data analysis and Personal Assistant, ses Machine earing are the Patonto help with two most used Python speech recognition. ‘examples. 3018 PYTHON AND ty LINUX SKILLS ARE THE THIRD «csesython ‘ortnwend of 2018, MOST POPULAR —_,DiseyPharuses Python iscussed language on IT. SKILLS IN to operate between other the internet THE UK. oraphic packages (1) (a is ) (re) | OVER 75% OF 90% OF ALL ISestimateD 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, THELSS. USEPYTHON. | saan: ( Python in Number [ PYTHON SKILL-BASED ¢ POSITIONS ARE THE ¢ 6th: MOST SOUGHT-AFTER The bs. Tagen elton JOBS INTHE UK. Q G al Python Data Science is Goole isthe top Data Science, Blockchain New York and San thoughtto become the ‘company For hiring Python ‘and Machine Learning Francisco arethe top most sought-after jb in developers, closely are the Fastest growing Python developer cities the coming years followed by Microsort. Python coding sil in the world Python developers enjoy an average salary of == £60,000 (95 (7%) (re) (wt) — — (ta se mt 95% OF ALL BEGINNER 75% OF ALL PYTHON 79%OF ALL 49% OF WINDOWS CODERS START WiTH DEVELOPERS USE PROGRAMMERS TO DEVELOPERS : ‘AND STILLUSE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3 : PYTHON As THEIR 25% STILLUSE THE REGULARLY, 21% USE ‘AS THEIR MAIN PRIMARY OR OUTDATED PYTHON 2 TTASA SECONDARY PROGRAMMING z VERSION. LANGUAGE. LANGUAGE, é SECONDARY LANGUAGE. rootinabictoccm CIT ) Introducing Python Why Python? De ic ens enn oe eee eee ctcarc 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 Neate ets PYTHON POWER Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away untilthe wee hours, staving ever an overheating heap of circuitry to create something akin to magic. These pioneers of programming carved their wayintoa new Frontier, forging smal routines that enabled the letter to seal acossthe screen. may not sound terribly exciting to a generation that’s used to ulirahirdefiniion graphics and open worl ult player online gaming, However, Forty something years ago Ie was biinginlybiiant. Natural these bedroom coders helped form te foundations for ‘every piece af digtal technology we use tad. Some went an to became chief developers for top software companies, whereas ‘thes pushed the avlable hardware tots its and founded the bilfon pounel gaming empire that continual smazesus. Regardless of whether you use an Android device, i device, PC IMac, Linux, Sar TV, games console, MPS player, GPS device Buln toa car, sebtop box ara thousand other connected and smart appliances, behind them ais arogramming, Alithose aforementioned digital devices need instructons tote ther whacto do, and allow ther tobe interacted with, These instructions form the programming core of the dvice and tat core can be built using avariety af programming languages. ‘Thelanguages in use today differ depending on the station, the platform, the device's use and how the device willinterac withits| a veraaay] @ BRT e Ho Oe Setcirseris yt certsserstasstbecuid? pid erayertecntaboneeei) ‘ttcurgor == 0) Pofceehor curr) cxntiensia accayeert::Beint(Orms WI 4 irtanetsbae i Size size > ortsize0; ‘ Tieden cetserat (02 = os 3p x col. once i900 header atfobangth Wate ‘ersorid + {js'=» colum.cetceunt() - 11) >= 0} Ger fe = slend(soloroisabled, scotorPaper; Seeman titel cetcaune0) Tyee ciestanerta) «ob Fikeeeop size] breaks (biter © eee Tatlineerins feeding Sensi Street ross Same Soca eve Seyi Semnnae Scarncrass re Grate ‘environment or users. Operating systems such as windows, macOS ‘and such are usualy @ combination of C+, Ci, assembly and some Form of wsual-bosed language. Games generaly use C+# whist web pages can usea plethora of avaliable languages suchas HTML Java, Pythenandso.n More generat purpose pragrarnmingis used to create programs, ‘apps, software or whatever alse you wantto cal them. They're ‘widely used across allhardware platforms and suit vitually every ‘conceivable application. Some opesate faster than others and some ‘are easier toleam and use than others, Python iene such genera Purpose lancuace, Pythoniswhat'sknown asa Highevel Languace, in that etal! tothe hardware and operating system using avanty of arrays, variables, objects arithmetic, subroutines, (oops and countless mare inceractions Whist its nat as streamlined as a Low-Level Lanuaae, which can dea dcetiy with memory addresses, al stacks and registers, its benef tis that i's universally accesible ‘and asy to leer, [73122 sovoke. java [npore. java. ang. reflect. iss invoke { BBETSEEcle void mane string (aos ¢ ty Tikes ¢ = class. forvne( args(0) 3: rath Catered ABE, ty cass Gbiéct hic = m-invokec nul, mut 9; Sto Sree i” TOT UNS wethods * + a Poe eass S Sargstol * , So oreh a args Otel: = 4 ree 95 catch ¢ Cialorabthdencestion ¢ > Pr GiaSectornameC ) can't: Finds the class » LoS iegite test option 9255 » Gud Mlegataccesatxception @3 > { 77'we don't’ have permission to Tivoke that » Sec 3) { 77'an exception scurred ninile invoking that Peart ysrenechod threw an: + e4. sntintoettctpt ong “38%: Why Python? Ea Python was ereated aver twenty sk years ago and has evolved t0| become an ideal beginne's langusge for learing how to program 2 ‘computer. Ws perfect forthe hobbyist enthtsiast, student teacher ‘and thase whe simply need to create their own unigueinevaction between either themselves or apiece of extemal hardware and the computer tse Python i ree to dovnload, instal and use and is aval for Unux, ‘Windows, mac05, MSDOS, 05/2, B05, IBM series machines, and ‘even RISC OS thes been voted oneof the ton five programming languagesin the world andis continually evoking ahesd ofthe hardware and Internet development cur, Soto answer the question: why Python? Simply put, t's Fee, 238) to learn, exceptionally powerful universal accepted eFective and 3 superb learning ane educationaltook ‘BASIC was once the starter language that early ‘-bithome computer users earned, python isa more modern take on BASIC, W's easy to learn {and makes for an ideal beginner's programming languag roobinanictoccn CT ) Introducing Python Equipment You Will Need V You can learn Python with very little hardware or initial Financial investment. You don't need an incredibly powerful computer and any software that's required is Gee eee WHAT WE'RE USING Thankfully, Python is a multi-platform programming language available For Windows, macOS, Linux, Raspberty Pl and more. IF you have one of those systems, then you can easily start using Python, COMPUTER Obviously you're going to need a computer in erde to learn howto program in Python and to test your code. You can use windows from XP onward) on either a 32 ‘or Dit processor, an Apple Mac or Linux install PC | ANIDE An DE (Integrated Developer Eniconmentfsused to enter and execute Python ‘code. tenables you toinspect your program code and the values within the code, as ‘well as offering advanced features. There are many dfferentDEs avaiable sofind the one that works For you and gives the best results PYTHON SOFTWARE ‘macOS.and Linux already come with Python prenstalledas part ofthe operating ‘system, 25 doesthe Raspberry, However, you need toensure that you'rerunning the latest version oF Pytnon. Windows users need to downoad ard install ython, which walleover shorty. TEXT EDITOR ‘hilt atexteditor san ideal environment to enter code into, snot an absolute recess. You can enter and execute code del Fom the IOLEbut atext edo, suchas Sublime Testor Notepacs, offers mere acvancee Features ancicolour coding ‘when entering code, INTERNET ACCESS Pythonisan ever evolving environment and as such new versons often Introduce new concepts or change existing commands and code structure tomake it amore efficent languege, Having accesso the Internet will keep you upto-dt, help you ‘ut when you get stuckand give acess te Pythons immense urher oF medules TIME AND PATIENCE Desoite what other books may lead you to believe, you vont become a programmer in 24haurs, Learning to code in Python takes time, are patience You may become stuckat times andother teste code il Flow ike water Understand you'e leering something ently new.and youwliget there, THE RASPBERRY PI ( Equipment You will Need Gi” Why use a Raspberry Pi? The Raspberry Pisa tiny computer that’s very cheap to purchase, but offers the user a Fantastic learning platform. ts main operating system, Raspbian, comes preinstalled with the latest Python slong with many modules and extras. Renae ‘The Raspberry Pi 4 ModelB isthelatest version, Incorporating 2 more powerful CPU. a choice 168, 268 67 4C8 memory versions and Wil and Bluetooth ‘support. You can pickup a From around £33, increasing Upto £54 forthe AGE memory version, or a apart oF Kt For £50, depending onthe kit youre interested i, ‘The Rasplery P's main aperatng system isa Debian based LUnuceistribution chat comes with everyting you need in simple to use package. t's streamlined for the i andis an ideal platform for harchare and software projects, Python programming and even as a desktop computer The FUZE isa learning environment bull onthe atest model (ofthe Raspberty i, You can purchase the workstations that ‘came withan elactronie ki and even arabat arm for you ull and pcocram. You can find more information onthe We have soveral great Rasphery Pitti avalable via www. bdimpublicstions.com, Our books cover how-to buy your first Raspberry Pi setitup and use t there are some creat step baysteo project examples and guides to get the most Fomthe Raspbery Getting to Know Python Pa aacecatecc eur re tc reichiinl one coe ceteris language on which to learn how to code, but it’s also powerful enough to be used by companies when trawling through petabytes of raw data. PYTHON POWER Python isa high-level, general-purpose programming language that was designed by successor to the ABC Programming Language, and became available to use in 1991 ‘The Python Software Foundation, a nor profit arganisation devoted toboth Furthering and improving Python, curently develops the language. The Foundation's purpose isto “promote, protect, and advance the Python pragranming language, and to support and Ree emo eee ee aaa Peed Se allowing those who arejust beginning tocode to follow i without eer ate eee etry fies ete nee sega ete ta ea Big Dataand Alarethe two fastest growing Pythor backed technologies a the moment, 8ig Data simply armodern term erie perry ened el Oey Sees eae paneer ee co ey area ray Petia Reet eee coe CEE Perron Ce CE eee en ee cuca image ofa black hole was released, the supermassive blac hole in ferent as See ee eee eee eee es ee es ees ete ret eters ein eee ee eed eee tar acd eee tee a seer eee ay Se een eee es ster, the team then used Python to painstakingly stitch together See ee eee tence te eer Intelligence. although we'estilla long way off fom the visionary stores of Arthur C. Clarke, Alis ast becoming one ofthe mast Ea en eee eet ee ee robots the Al that Python crives i designed to create autonomous te era ee eee ee ren ccs Seen a Goad PYTHON 3 VS PYTHON 2 GES Ems ea een eee men pte ier Pree ieaey eco Ca ee Cap ae e eee ted ie ennai eee eet et ere aera eer ee gn ee sa Ce sn Un kters Cettn ee ie i ee eid eee nee eaas ee ee ee eg Ue eee sees oe es eee ee earned Ca er eer ee meee eed ere i errr enna ee sot eee Cee ee rer intrusive, or even an invasion of privacy, you have to ait thatthe ee eee ee a eer eat Ciever techniques, a Python developer is able to create amachine Se eee ae ther websites andideas relating to what you've searched For, eee ere eid re tee eee area eer ner Seen ee eet) Something more efficiently. nthe case of neural networks in the ee en ar ee ee eee eee era or etme te amare accurate result, or doth maths behind the code quicker Se ee oo ato Dee Pooch tents NI es eee er aera Ree tee ee ees ele ie fees eee re sd eee ee a ee er ee nie Le ee ee ree eee a ee eee] Cee ie Se tee asy ate ee ie tas tN ete eee ames Ce ere eee IO er ee eet ae gee ee oe ue eee eed Cee ta tronses the existing Python 2 conter-ra Python 3 may take more een ee ie al hammered no Ks coF ih infact, xper to see tac cf date Cee eet Ped aon) enor crore) pee ees Pea eee ren ene) rn eerste) Pe ents Poteet eer Stee) Pere tts pean Pee ed ars ea Coens eared port] ec Ce occa et Cen eens eee eter te err anne eee anette teen Pel eee Le ee ie etal eter! => Introducing Python How to Set Up Python in Windows Nee ily install the latest ve DO ol DCE ee AN ne sues ern eo eo Ma eect platform of choice for building th ¢, it's still an ideal starting point for beginners. INSTALLING PYTHON 3.X Microsoft windows doesn’t come with Python preinstalled as standard, so it will be necessary to install it yourself manually tars cae FR vor crnryoscetrnsrtnmnoytes ED feoccuroceimante Owens halen sr Sees elagnsey Sea Yyousee Python 38, or more, aslong ass Python 3, the code in this book wil work ine. To ce Clkthe Doweload bon for version 2xand STE save the file to your Downloads folder. when the feisdovnloaded, double he sxecitable andthe Pon ietalaton wear wllmnch Frm ere, you have two chor: ial Now and Customise nalaton,wevecommend ato or thecustomice stalin Ink J insta Python 3.7.0 (32-bit puthdn, : BED xottanicionsccn BRED choosing the customise option allows you to specify certain parameters end whist you may stay with the defaults, it's ¢ood habit to adopt a, sometimes (not ‘with Aythen, thankful, nstalas can incude unwanted adeitional Fescure, Onthe Fst screen avalable, ensure al boves are ticked ane cick he Next button, S ar en sna & Tenens outhén The net page of alone inci seme inteesting Gua additions to Python. Ensure the Associate file with Python, Create Shortcuts, Add Python to Environment Variables, Procomp Standard Libary adn for Al Users option ae tke These ake sng than ater mich ease Cea when youre rend eo conve Optional Features ap ——— : & eee ci fe a (Coogee RE PEER v1 may n00c to confit instal the Windows authentication notation. simpy d nd Python il bean to instal Oncethe Installation s complete, the Final Python wizard page wil allow you to view the latest elaase notes ad follow some online tutor Setup was sucessful a = pythén windows, = EEPETD ocfore you close the install wizard window ‘owe i's best to click an the link nex to the shield detailed Oisabie Path Length Limb. Thiswilalow Python tobypass the Wi execute Python procrams Click Yes again, to authentic ions 260 character iitaton, enabling you to din Geen folders arrangeme the proces, then you can Close the The fist Unk, Py version af Pyenon whe the DL ted (more on that na moment), Teapen oo 6 Fiter Best match IDLE (Python 3.7 32-bit) eo Search suggestions suave the Pythan Shell, where you can begin your Python broaramming journey, Dont wory I your versions newer, astong as t's Python 3x our cade works insie your Python 3 interface IF younow clickon the Windows Start button again, and this ume type: CMD, youl pcesented wit vane Prompt linc. Click Eto get tothe Windows command lie environment, To enter Python within the command ine, you need totype: python and press Enter. Theconmandlneverionaf Ponuertin Sue) much the same way as the Shell you opened in Step @rtethe thet fang arewsters wh kv ere tnetor non, emer ete) lene ane cet Comerend b> Introducing Python) How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it’s often dificult to nail down just one-way of doing something. Different distributions go about installing software indifferent ways, 50 For this particular tutorial we wil stick to Linux Mint. niaureedanatanvnciwnonet muon EEBEPB) crete wt ate constr ee STEP 1) iscaurrently installed in your Linux system. To begin Uses python3 ==version again to see iF Python 3.x’is vith drop inte a Terminal seson rom yourdsire'smeny ori the erevehistaled. Along asyou have Pn 3 youre Creator es ne mest ecenerajorverson, the numbers afte he 3. incicate patches plus further updates. Often they re unnecessary, davidedovie.mine:~ but they ean conta ital new elements Fle Ede View Search Terminal Help ESSER ex, enter python’ ==varsion intothe Terminal ea) FY ) Foundations Dre fs Python Foundations €¢ DES acy Ones etc T programming, These are your First Bete Ca ea a) Pee ne he hes ae First piece of code, save it and run it in Pe se Dee Cee) Ce Am ee and loops and the types of errors you Mee ees OMe ee ee ee pects ar Se cuca ean Your First Code Saving and Executing Your C ad Ree ere eres ey ) Python Foundations ) Starting Python For the First Time etch eM Can Merman ast ass your version of Python is 3.4.2, or something lesser than the current version, as long as Senna Nae tes aU ktuars STARTING PYTHON {As when learning anything new, you need to start slow. You can pick up the pace as your experience grows, but for now, let's just get something appearing on the screen. Don't worry, you'll soan be coding like 2 pro! ESTEE (ics onthe windows Startoutton, and starttysing BREEN ror example, nthe Shll enter: 242 ile. The result illbe the curenti installed After pressing Enter, the next ine wil display the vetson of Python, IDLE (Python 3.7 32-bi, for example. Youcan answer 4, Bascally, Python has taken the ‘code! and produced the Pin itto the Start Far convenience, otherwise simply click recon to relevant output. launch the Python Shel Tesi auheesovcneticobandce te ERIM Tetons acs vryrch he sca Buse responses and output of code you've programmed ua since code is basically a series of mathematical int Pathon.Thisisakiné of sandoox Fyouvilwheregoure able intacbonswiththe tem. nage whicrare the fine totry out some simple code ane processes. sequence of whole numbers, can easly be added, subtracted, rutile, and soon ‘whe tat's very interesting snot partly Sue ‘exciting, Instead, try this: print("Hello everyone!") Just enter int the IDLE as you've done inthe previous steps. Starting Python for the First Time eal BED pene scrrpeat ccm Bia ‘you don't like the way the coloursare represented, thanyou cat cane pte» cfg OLE a cicking onthe Highlighting i, However, we dont recommend that [you vent be seeing the sme as oursereensnots casethe Hello everyone bi. >>> print(“Hello everyone!) jello everyone! ESTER) Youtthave noticed the colaurcoding withinthe Python IDLE. The colours represent diferent elements of Python code, They are: Black Data and Variables Green—serings Purple- Functions Orange- Commands flue - User Functions DDarkRed Comments Light Red Error Messages IDLE Colour Coding [Feetour [Use tor [exampies | Puple—| Fusion | Seno psist i) Uptred [Erwrenengs | arctan BED 2% vith most sroarams avaiable, regardless ofthe operating system, there are numerous shortcut keys. te dit have room for themall here, but within the Oations| > Configure IDLE and under the Keys tab, youl see alist of the currencbindines ESSER thePython Lcisa power interface, and one that’s actually been written in Python using one ‘ofthe avaiable GU toolkits. you wane to know the manyins and ‘outs forthe Shell we recammencyou take aFewmomentsto view hntos//does pvthon.ora/3fibraryiclehtm ich detais mary of the DLE features. Your First Code ee AE eR UN eae Sger MT a ee) Cen M eon ec ee ete aac Cee Net Re CE u OM Rte ic teenie PLAYING WITH PYTHON AAs with most languages, computer or human, i's all about remembering and applying th You're not born knowing these words, so you need to learn them. Hodedseeheon2Dieeopenteses — ERRAEB rovtnoetir raed hemunoer the ua" Gidin the previous page. n the Shell, enter the SIGs ‘output is the 2+2 you asked to be printed to the fare falloving screen. The quotation macs ae cefning what sbergeutptted tothelDLE Shel to pntthe total of 22 s0ul nee to remove the ques print(2szy ight words to the right situation, print¢*Hettor) FEED % vrediced the word Helloanpearsinthe shel — EVAR) voucan contine assuch, printing 242, 46412343 asbluetext indicating autput froma sting. Rs _ands0 an tothe Shell. An easer way sto use a fairystraightforward, and doesr't requretoo much explanation. variable, which fs sernething we wl cower in more depth ater. For Row ir now, enter printc"242") oz ED wnubamplcaionsion \Whatyou have donehero's assign te letters and b two values: 2 and 2. These are now varbles which can be called upon by Python to output add, subtract, dide and soon, For as long as their numbers stay the same, Tr ths print(a) print(b), ( Your First Code ell ‘Now let's. ad a surname: surnane="Haynard” print¢surnane) ‘we now have twa variables containing both a frst name ands surname, and we can print them indenenderty askedthem tebe priced separately. you wantto.ade them up, youcan use the following print¢asb) This code takesthe value af bath and ads them together, and outputs he result. ESTED) Youcon play srourd wth different kinds of variables together with the Print Function. For example, we ould assign variables for someene’s name: ane="Devia” printCncme) BITE |e were to apply the same routine es before, using the + symbol, uhe name would appear correc inthe outputin the Shel Tryit print (name surname) ‘We need a space between the two, defining them as two separate \aluesand not something you mathematically play areuné with ERTTSET BD Potton 2 we can eparace the ewo variables with espace by using a comma: print(nome,, surname) ‘Alternatively, you cen add the space yourselE print(names” “+surname) Asyou can se, the use ofthe comma ie much neater ‘Congratulations, yu'veust taken your firststepe intothe wide werid et Python ) Python Foundations ) Saving and Executing Your Code Re On ses eerste ek a et for entering longer program listings. In this section, we'll introduce you to the IDLE RC ens tee ener nce EDITING CODE You will eventually reach a point where you have to move on from inputting single tines oF code into the Shell. Instead, the IDLE Editor will allow you to save and execute your Python code. Fenscomtnerentesul ten vn ck TARE you casein sare ow corgi ie SHEP ‘on File > New File, this will open anew window with STEPS) the IDLE Editor as itis in the Shell, enabling you to Unless Rename Thstee thon DUEEdtor anc wn, you beter undertnd vnat'sgung on with aur cage, Texte he can enter the cade you need te create your Future programs. code, however, you need to Fistsave it Press FS and you'lhave a ‘ave. _.Check box open FER tre Le Ecitoris forallintents nd purposes, RIP) ick onthe OK button inthe Save box, and salect simple teat editor wih Python featutes, colour destination where youl save all your Python code, coding and s on. You enter code as you would within theShel so The destination can be a dedicated Folder called Python, or you can taking an exampe rome previous tutorial eter just dump wherever you tke, Remember to heap a dyle sytem, : ough, Ele you eu nthe Future printc*HelLo everyone!") pi elie ain Enter anata you cde, pt hl SUPE ‘example, and click on the Save button, As soon asther\thoncodels sve. ts eeeted andthe cut wl De Geta he BLE Stet nts case the words Helo ene! This shew the vast major of your Python code willbe conducted. Enter tito the Ector, hit F, savethe code, andleokat the autputin the Shel Sometimes things will eifer,depencing on whether you've requested a separate window, butessent al thats the process 76, unless otherwise State, thisis the method we wil use, ESTED) | vovcnen the ie locacion of che saved Python code, youll notice tet ikends in a.py extension Tiss the default Python Filename, any code you ceate willbe \whateve: py, and any code cownlosdes from the many Intemet Python resource stes willbe py ustensure thatthe code snten For Python 3 ( Saving and Executing Your Code ell 02 b2 nane="Dovid” surnane="#aynard” print(nane, surname) print Corb) Ifyou press 5 now, youll be asked to save the filagain, as i'sbeen mositied fem before Lots extend the cade and enter afew examples from the prevlous tutoras BETTE vou cickthe OK button thefiewilbe overt swihthe new code entries, and executed: wth the ‘uiputinthe hel nota preblem wth just these Few tines but iF you were to eit larger fle overaitng can become an sue Instead, use Flle> Save AsFrom within the Edtorto create a backup, pis career : ESTEE Noe createarcn fle, close the dor, and open new instance (File> New File rom tve Shell Enter the following, and save tas hellopy ‘o=tPython” botist™ "cool |" printca, b, <) ‘We will use this code inthe next tutorial Python Foundations Executing Code from the Command Line COMMAND THE CODE Using the code wwe can run code that was made in STEP 1 you Fstinstalled Python, the sanding we can start urine autemat cally included alte necessary python andor components to allow the & 2 ° seman 7 104 words, the command ine, To begin wit, cick Star Button, and type: End aud ue arcing he Python BLE From hore you able to etc the cede you' Bure lick on the returned result frem the search, the Sui looke wiously, Such as Command Prompt Aap Thiswilluncha new ito vthablack background and white text. Tiss the command in Terminal macOs, Linux, and Raspberry Bl operating systems. bESRECED actly the same exitO to leave the promot Enter the folder where you saved the code from prevoustutorial andlst the available files within; you should the hella py fle aMacor Linux and Pl you maybe alittle commandline ten ee Town the Windows version of Python Ux python insted of python. feaon behind thes that UNDKtke ystems, sch ae macOS, aux, already have Python ibraries prestalled, These and libraries ae present bacause some ofthe macOS and Linux stem ing 2 newer vecson have dre ities rely on Python 2, and terete ‘oF Python, and thus akering the executable name, conzequerceste thesyster, ‘asaresult, developers decided that the best approach for macoS. and Linux ystems would be te leave te command ine ‘ython’ as exclusive Python 2 use, and newer versions of wserinstalled Python woul be pyehon3" Executing Code from the Command Line From within the same olde asthe ‘enter the allowing intothe commane tne python hetlo.py Thiswill execute the cade we crested wich to remind you's ‘o=tPython” boris" "cool |” print(a, by Thsisnt anisue with Windows asitdoesnt use any Python libraries other than the ones installed by the user themseies ‘when acaalyinstaling Python, when Windows user installs Python, the instalation wizard wl autorinclude the command tne instance to the core Windows PATH variable, witch you can view by entering: path int the pyaar File required command ine. dorvtrecommend youirstal bth Python 2 and Python 3 hin Windows 10;raturaly, you can you want, Bue ealstiall although Python 2slhasa foothaldin the ceding werld Pythor 2s the newest version However, Fyou do, chen you wl need to rename one of the Python versions names; as they willbe instaled incifferent folders and both use python.exe ast executable, sate ong windec have both versions of Python installed ) Python Foundations ) Numbers and Expressions MCSE rs rare see ae uO ee ence ne R ieee hee tear Cicer cte cnc eT ele SU ea Peele ane ellen ene el IT'S ALL MATHS, MAN You can get some really impressive results From the mathematical powers of Python, as maths isthe driving Force behind the code with most, if notall, programming languages, nena the CUversion af Pon 3. asmentioned You can well Siar ‘you can use either the Shell or the Editor. For the: SUG? the customary = aS time being, we're going to use the hell. you've opted to use 2 Mathematical operstons: divide, anor thireoarty text editor, note that you need to get tothe IDLEShell multiply, brackets andso on. mate wit for this part ofthe tutorial Practise with few, for example . uw 2 as = me 24283 vas cazacaray FED othe Shell enter the Following BaD “vr, ae Bisecussts concen aie rH zt called Floats, ar Floating point needanintegeras opposedtos iste ‘decimal answer, then you can we a double la ve oe EER voucmacoue an operation to see the remainder left ove Fram {ivsion For example: wa vill esply 3333333333, whic i, ofcourse, 3 3.recuring, you row enter: 109 ‘This will splay 1, whichis the remainder lef over from dividing 10by3, FD vecurwe have the power {perator, or exponentiation IF you want co be technical Towork ucthe power af Something you can use a Couble mulipiation symbol, lordoublestaron the keyboat 293 "0 Essentially ts 222, butwere sure you already know the tsi behind maths operators Tiss how you would work outin Pron. EER Nunbersane expressions don't stop there, Python has numerous builtin Functions to work out sets of numbers, absolute values, complex numbers, anclahost of Mathematical expressions and Pythegarian tonquetwsters. For tearm, to convert anumber to binary, use bin) Numbers and Expressions Ell Thiswill be SEO displayedas ‘0b1, conversing the nteaer into inay, and adding the prix Obtothe fron. youwant to remove the Oo prefix, then you format, "b") The Format command conv avalue,the nurnber 3, to. Formattedrepresentation ascontroled by te format speaification, the b part FID 2cclean expression isa logical statementthat il ether be tue or false. We can usethese to compare data, and test to soe ts equal to, less than, or greater than. Try this in aNew File o=s ~ > print, print(2, a= 7) print(@3, a= 6 ondb 7 print, a= 7 ond b a print(S, not @== 7 ond b = 7) a=6) print(6, a= 7 or b == 7) yw print(?, a= 7 or b = 6) 2 aoe print(, not Ca = 7 and b == 6)) a print(9, not @== 7 and b = 6) BRPTET BD xccute the code fram Step 9, and you'l see 2 series of Tru o False statements depending on the result ofthe two defining values: Sand 7. t’san extension of| ‘what weve looked at, anéan important part of programming ) Python Foundations ) Using Comments When writing your code, the Flow, what each variable does, how the overall program Pere eres une rec chaenaars code line by line, but when the code starts to hit thousands of lines, things get a little CTtiret voles Te, #COMMENTS! ‘A method used by most programmers for keeping thelr code readable, is by commenting on certain sections. For example, Ifa variable is used, the programmer comments on what t's supposed to do. It's just good practise ‘welstat by creating anewnstance ofthe DLE SuEH Editor (File > New File), and then create a simple variable nd pintcommand ont Prine(*The volue of A is,", a) Savethefie an execwe te cove B Commentsipy -C/Python Code/Commentpy (37.0) STEP2 Als, 10 into the IDLE Shel wincow whichis what ie expected, Now let's add some of the tyaes.of comments you'd rrmally see within code: # Set the stort value of A to 10 onl8 Print the current value of & Print¢*The value of Ais,", a) [a emeg tn Cee armen gy 7 FRED) be-ssvethe code and execute, You'll see that the ‘tout nthe IDLE Shel stil the same ae before despite the exralines being added, Simaly put, the hash symbol) denotes line of text. the programmer caninset, to informthem ‘nd others of what sgoing on, without the usar Being aware PII bers assume that the variable A weve created is the numberof ives ina game. Every time the payer des, the value decreases by 1. The programmer cauldinsert a Foutine along the Unes of owt print(*You've just Lost a life!” print(*You now have”, a, “lives LeFtt” [a cones Cota Code while we know thatthe variable denotes number oflves nd the player has|ust lost one, a casual viewer, or someone checking te code, may net know. imagine Fora ‘moment that the codeis twenty thousand nes long, instead of just cursevan You can ae how handy comments ar, Brest ax Essentially, the new code together with comments «could look ike # Set the stort value of A to 10 onie 4 Print the current value of A print("The value of A is,", a) # Player lost a life! ona-1 # Inform player, and display current value of A lives) print("You've just lost @ Life ") Print("You now have”, a, “Lives Left!" PSTESED You conuse comments incifferent vas. For ‘example, Block Comments ae 2 large section of tex at detals whats going on in the cade, suchas eling the code reader which variables youre planning on using # This is the best gone 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 ( Using Comments El Inne Cornt comment ta: ow 2 Slee ‘section of code. Take our examples from above, stead of heernmte code on 2sepeae ne ve coud ee o-10 # Set the start value of A to 10 Print(The value of Ais,*, a) # Print the current Salve of & cari # Player tost o 18fe! prinkc'You've Just lost @1iFel) rint"You now have, op *lives Left!*) # Inform Player, ond eisplay current walue of A (lives) ‘The comment, the hash symbol, can also be used to. comment ou sedtiors of code you dont want to be ‘executed in your program. For instance, you wiantedtoremave the Fist print statement, ou would use # peint(“The value of A is,”, a) [B “Commensy-CsPyon Code Comment py 70 Fle E&e Fomst_ Ron Opens Window Hide ESTER Yous%o use threesingle quotesto comment ut 2 Block Comment, or multiline section of ‘comments For them to work, lace them before and after the areas, you want to comment: This is the best gare ever, and has been developed by a crack squad of Python experts who haven't slept or washed in weeks. Despite being very snelly, the code at least works really well. 77 ) Python Foundations ) Working with Variables AWA Dec Cae Conetie eater cece Mana eee eet ee orn aoa ee eases ete Rol eek RUT) VARIOUS VARIABLES Well be working with the Python 3 IDLE Shell in this tutorial. f you haven't already, open Python 3or close down the previous IDLE Shell to clear up any old code. FERED some programming languages youre required rouse acolla sign to denatea string, which sa variable mage up of multiple characters, suchas aname ofa person, In Python thissnt nacessary, co for exarpie, nthe Shell enter: ‘nome="David Hayward” iuse your own name, unless you'e aso called David Hayward, ‘Asse seen prevoush, aribes an be Sas concatenated using the plus symbol between the vavablenames inouresampla wecan ee print (nae +“ ‘Te LET. The mile part Deoveen he quan low ustoade olan a spice Asvaaes reconnected whouk Sates, we need ood them manvaly Youcan check the pe of ible in use byising Suave the typerG) command, placing the name of the | varbl nie the rake ou example, ths wold be ‘type (nme). Add 2 new sring var abe: kit Lee" Descended from Celts" @ ED ntamanlicionsion Wecanaio SUP combine variables ‘ihinanother vari, fr camp tocombneboth name ‘ane title variables into anew variable, we use: character-nane + title Then output the content ofthe new variable os print: Character) Numbers are stored as afferent variables: genta Type Cage) hic, a6 we now, are integers, SPR over you cn'tcombin botsirngs ne sue Integer type variables in the same commandas you would asetot sar verbs Youlinee etm one mothe thes or vice versa, When you do try to combine both, youll get an ferrormessace print (rane + age) ERS) 1's S22: trownasripecasin.thePthon print (character +“ is “+ strCage) +“ years old.”) Alternatvey, you can se print (character, “is, age, “years old.) ‘otce againthat nthe lest example, yu dost need the spaces between the wards in quotes, as the commas treat each argument toprine separately BSPAED) 2o:her example of Typecasting is when you ask for input from the use, suchas 2 number. for example, enter ‘age= input “How old are you? *) ‘Alldatastore from the Input commandis stored asa stringvariable ( Working with Variables ell BPR is presents bi of aprotlemuhenyouwant suave ‘te work with a number that's been inputted by cheer for example. ar 92 = TOlsbothastiino verble and an imeger itwortwork teed, soured ere inttage) + 10 ThiswlTypeCast the age string into an integer that can be worked with BRED Te use cf Typecasting is also important when dealing with floating pont arithmetic; remember numbers that havea decimal point i thei For example, enter: shirt=19.99 ‘Now enter EypeCShiirt) and you see that Pyehon has allocated! the number a a at, because the value contain a decimal point. ESTER When combining incegersand oats Python usualy conver te integer to 2 flat, but should the reverse ever be apolie, it's wort remembering that Python ‘Soesn'=returs the exactvalue. When converting 3 Hest to 39 integer, Python wllabways round down to the nearestinteaer, called truncating; in our case instead of 19.99, becomes 19 ie ) Python Foundations ) User Input AWA Dol emer ea Re ol TUR co eC ete ema ane oni RR ee eee eats USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding, A game, for example, may ask for a character's name, whereas a database can ask for personal details, isnot areads, open the Phan 3 DLE She Sua" ‘and start a New File in the Editor. Let's begin with someting realy smoleenter prine¢*Hett0") FrstnomesinputC*that ts your first name? “> printC*Thans."> ‘surnames input(“And what is your surname? “) Save anc evecute the code an as youre douse. SUare ‘suspected, in the |DLE Shell the program will ask foryeurfieerane song eae thesarabefstame falew=cby Youtsurame, sored son ve urame), in ED wnutamaanlcaionsion Now hate have the sesame soredina SUGPS couple of variables, we can call them up whenever we want: print(‘Welcone”, firstnane, surnane, you're well. today." T hope ened creer Ar - 3 fun the code andl noticea sight ie, the SURG full stop after the sumame follows a blank space. Toelimiate that we can add aps gn ead ofthe comma h thecode: printC*Welcone”, firstnane, surnames". I hope ‘you're well. today.” You dnt hay haw tac ote tet win SUE? E) ‘the Input command. For example, you can ask the User thelrname, and have the inputin the tine below print¢*Hetlo. What?s your nane?”) ome=input() bese print("Halt! Who goes there?”) ome=input() ESTED: 2 9000 starctoa text adventure game, perhaps? Now wecan expand oni and use the raw input From the user to Flesh out the game alte LF namen="David?: primtC-Welcome, good sir. You may pass. else: print¢“T know you not. Prepare for battle!) User Input \wnstyuvecoatedneeica contin bred on suave the user's input. In short, we're using the input fromehevser and nenvine tenant conckan Teer, fhe sarees Gada ter name, the arcu ator deo = vnhindered however thy enter raeoer than he gure chslencesten So8 ha As you leamed previously, any input From a user Isautomatialy a string. so youtlnged to apply a TypeCast in ardor to tin inca something ese. This creates some interesting addons tothe input comand. For example 4 Code to calculate rate and distance print(*Input a rate and a distance”) rate = float Cinput(*Rate: “)) ESTED rctofinalsctne ate and dstancecode, we cana distance = foatCinput(*Distance: *)) printC*Time:”, (distance / rate)) Save and execute the code, and enter semernumbers. Using the Float{input element, we've told Python that anything entered is 2 Floating point number rather than asttng, ) Python Foundations ) Creating Functions NS eh aes oe ts Teg UCC sg et ncn en Ted) lee ae RU a ee eee a eeu mel eee) Oct ina ired FUNKY FUNCTIONS A function i command that yu enter into Python inorder to do something, I's alittle piece of self-contained code that takes data, works on it, and then returns the result, sraenydatuttindon ween tors TRAE You can pra tos ots nm Sua! can doll manner of useful things in Python, such as | SIGS the same manner. Let's assume you went the sorects, change te am oneformacto anther ane check he numberof letersn a ertonssurame yo coua ete flowing length artypeciteme Bascaly afuncion easnort werd flowed code (erter he ext editor forth example’ bybradets For evar, ent, 0" ped ENTE 2» cauntelencnane) print (“Your surname has“, count, “letters in ay Press FS and save the coce bo execute Annaionaieedtawinlysvade verison — EEE penonsterottrtonsbutto too Suse) ° ‘depending on what the function is programmed Sua ‘many to get into in the limited space available here. toda, and returns the end value, The data being worked on goes However, to view the lst of bultin Functions avallable ta Python inside the brackets, soif ouwantedto know now manyletiers 3, navicate te hitps//docs.python,ora/3/library/Functions ml. are inthe word antdsestablshmentaranism then you'd enter These ae the pre-defined functions, but since usershave created Len(“antidisestablishrentarianisn”), andthe number28 many more, theyre not the only ones avalable. ‘would return, ED entamnliaionsion through modules Peroni ovasange ot modules avalible tac can cover numerous oroarammin tes, te tuse advanced Mathematics uncion ener import math once entered, youll have access toallthe Math madule function: FORGING FUNCTIONS There are many different Functions, created by other Python programme iene rennet STEP 1 ferry fier Hel toc) ] print Cet on} Fettoc) Press FSto save and cun the scrip. You'll see errr tae te pemeen eens eer) ete variable, See ee! ca eters Peete ceed lead Se 3 full stop, then the name using the math module, since we've ion, we can iis the square ot functio Toeos0, ent math. sart(16) Jef presented a¢ module Funetion(éata). which you can import and you'll undoubted Sree ee BR to modify Further, eae Covers fi Fron Hetto Inport Helo Fetloc Dovid) pee File (Fle> New ed tosayhel eee cial ) Python Foundations) Conditions and Loops Cee een ec neg eC ec cs complex. How you use them depends greatly on what the program is trying to achieve, PevonCe Mngt Cine uated esteem crn TRUE CONDITIONS Keeping conditions simple, to begin with, makes learning to program a more enjayable experience, Let's start then by checking if something is TRUE, then doing something else if it ist. Letsceaeanen honpogamtutnan te TRAE NowsseantanenntocieF ewe, Sie user to linput a ware, then check it to see iFit'sa SUG length variable is equal to Four, and princa friendly Fourier wordornot Sere wis Fl New Fl, snbegiith conformation Fleaples other the input variable word=input("Please enter a four-letter word: *) word=input(*Please enter a four-letter word: *) ‘word_lenc LenCword) Uf word. tength == 4: print (word, “is @ four-letter word. Well done.”) | ‘The double equal sign (==) check if something is equal to somethngate Novae arena er etheln ETRESIB then athe endo tleton ta th SUE function and pass the word variable through it to Sua ‘statement is true, do everything after the colon gettvetaalrumbes fee he seas eneree thasindeted, Nowe move theca aeetotrebeaning ot word=input(“Please enter a four-letter word: *) the Ector ord. LengtheLentnore) Ra RRETRRERTRCOT LOA ord lengtheLenGword hed ~ ‘if word_length Z eke res ed SLUTS GE RIWOEAMAL Sen eon ina Drink: words *is not a four-letter word") wear a ED ores oerin ie stele Seginnth, BMD erst cold become aatecomplon Weve shoudheetversuuned menacerhatre words fourletare _adeedacondionforteeseter ward ss FS again, andre‘un the program, bucthis ime, enter a letter word. The Shell wi dplay that it's not a Fourletter word word=input("Please enter a four-Letter word: *) word_lengtheLenCword) if word_length == 4 print (nord, “is a four-letter word, Well one.” elif word_length == 3: print (word, “is @ three-letter word. Try agein.”) else: print Gvord, is not o four-letter word.”) LOOPS Ee Oe ea ee eee eee ame block of code a number of times, usually with the support of a condition. STEP 1 Oe Oe ) Python Foundations ) Python Errors Tecate i ana Cente ence CUM te a Python will declare it’s not able to continue due to something being missed out, wrong or simply unknown. Being able to identify these errors makes For a good programmer. DEBUGGING Errors in code are called bug, they're perfectly normal and can aften be easily rectified with litle patience. The important thing Is to keep looking, experimenting, and testing, Eventually your code will be bua free. FD core isnt.asttuidasthe writenword.nomatter — ERB thankfulyPython shelpful when it comesto ow geod the pragramming language i. Python is displaying eror messages. When you receve an certainly easier than most languages, ut even tis prone to some errorinredinkfrom the OLE Shell, twill define the eror isa annoying bugs. The mest common are tyb0s by the user and while alongwith the line number where the errr has occurred, While in «easy find in simple dazen-line code, imagine having todebug the IDLE Editor hssa litle daunting forotsaf code, text editors multithousand tine code help byineludinatine numbering ‘Ac weve mentioned, the mast cameron oferorsis ‘Syntax erorsare probablythe second most SUED thetyoo,ortonatthecommancteve mstyoing the aad corn eros youl came across as programmer. print command for example. However, cheyalzo occurwhen yau've Even Ifthe speling is correc, the actual command se Iswrong In gt numerous variables, all of which nave enathy names. The best Python 3 thisoften occurs when Python2 syntaxes are apie. The advices to simply go Uovough the code and checkyourspeling. most annoying ofthese the prin function. In Python 3, we use o prine(‘words", whereas Python2 uses print “words” (Python Errors ell PRED Pec brackets aroako acalpat of programming — EB) An excelent way to check yourcode stop-oystopic ‘errors, especially when you have something lke: tose Python Tutors Visualse web page, Found 3t in(bel anced _check¢in wa pvthontuter.com/isvalize.htmltmode=edit,Simaly paste ————s Your code nto the edtor and cick the Vsualse Execution button to runthe code line by-ine. Tishelpt0 cles bugs end any rmisunderstandings. Rememberenat for every'{ there must bean equalrumberof) There are thousands of online Python resources, Planning makes for good code. While alittle oid ‘code snippets and lengthy discussions across schools good habitto plan what your code will, Forums on how best to achieve something, While 99% oft isgaod da before siting downto typeI out, Uist thewarlables that willbe ade, don taloays be lured into copsing and pasting random used, along with the modules, end write out ascipt For any user cade nto your editor. More aften than na, wort work and Interaction or ourouts Frustrat ngly you wort have lesed anything ERED iidencsereatriky parcof Python programming — ENP purctyoutof interest, treword debugging in thata lot oF beainne'sfllfoul of. Recalthe If icon comoutina terms comes From Acmial Grace From the Conditions and Loops section, were te colon means Hoppe, wo, backi the 40s, as working On 2 monolithic Harvard everything indented folloning the satementisco be executed Markl elacromecharical computer According t legend, Hopper ‘slong a t's true? Missing the indent, orhaving too much ofan founda moth stuckin a relay, hus preventing the system from indent, will come back with n ereor working. Removal of the moth was hence called debugging, Pirin = ) Python Foundations) Combining What You Know So Far PSTN o i ea Re eto LEMOS looked at so far and apply it to writing a piece of code. This code can then be used to Recenter ts eRe as PLAYING WITH PI For this example, we're going to create a program that will calculate the value of Pi to set number of decimal places; as described by the user. It combines much of what we've learned, and alittle more. that can accurately coculae P without rendering the computer's (CPU useless For several minutes, The recommended caiculation Usedin such creumstancesis the Chucnovsky Aigorith, you ‘an find mare information about ®t gnswikipediaora/wiki CChudnovsky_ algorithm, We can wise the Chudhoesty Algorithm to create ‘ur own Python script based on the calculation, Well begin by Importing some important modules and Functions within tre modules From decinal import Decimal, getcontext ‘import math This uses the decimal and getcontext Functions From the decimal ‘adule, both of which dal with large decimal place nambars, and, faturally the math module Now wecen insert the i caluationalgortm RD crc coe Tiss aversoncrthe Chadha Alger ef catecn): £ = Decinol(o) i = Decinal@) fdeno = Deeimal(0) = k=0 mic for k in rongecn): £ = GoecinalayrorCnatn Factoriol (Decinal(6)*K))*C13591400454514013446) ‘eno = math. foctoricl(*k)*(aath. Factorial k)**Decimat(3))"C64032077(3°K)) pi += Decinalt)/Decina (aero) i= pi * Decinal(i2)/ Decimal 640320"*DecimalC.5)) pi = Upt return str¢ot) BME tistics FETED) 52 by opening Python and creating a New File in the Eitor. Ft, wernees to get hold of an equation Tha reousstep dfnesthe ules Ut make up STS bath the algorithm and creating the string that wll eventual dle the value of accordng tthe Chadnovsky brother sagorenn.Asyou Pave no cou avensysumisee swouldbe handy to aca output valve of tothe screen. Te ret at wana print¢catec1)) FERED) You can save anc execute the code at this point, youlike. Te output wil prin: the value of Pito27 ‘decimal paces: 3.141592653589734207668453591, Wile orety impressive on is ow, we want seme usa nteracion, ta ask the user as to how many places Pi should be calculated, FRED We canirsert-an inputline before the Picaloation| Def comnmand, it neta bean integer, a ew ctherwise default to a string. we can calitaumberofaigs,ané use the getcontext Function runberofdigits = intCinputC*please enter the runber of decimal place to calculate Pi to: “)) ‘getcontext().prec = nunberofdigits PED wecaneve nv, and tl ask the user tohow many decimal pices they wantto calculate Pi. and then output te result inthe DLE Sell. Try twith 1000 places, bt dont go too high or else your computer wl be lacked up fretting morofpenrmnmnole SIEag being able to modify code, mong more resend ets ancomert tia tines hw ion tates computer's leit ne" cea paces ond wesei tie fornataninedfree Caius Forthi cop ote conan ine tod pert the lerana module uses Seodyhovk sale pip install. colorana Tofrsncurcode, we necto nile be SES pram module, and then start the time function atthe pint wherstnecevaton sa een tines The the Termia or commande) from decimal import Decinal,, getcontext ‘import math import tine import colorama Fron colorana inport Fore colorana.init© runberofdigits = intCinputC*please enter the runber of decimal places to calculate Pi to: “)) gekcontext..prec = nunberofdiaits start_tine = tine.time() def catctn): Canning wha You now Far Gis (which will output text in different colours), ‘wth the Fore Function (which cctates the foreground nk, colour ane the ume module to start a virtual stopwatch to see how long Now we need to import the colorama module import time ‘mort colorana From colerama inport Fore t= Decima1¢ey pi = Decimal (0) deno = Decimal (@) k=0 for ke in range(n): t = (Decinal(-1)*4k)*Crath, Factorial (Decimal (6)*k))*(13591409 545140134") ‘dena = nath. factorial G*k)*(rath. Factortal(k)**Decinal(3))*(640320"*(34D) pL 4= DecinalCt)/Decinal (deno) pi = pl ™ Decimal (izy/ Decimal (640320**Decinal (2.5) pi = Vp return strcpid printccatecay) print(Fore.RED + “\nTime taken: start_tine) tine tineg) = 5 Wan ACR | Data : — , es P "1 J , oe r Pree a ty ®, gold or oil, and with it, you can elect | 3 oy CU or Ue 7 a eres tg et ed PY Cees ue ely d CN a - Py Crore ie at te J Peete < 7 Riera uN arc NTC) a + | Pe Python's ability to cope with data - . “4 and how it can be organised in your Seem ere ris - created and how to read and write CO ee a Seung” rv Cs S, ea es Cee eee ees , r | ea eens Le Meme ena oe oi o EC ee meray eee ae => Manipulating Data Lists Pee OMe Reet NM Ro eer Python. A listis simply a collection of items, or data if you prefer, which can be accessed asa whole, or individually if wanted. WORKING WITH LISTS Lists are extremely handy in Python. A list can be strings, integers, and also variables. You can even include Functions in lists, and lists within lists. Alatisa sequence of data values lleitems. You BALD scene name oF ours folowedby an equal sl. then square brackets andthe ems enarate by comms ne that strngs use quotes: runbers = [1, 4, 7, 21, 98, 156] ythicat_crectures’~ [“Unicom", “Batrog", “Varpire®, “Dragon, “Minoteur"} = ‘Youcan aio acces, or index. the attr inal SD 29 ne mirssign oor the Rem number), 0F the second ster uth 2, ane 390, Ting to reference an item that satin the st suchas [10] wi retum an erro urbers[-2] nythical_creaturest-4] B= (nce you've deiner youcancllesch by SUare ‘roferencing its name Followed by a number. Lists searthefis: ie enty2e0,folowe by 1, 23,390 390n Forename: runbers Tocallup he enti contents the st. rumbers[3] Tocalltheemthd fom zero intel (21 inthis) Sein sitar to indexing, ut you can renee Sua multiple items in a list by separating item numbers witha coon Forexanple: ‘nurbers[1:3] ‘il. output 4 ane 7, those being tem numbers 1 3nd. Note that the returned values don'tinlude the second index postion (as you would numbers[t3] ta retun 4, 7 and 21). You can update seme within an existing list, remove tems, and evenjoin ts together. Far example, to Joln two lists we can us! everything = numbers + mythical creatures Thenview the combined lst with everything PPD) vers canbe added toa lst by entering rumbersanunbors+[201] Or Ferstings saythical_creatresenythical_creaturess [*Griffin”] Cc by using the appenc! function: saythical_creatures.append(“Nessie”) runber's.append(278) Removal of items canbe doneln two ways, The Fist STEP 7 isbythe Remnumber: el nunberst7] The second, by item name: ythical_creatures.renove(‘Nessie”) ‘You can view wat canbe done withlists by entering SEND irflisc} Into the Shell. The output is the avaliable Functions, for example, insert and 0p are used to add, and remove, items at certain postions rurbers.insert(4, 62) Inserts the number 62a item index 4. Ar runbers .pop(4) wiitremoveit ‘You also use the list Function to breaka sng down Into ts components For example: Breaks the name David into'0 toa new ist: “Thiscan then be passed nane=list (David Haynard™) age-[44) user = none + age ‘Based on that, we can create» program to store Bar Someone's namne and age as alist: one=inputC*What’s your mane? ") Iname=List(name) ‘age=intCinput(*How old are you: “)) ‘lage=Loce) user = Inane + Lage ‘The combined naryeand age lst fs called user, which canbe called byentering serinto the Shel Experiment ard see what you can do, ) Manipulating Data Tuples Tuples are virtually identical to lists, however, where lists can be updated, delete Canes oa Chen aren ue Citmy perfect For storing fixed data items THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the program is intended to do. Mostly a tuple ic reserved for something special, but they're also used, as an example, in an adventure game where non-playing character names ae stored. ‘Atuple is created the same way ase list, butin this Instance you use curved brackets instead of square brackets For example: “February”, “March”, “April”, sront “May”, snonths Tree ax You can create grouped tuples into lists that contain ‘multiple sets of data For instance, herewe have a tuple called NBC (Nor-Payable Characters) containing the character name a their combat rating Foran adventure game NPC=[C*Conan”, 100), C*BeLit”, 82), “Valerio”, 95] ‘Aswith its, the items within anamed tuple can be Indexed according tothe postion inthe data ange: months [0] ‘sonths(5] ‘and s0.en, However, any attemptat deleting, oradéing, tothe tuple vill result in an error in the Shel aes fac ofthese ditaiterncante cee sa whole Sues by entering NPC into the Shell, ar they can be indved acer ore ston NP] vou ca 20 neste ingudaluleswahinthe NPC ecto] ta il display 100, a SR es orcining hat when efrenrng mile SUPE) ‘tuples within alist, the Indexing is slightly different fromehenern You woud eoestehe¥5 combat an othe CharctevleiatoDeNPC[aS] however tant Realy NeczacA SPR os inpicctrotpie mora SUEPE corresponding variables: Coane conbat-ratng)-NPC ‘Youcannow check he wlus by raring ame and comb ting, @ aa a0 2 a4 20 1 za 1,0 This as youcan imagine gets tie confusing when you have alot coftupe datato deal with, ESTED Turies though, utlse a feature called unpacking, ier the date items stored within a tuple are ‘assigned variables. Fst create the tuple with Go em (rame an combatting: NpcaC*Conan”, 100) Remember, as with lits, you an also index tuples using nageLve numbers, which count backwards From the endof the daa list. So, Fer our exampie, using the tuple with multiple dataitems, we woul reference the Valera character with NPctzI-0) BREED Wve con use the maxand min functions to Find the highest an¢ lowest values of a tuple composed of numbers. For example runbers=([email protected], 23, 45.2, 109.3, 6.1, 56.7, 99) The purnbers canbe integers ad fasts. To output the highest and lowest ase print(maxCnunbers)) print(win(nunbers)> => Manipulating Data) Dictionaries ee Mn ee eta EC ac ec een Or Mac euee, tea peculiar meer a et esi you'llsoon be able to apply them to your own code. KEY PAIRS A dictionary’ alist, but instead each data item comes as a pair, these are known as Key and Value. The Key part must be Unique and can either be a number or string, but the Value can be any data item you lke, PRED bers say you wanttocreate a phonebookin Python, PRIMM Ac wih lists and tuples you can check the contents ‘You would ceate the dicionary name, anc contain the data in cuty brackets, separating the key and value byacolon| oF ahctionary by cling the dictionary name Key:Value. For example: phonebook. inthis example. This wil dsalayche data items you've entered ine sila fashion tosis, which you're ne doubt familar phonebook={*Enna”: 1234, “Daniel”: 3456, “Hannch?; th Py now 6789} & Be PSTISED) %rth most ists, tuples and soon, strings need Thebenetof wing a dona stat you to be enclosed in quotes (single or double), while ous integers canbe ef open Remember tt evaue canbeethers ‘an enter tie key tondex the value. Usa the phonebook example from the previous steps, we can enter: string, ran integer, you ust need to enclose the relevant one erent nave ‘phonebook “Hannah phonebook2={"David": "@987 654 321"} raceme a «x Q value lems as such Phonebook[*David"] Phonebook ‘adding toa dctionary easy too, Youcan include ‘anew data item ent'y by adding the new key and "0987 654 321” rise ca And you can also remove items froma dictionary by ising the det command Fellowed by the Itemskoy~the value wil also be removed as wal since boty ‘warkasa par of dataitems ‘del phonebook("David”) PRT T2kinathisa step Further how about creating a piece of code that wil ask the ser forthe dictionary key and value kems? Create a new Esitr instance, and start by cating ina new, Sank cetionary- Phonebook=t} w SID to, wereedtodeine te cerns ne suae variables, one for the person's name, the other for thel phone number Ge weep lesmplet ails enathy Pyton coe nonesinput(“Enter name: *) runber=intCinputC“Enter phone nunber: “)) BRED ote weve kept the number asan integer instead oF astring, eventhough the value can be both ‘an integer and a sting. Now we need to ad the user's inputted ‘arable to the newly created blank diconay, Using the same process asin Sep 5, we can enter: phonebook[nare] = number Bar - ERTESETB 801 when we save and execute the code, Python willaskFor a name end arumbe.twllthen insert those entries into the ponebook dictionary, which we cantest by entering ito the Shel phonebook honebook[*“David"™] IF the number needs to contain spaces youlneedto makeit 2 string, soremove the int part ofthe input Splitting and Joining Strings eee Tur Cun sce ae eer RCO sc come across long sets of strings. A useful skill to learn, in Python programming, is being able to split those long strings For better readability. STRING THEORIES We've already looked at some lst Functions, using insert, remove, and pop, but there are also functions that can be applied tostrings. ‘The main tool in the string Function arsenal is split). BIE" ‘with it, you're able to split apart a string of data, besed onthe argument win the rats or exams, here'sa string thre ems each separate by aspace ‘text-"Deniel Hannah Erma” PE Nove lot's turn the sting intoa lst, and split the content aceon romes=text. split" *) ‘And enterthe name ofthe new st, names, ta see the three tems. Be : BREED Fete vatehetoxt soit part contains the brackets, quotes, then aspaceFolawed by closing quate: ‘and brackets, The space ithe separate, indicating that each list item entry s separated bya space, Lkewise, CSV (Comma Separated Value) content has a com, so we would use: ‘text="Januory February March April May, Jun rmonthsmtext.split¢*,") BIB i. previous seen having some we can Sua splita string into individual letters as alist: aneetist¢“Davie) ane The returedvaluels‘D, 2 V7, whlle|tmay seem alicte useless under ordinary circumstances, cauld be hand for creating aspeling ge, for example Bre - ( Splitting and Joining Strings Ea BRPED treconverse ofthe ) Manipulating Data) Formatting Strings As you work with data, creating lists, dictionaries, and objects you'll often want to print Ciel a ern ec eek Cees eee Meena one cutee ken ect ursccied STRING FORMATTING Since Python 3, string Formatting has become a much neater process, using the format function combined with curly brackets ‘This makes things easier to Follow and, as with most coding, there are other ways to do things but this way is recommended. FATED The besicFormatting in Pythons to call each TERED Wear of course, also include integersinto the mis: veriable nto the string using the curly brackets utah rnane="Conan” print(*{} of O wos a skilled mercenary, rin€("The barbarian hero of the Hyboricn Age is: and thief too. He once stole {} gold fram a 0" -formatCname)) formatCname, place, nunber)) EELED rece cccetesrtteconwitvosee EERE tereve mo atows vn tose sng crtravets youve enced e arable none, rarmating some ste espe arweve shown andthe rntfuncion narater Youran ncude mutiplecssesof yu her, nd ators can began more complex Ell Zeng formatting nv satpro ‘Sependsan vio ou war Fam our roam. pod porto teerence ecuetyrearcnesttna ornate, ste Phen Deas webpage Found Seingiemt re you atonsorheh rrane="Conan” place="Cimeria” print("{} hailed from the North, in @ cold Land known as {".formatCnane, place)) (. Formatting Strings Ea BRED eecestingly, youcan seference alt using the string Formatting Function, You neee to place an asterisk in front ofthe ist name: runbers-1, 3, 45, 567545, 3425346345, print "Sone rurbers: 2,0 0 Os 0". Format numbers) ESTEE) Yo. can print out the content ofa use’ input inthe same fashion one=input(*What’s your mane? ") print(*Hello {}.".FormatCname) FED ith indesing in lsts the same anpies tolling 2 lst using string formatting, We can index each ter according tas position (ram 0 however many are present) nunbers=1, 4, 7, 9 print(More furbers: {3}, 0}, (23, {1).”. format(*nunbers)), ESTES) 26 2sy0u probably suspect, you can mix strings and integers ina singe listto be cae inthe Format function characterse[*Conan”, “Belit”, "Valeria, 19, 27, 20) print (*{0} is {3} years old. Whereas {1} is {4} years old,”.formatC*characters)) PD rc yeu can extend this simple code example to display te Fist letter in a person's entered name. nane=input(*ihat’s your mane?) print(Hello (}.”. format (name)) Thane=List(nome) print(The first Letter of your name is a {0} Format *Iname}) ESTER Youcsnals call usona palo sts, and reference them individually within the same print function Looking backat the code Fram Step 7, we can alter eth: rones=[*Conan”, “Belit”, “Valerio” ‘oges=[25, 21, 22) eating twa lists. Now we can call each st, and iniviual items print '{0[@]} is {1[0]} years old. Whereas {0[1]} is {1011} years old.”.formatCnanes, ages) ) Manipulating Data) Date and Time When working with data it’s often handy to have access to the time. For example, you may Tenn eu eR red ae eg eet eee os Peace MUCR a eee Tn euch cet coa tol Marta TIME LORDS “The Time module contains Functions that help you retrieve the current system time, read the date From strings, Format the time and date, and much more. BRED Fs: you need timpot the Time module. sone ‘oucansee the stucue of how ies presented Sua" ‘that's built-in to Python 3,50 you shouldn't need to- SUGPS byentering ropintoa conmandpromptand pp insalit.OnceitSIMPOEG. sng. 19cat. time) ‘we can callthe curent time and date with a simple cortmand: import time ‘The outputisdsplayedassuch: “time.structtimeCem io yeara2019, tm_nona9, tm_ndaye7, tmhourad,, 7 ‘tmunin=6, tmsec=13, tmnday=3, tmydoy=250, tm Daemon =a x) isdst=0)?; obviously dependenton your current time, 2 opposed pene mae ing ge mene tothe time thisbook was written eunetinaonssititorinencies nese TRAP theres umeoistieors tutta the SUare Givided up into indexed items, as with any ather sua ‘Time module. One of the mast common of these tuple andshown nthe secon ot bel t-te. thi youre abet presents wie range of arguments secon the time tule ito ating. For earls, tocolay he caren day ote week we ane Inger ie ‘time. steFtime A) 2 ayotyene 31036 oan omy BE xottronicionsccn Naturaly this means yu can corporate various USED Frcscrsins your oun code, sschos ‘tine. strftimeC*a") ‘ime. strfeimeC%2") tine strFtime(¥") ime. strftimeC*SH") time. strFtimeC"siR) Note the last two entries, with 96H and HM, as youcan see, these are the hours and minutes and as the lst enty indicates, entering them as Ss does display the time corecly inthe Shell. we cn easly rectify this with time. strftimeC sa: 3") BITES Thismeans youre going tobe able to deplayether thecurent ime,orthetime when something cccured such asa user entering tei rame. Tris cade inthe Eater import time nane=input(“Enter Login mane: “) printc'Welcore”, name, “\d") print("User:”, nane, “Logged in at”, time. strftime(“SH:9")) Try te extendit further ta include day, month, year, and soon ( Date and Time Ea BREED We can ako use the Time module te cisplay the amount cf time taken Foran event to happen, For ‘example takin the above code, we can ater sihtly by inl start time-time, timeC) and endtimentine.time()-start_time ERE Te output willooksimitarto the screenshot below. ‘The umer Function needs tobe ether side of the input statement, as that's when the variable name is being created ‘depending on how long the user took io in. The length of time is then clspayedon te last line ofthe code as the endtime vail. BRTESE TB Theresa locthat can be done with he time module, some of itis quite complestoo=such ‘as deplaying tre number of seconds ince January 1st 1970. F you ‘wane to dl dow further nto the Time module, then in the Soe center helpCtime) to spay the current Python version help ile For the Time module, => Manipulating Data Opening Files In Python, you can read text and binary files in your programs. This enables you to Tosco ete em Rae miei Nee tt TR Ree eee ae uke sca hd eure ee etic an OPEN, READ AND WRITE In Python, you create a file object, si «to creating a variable, only you pass inthe File using the open( Fun Files are sally categorised as text or binary. STEED ory rtring snetertinte your sytons Siar text editor. The text editor is preferable to a word proceton a vordprocesos ince baceround eaten snd ‘ter elerents. nour exam, we have te per The rma, byRbert = Howard and weve aed te le: poembxt You wee pend farcontopastheFieintoa Sure variable as an abject. You can name the File object anything you tke, But youwilneed to tell Python the name and locaton of thetentfileyou'te opening: ‘poen=openC*C:\\Users\\davich\\Docunents\\poem. txt") ‘The reason forthe double sash) is because Python wilread this 385 Unicode Ero, thinking you'ee entered: \U Tisis Windows-only, SEM jou row enter poemintathe Sel youl et UGS ‘some information regarding the text file you've just eles tobe coened we can neu ute poemvarale2o esd he ‘ontenso teie poem. read) Note than a fm entyyin the text represents a newline, as we have used previoush. we a Wyoverter pormsesd a second tie, ou il Sua notice that the text has been removed from the fle. You wilneed to enter poemmopen(“C:\\Users\\david\\ Documents\\poem, txt”) againto recreate the ile. This time, however, enter: print(poen. read()) Nn the mn enries are remaved in favour of newlines and Linux and Mac wont have Eis sue readable text, a a Drasen Forexamle poem. reedcs) As with ts, tuples, canaries and soon, youre able te index inddual characers ofthe text, Displays the Fst ive characters, while entering poem.recd¢s) Vill display the next Five. Entering (1) wl display one character at atime, Similar, you can dsplay one tne of textat atime by SIPC ‘using the readline() Function. For example: poerropent*C:\\Users\\davi d\ \Documents\\poem. txt") poen.readlineC) Wil display the First ne ofthe tet. An oer. readlineC) Vall display the next line of text. aE AD 5 you may suspect, you can pass the readtineQ) Function into avaiable, allowing you to calli 292i, when needed poermopen(*C:\\Userss\\david\ \Documents\\poem. ext") Linespoem.readLine() Line ~ Opening Files Ea SPP scouting terrier yu can sso rene) to suave grab all the lines of the text and store them as muttipe lst, These can then be stored as a varable: ppoen-openC*C:\\User's\\davie\\ocunerts\\poen. Ext") Lines=poen.readlines() Lines(2] Tines{1) lines(2] PTE) Wiccan also use the for statement to ead the ines of tax back tous for Lines in lines: printClines) And, since this Python thereare other ways to produce the ‘ame output ppoemopenC*C:\\Users\\davia\\Docunents\\poen. txt") for Vines in poen: print(lines) ESTER: simagine that you wanted to prin he ext a character at atime, as would an old dot mati printer, We can use the Time module mined with what we've ooked there, Teythie import tine poen=openC*C:\\Users\\david\\Docunents\\poen. txt") Lines=poem.readC) for Vines in Vines: printClines, end="*) ‘time.sLeepC. 15) The outputs fun to view, and easly incorporated into your ovn code, ) Manipulating Data Writing to Files eeprom ca agaist nM nom sara Tee TiC Pease tains Pe eckson arse ed Meu renter tet hie tee aces Ceuta WRITE AND CLOSE ‘The writeQ function is slightly more complex than readi). Along with the Filename, you must also include an access mode that determines whether the file in question isin read or write mode. ‘topen"C:\\Users\\david\\Docurents\\text. txt”, “W") This code wil crate a text file, called textxt Inwrte mode, using the arable tf there's no file ofthat name in the locaton, wal ‘ceate one. Fone already ex ll overwrite itso be careful Start by opening IDLE andenterthe following {obviously entering your own username locaton: Baro However, the actual textile ssi blank You can ‘hack by opening it up) This sbecause youve ‘written the line oF text tothe Fle object, but not committed i tothe fle so Part ofthe wntel) function s that we need to commit be ‘cvanges tothe Fe, we can do this by entering: tecloseQ) Wecannow witetothetextfe wingthewtel SUare function. This works op posite ta read), writing lines Insteodof reading them Tryths ‘t.writeC*You avake in a small, square room. & single table stands to one side, there is a locked door in front oF you.) Note the 105, ts the number of characters you've entered W younowapunthetest fe witha text edtor you Sua see that the line you created has been written ta the fe Th ges vs Ee foundation for sone interesting posite, perhaps the creation of our ownlaa eo even the beainnggt snadentre gone To expanclthis code, we can reopen the ile using 3, For accessor append mode, Ths wll adé any text atthe end ofthe orginal line, instead of wiing te ile and cresting anew one. For example: ‘t-open(*/home/pi/Docunents/text. txt”, EwwriteC’\n") : You stand ond survey your surroundings. On top of the table is sone meat, and a cup of water Sn”) 2 ‘We can keep extending the text line by line, ending ech witha newline (V). When you're ane nish the code wit ¢claseQ, and open the ile na text editor to see the results t.writeC*The door is made of soLid oak with iron strips. It’s bolted from the outside, locking you in, You are a prisoner!.\n") #.claseQ) ERTS There are various types of fle access to consider using the opend function. Each depends on how the Fieisaccessed, and even the poston ofthe cursor For example. r+ ‘opens. Fle in read and write, and placesthecursorat the sar of thefile ( writing to Files Ea \wecan pasvaralestoafethat weve created suave In Python, Perhaps we want the value of Pito be conttento are Wecan cal Fromthe'atmedle, eats Tie andpanstheaupitot Pinot fe incor ath print(“Walue of Pi is: “,math.pi) rinke-\iri¢ing 6 fle now.) a = Now let's reatea variable called pi, and assignitthe value of P vie alsoneed to createa new fle to write to: ‘teopenc*C:\\Users\\david\\Documents\\oi txt”, “W") Rememiberto change your file location to your wn particular system setup, Dewees come mareran te a EEER To frish, we con usestring Formatting tocallthe variable and wrtet to the il, shen commit the ‘changes and dose tefile ‘tewrite*Value of Pi i rcloseC) [Asyou can see From the results, you're able to pass ary variable ta afie 0° Formatcpid) ) Manipulating Data) Exceptions Peer on cet Gen erence Cree onal comes eter hie two numbers, and they try to divide by zero. This will create an error, and break your code. EXCEPTIONAL OBJECTS Rather than stop the low oF your cade, Python includes exce «can combat errors by creating conditions where exceptions may occur, objects, which handle unexpected errors in the code. We You can create an exception evror by simaly tying Siar! to divide a number by zero. This will report back ‘with che ZeroDivsiontrror: Division by zero message, as seen in the screenshot. The ZeoDisionEror part isthe exception cass, of wich thece are mary. (Gascon ae Bee “ones ‘automatically when Python ‘comes across something that’s inherendy wrong withthe code However, we can create our own ‘exceptions that ae designed to ‘contain the potential error and Feacttot, as opposed toletting the code al. FTTREDD Wiccan use the Functions raise exceptiontocreate ur ov esrar handing cade within Python. Ler’s ‘assume your code has you warping around the cosmos, toa much however, results ina wero core breach, To toa the game from cexting duet the warp care going supernova, we can ceate s ‘stom exception raise Exception(*warp core breach") ofttry, excep, else, where the code held within ty, then there’ ‘anexception de something, or do something alse. To trap any errors inthe code we can encase the potential errarwithin a try block. Ths block consists a For example using the dive by ze ear, we can create an exception where the code canhandle the errorwithoutPython gitina due tothe problem: ty: ‘rintCinput(“Enter the first number: "D) bbeintCinput(“Enter the second number: ")) printCa/b) except ZeroDivisionError print¢*You have tried to divide by zero!) else: printC*You didn’t divide by zero, Well done!) rr FRTESTD You can use exceptions tohanale a variety of useful tasks. Using an exemple from our previous tutorials, lets assume you want to open afileand write to trys ‘txt = openc"C: \Nusers\\david\ Documents \\textfile ext”, tr") ‘txt mriteC*This is @ test. Normal service will shortly resume!) except T0Errer: print (*Error: unable to write the file. Check permissions”) else: print (“Content written to file successfully. Have @ nice day.") ‘txt. closeQ) ‘Obviously this won't work due to the file textfle.ext being opened a read only the part. So inthis, case, rather than Python telling us we're doing something wrong we've created an exception, using the 1OError las, informing che User that the permissions ae incorrect Nataly, we can qui ic the se by hanging sae the “r” read only instance with 3 "w" For write. This, a youateadyhnon irate the le andthe corterhen ‘omni the changestothefile. The end resul- wil report adifFerent set of circumstances, inthis case, a successful execution of the code, PED) You can also use Finally: block which works ine similar fashion, but you cannct use else wth i Hit: ‘Yul need to delete the texte tat le rem your Felder. try: ‘txt = open C-\\Users\\david\\Documents\\textfle. ext”, tr") try ‘txt nriteC*This is @ test. Normal service will shortly resunel”) feally: print C*Content written to file successfully. Have a nice day.") txt closeQ except T0Error print (“Error: unable to write the file. Check permissions”) ESEEED *seFore an errorwill occur as we've used the read-only permission, Fave change‘ toa"w" then the code will execute without the error being deplayedin te IDLE ‘Shell Needless to say, it can bea trcky geting the exception cove Fight te fist ime. Practise, though, and you wil yt Une hang of as => Manipulating Data) Python Graphics PC iene eee eee nee ec aie Been ae eg ie te sesamiae naa Ce) has numerous ways in which to include graphics, and they're surprisingly powerful too. GOING GRAPHICAL ‘You can draw simple graphics, lines, squares and s0 on, or you can use one ofthe many Python modules available to bring out some spectacular effects. ‘One ofthe bes graphical modules to begin earning SUBPL Python graphics is Turtle. The Turtle modules, as the name suggest, based on che turtle robots ued mary schools that ean be programed to cra somethingon a large pee of paper onthe floor. The Tule modilecen be imported wth importeurte ro Ee The command ule cil) iswhatcrawste SIGS drcle on the screen, with 50 being the size. You can play round ts he 2s F36U ke, ging vO 100, 180 and beyond: you can draw an arc by entering turtle. circle(s®, 180) where the sze 5, bu you eteling Python to oni ser ofthecrcle Let's begin by drawing a simple cre. Start aNew SURE File, then enter the Following code: import turtle turtle.circtecse) ‘turtle -getscreen()._root.mainLoop() ‘Asusual press FStosave the cade and execute This ull open una ew wincow and the Turtle’ wil daw 2 cle. Theat ptf the cil coe tle thon to keep Sua the window where the drawing istaking place to reminapencotheusereanchcocose t Naw lees make :0un import turtle printcDraving @ square.” for t in ronge¢a): turtle. formard(100) turtle, left@a) ‘turtle.getscreen¢)._roat mai nloop() ‘You'l notice we've inserted a loop to draw thesides oF te square To add some colour we canaédanewlineto tre turtle .colorC*Red”) ‘And we can even change the charscrerte an acral turtle by ent ing turtle.shapeC“turtle”) \ecan also use the command turtle begin fill), and turtle-end_ Fillo eo Flin the square with the chosen colours; in this ase, ed eotline, ad yellow il From turtle import * color¢‘red’, *yellow") begin A110 while Trus Forward(2ea) LeFt(170) if absCpos@) «< 1: break end ALLO cone Wesadfferent method, but very effective, * ESTES ether way you can dsplay graphics iby using the Pyaame module, There are numerous ways in vic pygame can help you outaut graphics tothe screen, but For row let's look at spaying 3 pre-defined image Start by opening 3 browser and finding an image, then savet tothe folder where you save your Python code, e S—: Ea SS Python Graphics Ci” RPE Now es ge the code by importing the gygamne mde: ‘import pygane pygame init ‘ing = pygeme mage loadl(*RPA png”) white = (255, 255, 255) w= 900 = he 450 —— screen = pygane.display. ~ 7 setnodec(n, h)) : sereen.fiti((nhite)) screen. ft1Ccwhite)) screen. bLit ing, (0,09) ygane. display. ip) while True: for event. in pygane.event..getC iF event type = pygane. QUIT: pyoare.quitO BETTE DD the previous step we've imported pyaame, inated the pygame engine, and asked ito mnport ‘our saved Raspberry loge image, saved as RP png, Next, we {defined the background colour ofthe window to pas the image, {ane the window size as perthe actual mage dimension. Finale have alooptociose tne window, we9000 0 h = 450 screen = pygane-display.set_modec(w. h)) screen, Fill((nmite)) screen, pygane, while True: for event in pygane-event.get( if event.type == pygane.QUIT: pygame. quit) Fill((nhite)) blitcing, (0,09) display. Flip) BETTI 555 to save and execute the code, and your image will be displayed in anew window. Havea ay around vith the colours, sizes andso.on, anctake time to lok tp the many Funetions tin the Pygame medle 0, RaspberryPi => Manipulating Data) Combining What You Know So Far eee Reou URE piece of code that can easily be applied into a real-world situation; or at the very least, Pome Ran eRe urges rir aah eta ie ues EER RMA AOL Ad re eee a eae LOGGING IN For this example, let's look to apiece of code that will create user Logins then allow them to fog nto the system, and write the time at which they logged in, We can even include an option to quit the program by pressing‘. Lets begin by porting Le Te md, eating BIE" anew dictionary to handle the usernames and passwocts,andaretng a veable to esate te current ats of the program tmoort tine users = status =" Next we need to define some Functions, we can begin with creating the main menu, to were, after selecting the avalable options ll users wl return: ef mairMenuc) global status status = input(*Do you have @ Login account? yin? Or press q to quit.”) if status = “y": oldUser( elif statis = “nt: rneallsen() elif stotis quito BRED soba sats satern soprates alacal Sas) variable Fram one that can be called throughout Lhe code, ths way an aethe eau erent thot Deng ‘changeciinsie the function. Weve also referenced some newly ‘fined Functions oldser ancl newUser which wel get to next, ‘The newLse Function inex: Bee def newserO: createLogin = input (“Create @ login name: “) if createLogin in users: print C*\ntogin nane already exists!\n") else: CcreatePassw = input(“Create password: *) users[createLogin] = createPassw print(*\nUser created!\n") LoginssopenC*C:\\Users\\david\\Docunents\\ Vogins.txt*, "a"? Logins.writeC\n” + createLogin +" + createPasaw) Logins closec) ‘This creates new userand password, and writes the entries into a Fie called togins txt.

You might also like