Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
100%
(1)
100% found this document useful (1 vote)
589 views
197 pages
The Complete Python Manual (5th Edition) - April 2020
Python complete manual
Uploaded by
Mihai Margineanu
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
Download now
Download
Save The Complete Python Manual (5th Edition) - April 2... For Later
Download
Save
Save The Complete Python Manual (5th Edition) - April 2... For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
100%
(1)
100% found this document useful (1 vote)
589 views
197 pages
The Complete Python Manual (5th Edition) - April 2020
Python complete manual
Uploaded by
Mihai Margineanu
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
Download now
Download
Save The Complete Python Manual (5th Edition) - April 2... For Later
Carousel Previous
Carousel Next
Download
Save
Save The Complete Python Manual (5th Edition) - April 2... For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 197
Search
Fullscreen
rayialeleY, the Sens Inte & The: Complete Linux Manualement,65)}), !1}}( Ms ps recmeeel oo Bare teeny ent (a) || ( Brice Ce BCs OD east) (Ol Crm ere eres ate Dar (a, function(c,d){b. find( =) iG (terns »function(c,d){d=$(d);var £=d.prop("name"); ! (a,f)?d a [etc as SAM aeas = ti 7 Iters_Form_ container Selector) find(”.filter Aa eins FS a (b) - length; 0
ri L) i p oe History of Coding | (eee etd eC eee ater is amodern concept that's only really happened in the last fifty years or so. However, that assumption is quite wrong, coding has actually been around For quite some time. Cee RRR RRR RRR CONC RR CORLL ee eee eee ae i ear ee eat or 1842-1843 1930-1950 We stare of when humans ‘rogram’ adevice. How cepted that the Ce eee) Pei eee r at ene ard Doane sn ‘design on 3 previous automated weaving Ce tae eet scholars who worked in the House of Cees Ce eet Eee ee was. amechanical musica instrument: eee re ere ie te P anailable atthe timsoor oe meeed SC eauae uae See Ce ature) Sera rad Rien Cee freer een aera eg re ees Geers From the 1970s the development of thelikes oF SQL, Cwith Classes (C+), MATLAB, Common isp and more, came to the fore. The’80s was undoubtedly the golden age ofthe home compute atime when slicon processors were cheap enaugh for ‘ordinary Folkto buy. This led toa boom in home/bedroom coders with the rise of bit machines. 1951-1958 ‘The first tre computer code was, en aces Cee eee Seats Cea eras eis ed eee er team ees Computer programming ‘was mainly used by universities the military and big corporations during the ‘60s and the'70s. Anotable step toward amore userriendly, lorhome user, language wa the development oF BASIC (Beginners All-purpose Symbolic instruction Code) n the midsities. Si Sere ote ‘programming languages and allowed eee ua’ eet eon Peete rey Peer neingctid Peer ‘Admiral Grace Hopper was part of the team that developed the UNIVAC computer and she eventually ‘developed a compiler For tn time, the compiler she developed became ‘COBOL (Common Business oriented Language), computer language that's stillin use today. b coos nr ”Choosing a -Bper=ticn — Programming pret ens Language ¥ Tatnelenacciacer ica) ct _X = Fa See ee eT ere Ly aan a ee a single book ofthis size. New languages Ra Uren a Tr and ways in which to ‘talk’ toacomputer ©perat ee 2 = Fg or device and set it instructions are being aT invented almost daily; and with the mod MIRRC Pista Ten ttesn tnt ma nur Pes -Use_x = Fa eau auetes sen etl tunes __mod.use ae PPevieeatu ten Secu ay ut ee ee] ReMi ents od -use_z = Tr Pe) stmt Tras CTH eoie ae 7 Eee aes nate eer tes a peer ester eee eh cer) > (American National Standards institute) standard, there are different versions of Se ee ea ete eee as ones Reet a Seine aan eV c<:1 reenter beter oe coe ee functions javascript runs onthe clint side ofthe web that canbe used to desion see eye etre ees beemer renee ine wr met eee reiss ea cone eso rr areca ret based content games and mobile apps. the two main componentsof java platform are application programming interface virtual leite ett eters citisan elegant object-oriented languagetthat enables developersto bull variety of secure rabust applications run on net framework. you can use ch create windows client xml peet ree tetas etege tire mete racer es one ay python isa widely high level language ten ese ence philosophy emphasises code readablity anda syntax thet allows programmers te a een sora ccr cee pus plus general purpose ete rea features. was designed with bias toward system embedded resoutce-constrained large systems performance efficiency flexibly ser ris perce ens peete ae crt ei ns er eet essential parts ruby be removed or redefined at will existing porate et ed range tasks including administration development network gul more. its major features perro ier trees per ans teen mnt ene ieee eens neers rte eer ua maurice came eae ere cnr pee cree world creating coding hardware thankful atthe foundation doesnt require specast equipment for atop quid hydrogen-ooled pc. ifyou computer no matte how basi begin learn naturally if in question is commodore then mey have some difficulty folowing modern tutorial but best around today started an bk machine so there hope yet tothe internets necessary downoad install update environment alongside ether: macos linux installed canuse ather operating bu these big three wil find most resources writen ane orall ofthese ning ean erreurs penner pe iene ies rena eg tents ce ent been inc sent sey co carrer software interms softuare nostofthe environments-thetools thatalowyoutocode comple executet-are freely valableto download instal specalt ols aoisble cost athis evel theyre not purchase any extra inorder tart earring howto youray yoursel changing fram mainstream envionment using collection your ow lscovered ool write rs all personal preference nthe end as become more experienced start touse different tools get thejob done. envecnments enhance sections making teaser read others wl allow quickcompiling exection. e alla matter testing experience cl wort soit natural vast majortyof microsoft leading however dant eiscount especial linux. users enjoy equal number their counterparts. infact probably lot professional coders mac over apc simply because fact ystems built top unix commandline os powers much word filesystems servers this ayer lets test programs. almost without specialised ide. isby far popular important avaiable. only sdoesit aunictke backbone als it aso free comes mast learning make upthe internet. i nearly supercomputers aswell specicaly organisations such naga cern military itforms base android-powered devices smart tvs in-car asa isan excellent idea andit inside ever affecting installation ar maco8. raspberry pi ifyouhavert already heard we suggest head wwm.raspberrypi.org checkitaut.inshor piisasmlt fly functional own customised linuchased pre-installed everything need stat c scratch anc cheap costing andalowsyou utlse ferent inthe ferm rbotis electronics projects wll offering complete desktop experience. atbough powerful computing device pihasa going fri especialy termsof being platforms method choose remember change gan favour aver another. dont afraid ta experiment along way youwill eventually unique handle allthe enter intoit. machines avitual piece thetallowsyoutoinstalla fully wrkng within confines itself nstaled alacate user-defined fromthe host providing memory hard rive space etc wells sharin hos commuters inert connection. advantage youcan werk linu example ieaffectingyourcsertly inetaled hott os. means running aunch vital dent bot into unuxand hie able wind. ofcourse makes fantastic instalations systemsrunning from wile languages. yau fear af breaking hast easy retuin toa previous configuration reed reinstall again virtualisation isthe key companies now. rather than having single server ith instalation t team instead opted fora virtualised whereby each instance ie vitual several machines. cuts down physical better manage fecoutces enabes them deploy entire decicated particular askin fraction ofthetime. minix neo n42c-4 neona2c4isan extraordinary small minipc developer mind measuring just ths ntl n4200 cpu. powered propreinstalled computers come across. beauty lesinthe fac. inceasedstorage avlable acomputerthatcan easly mutiplevitwal vitualmachinescan cover android other stems alowing towte oss damacing causing problems production home compute. mink starts emmic memary.yaul add another hundeed fifty increase specifications consider license ro alone costs store becin benefits cf opting amore impressive ver likes p. oe: print app desktop. multiple safe isolated environment. short ideal code. sounds good what exactly does work offical dentin ofa vtual efficent duplicate real basically emulated operatein exacty same dedicated operator o hypervisor. hypervisor youto installs separate sytem vithinitself acess intemet hypervsor take part computers: cpu dive shared set asie fr therefore wont avaliable until has closed resource overhead crippling forthe fyou enough available particularly slow processor. while entirely possible ona tle snot advisable. ideally heed aminimum away willbegin sufer theloss memoryto least drive quad core processor adualcore cp cause bottleneck ur linuctitles contain steps installa inypervisor limit tohow many pysical restricted by amount tesources cn allocate stil leaving operate on. abe host. numberof diferent type depends greatly emulating patticular others. virtualbox afiee f23y oracle great vitwal ist s0 macos. arm processors bucitcan dfficl master. plenty hypervsorsavallableto try commercally tat significantly owesful offer both beginner ob. setup newer distributions orif feel also tonstall antiquated versions. ary versions even back dos although may ind functionality vm lost due older drivers access mindthen min atest version ubuntu machine. conversely linuxas ts ahypervsor licence resister activate itual removes duatboct duat-booting ishaving systemsinstalled drves onasingle computer. compute up given option which want boot ike scenario irisn always straightforward asall booted ful acces resources. dual booting when systemsis updated updates security patching bug fixing alter kernel changes applied ater n hich che meaning inital baot choice coud overwritten ability rectify oul ned master record re-allow systems. danger possibly verwriting fstinstalled data often play well cunning side-byside indeed cal: share problems. contrast sil problematic times takes jut nasty disastrous aspects old cual mactine sine compen aryour advantages coder offers cross-platform cade. astro youre quickly effortlessty power acompletely thi yout iron out bugs teak works afferent expand reach non configure speiicways specc isqute invaluable. vrtual greadly reduces inherent languages ibraries ides modules support cifferent involved acoder. elements talk directy specifics ofan easily overcome clutter libraries turn affect ibrares element stability. wilting could potentially instability during phase executing sense ton where repeatedly reboot eset something cuetothecode instabiltes inefficent justplain annoying viewed aca sandbox unstable vathout harm doing damage working vues malware vthout infecting anonymity internet thir party slowing early stages seema lite excessive worth looking liuxcan easier some. vetsons hve preinstalled. either vituaisation show successful developers geting tot skillset advantageous tostart look tinstaling taking ourlinux tes https: typesproduet toinstal utlise z se nan neng com gece coniaiss funes oncattan cue ecient ect fears multiplatform those obviously program windaws xp onward a32 apple maco ide usedto execute inspect values advanced avalable gives results software. preinstalled ensure latest python. andinstall wel shorty text editor tex edtorisan enranment int absolute necessity idle atext eto sublime texto notepad colour entering evolving newversion introduce new concepts commands structureto efficient language. keep up-to-date help stuck give pythor modules. time patience despite books lead believe won programmer patience. maybecome lw tke water understand ently there. pisa tiny very user platform. raspbian extras. raspberty model incorporating wi bluetooth pickup pt increasing upto pat kt depending kityou interested in. fuze project bul pi. workstations me abot program. mere information wwwfuze.couk ptiles avaiable via wow. our pibooks buy fist setitupand step bystep projec examples guidesto p debian-based linuxalstribution simple package. streamlined pland backup pictures through analysing petabytes data. biggest easiest learn. chapter upon remarkable do ting know why dee alias um sce aku eo eeu maem ms uctda deat preece ek cement en melee aro cece wa reece id preartiase nics since earliest were enthusiasts professionals toiled avay wee hours slaving overheating heap circuitry akin magic. pioneers carved thelr frontier forging routines enabled letter scroll screen. sound terribly exciting generation ultrahigh definition graphics open werld muli- player online gaming fortysomething years agoit binginaly bilan. bedroom helped form foundations digital technology today. went onto became chief sofware whereas pushed tots limits founded billion pound empire continually mazes s. regardless whether deve ios pc lnux tv ames console mp3 layer gps builtin car settop box athousand connected appliances behind allis aforementioned digtal instructions tell todo alow tobe interacted butt differ situation wilinteract stleurger>= 0) Pefresinortcursor): certTachataoneracend) ‘einen Deine SE eeetieet: iC reste eet ftor fe Steen re farina J poi arog scstontrocua wold scrayeerL:-paine(oras ¥) { ‘ibtats © catcount()) flee catnerl fibviton = Fitop ? cetLanecy(ids “header 3g { pe jen! Rave’ peratoston to ahd eat } EgechC xnvocacontargetexception e4 ) { Jian excapeion ocurred while invoking that inethod System. out,printIn¢ Sheehod thren an: " + e8 ‘gotTargetexeaption( *) y P Javaisa powerful language that’s used in web pages, set-top boxes, ‘Tvsandevencars. C Why Python? Cl Python was created over twenty si years ago and has evolved to became an ideal beainnerslanguage for earning how to programa computer's perfect forthe hobbyist enthusiast, student, teacher and those who simply ned ta create thelr on uniqueinteraction between either themselves ora piece of externat hardware and the computer isel. Python sree to downoad, install and use ands avalable for Linux, \Windows, macOS, MS-DOS, 05/2, 0, IBM iseries machines, and even RISC OS. thas been vated one ofthe top five programming languages in the world and continually evolving ahead ofthe hardware and Internet development curve. So to answer the question: why Pythor? Simply put, i's ree, easy to learn, exceptionally powerful, universaly accepted, effective and 2 superb learning and educational tool BASIC was once the starter language that early ‘sbithome computer users learned. Python sa more modem take on BASIC, i's easy to learn _and makes for an ideal beginners programming language. oe:Fy What can You Do with Python? Preece ceca cere enter ctintsciccl ee Ue MSR tod en Lee RNs ool Lea eeeeo cae tu cect enue giscaeti iol cas ee Ve Ce ae Ve i es Cee ee eas wy " ee ae ene eee ee mee ee eee feelings Tear re ones Line eh Cm te eee en eu ee ees Se te et arm Cee ee ee ‘need without having to cross multiple anauage barvers Python GO ee eed TaD A Eee eee eae seat pces Basically, t means extremely large datasets that are availabe or analysis to reveal pattems trends and interactions between humans, sodety and technology. OF course, oes eee eee enc ean ec ee ee ee ete Sores Python plays substantiate inthe word of big data. t's extensively used to Bee ence ee er ee ee et ee eee eee Geer ee ers inamongst the numbers that counts and presenting it ina fashion that's readable and Peern tee Ce ere ee ere eee etary Teer a cee ee preety pete rence tee meee en een eect Pe poeoboceeeorresoee ve uments tty evi uariree erie Siete Tear roe PTS Psionriotainnee een Leia merc en ionPU ae) a nee (e ebm cues ee ee ee eee term used foray computing process wherein the machine s oing something inteligent working and reacting in similar woys eee eer eects pen he crag ieee ere ee esd ete nr era acre m een ete eee reise eters the machin’, more accurately the code, need to learn ae une Ed Sa eee irs eet ren RL eee Instagram and then discovered that your searches within other ee co ert! similar celebrities? Thisisaprime example of using Alin ere ree eee acai Botte oat aas Seer) Seianitrdol ostream poser CO | Cees ts reece eae) ee naa parece eer iat y PVecy austen) m \Web development has moved on considerably since the early days of HTML scripting ina limited text ecitor, The many frameworks and web management services available now ‘means that building a page has become increasingly complex. \with Python the web developer has the ability to create dynamic and highly secure web apps, enabling interaction with ‘other web services and aps suchas instagram and Pinterest. Python als allows the collection of data from other websites. and even apps built within other websites. le & EL ith o/s m lay find too many triple rat y be surprised to lean that Python suse y ofthe ghar hon in gaming rea Python sot can 2c he sever cheating load balan matchmaking aches the canbe induded add PYTHON EVERYWHERE Coe en ree programming language. By learning Python, Pea le es ne ee ea Coe ete Biss Ce eee emcee Pi aneiie wneubinbicicnscanz= Welcome to Python There’sa lot to like about Python, but don't just take our word for it. Here are some amazing Facts and Figures surrounding one of-the most-popular programming languages of recent years. —_ oe Alexa, Amazon's Virtual Personal Assistant, uses Python tohelp with speech recognition. Oe Ne saaaWnNs ame oe DeceMnen PYTHON AND ety LINUX SKILLS ARE THE THIRD eeuaweene MOST POPULAR discused languaga on LT. SKILLS IN the Internet THE UK. & aaron (759% ) ‘OVER 75% OF 90% OF ALL RECOMMENDED FACEBOOK POSTS. ‘CONTENT FROM NETFLIX ‘ARE FILTERED IS GENERATED FROM ‘THROUGH PYTHON- MACHINE LEARNING ~ CODED MACHINE ‘CODED BY PYTHON. LEARNING. i Data analysis and Machine Learning are the two most used Python ‘examples, Disney Pixar uses Python inits Renderman software twoperate between other sraphics packages. an (75% \ ITS ESTIMATED ‘THAT OVER 75% OF NASA'S WORKFLOW ‘AUTOMATION SYSTEMS ON-BOARD ‘THELSS. USE PYTHON.16,000 “ass titttiti 6th: tt 4eriit 0 eeccccceccccccceces MOST SOUGHT-AFTER ‘There are over 16,000 Python jobs posted every six months in the UK. JOBS IN THE UK. % Python Data Science is Goosleisthetop Data Science, Blockchain New York and San thought to become the company for hiring Python and Machine Learning Francisco are the top most soughtaer job in developers closely are the fastest growing Python developer cities the coming years. followed by Microsoft. Python coding sil inthe wold Python developers enjoy an average salary of SS £60,000 %) (15%) (79%) (49%) \7 VY NS 95% OF ALL BEGINNER 175% OF ALL PYTHON 79% OF ALL 49% OF WINDOWS ‘CODERS START WITH. DEVELOPERS USE PROGRAMMERS 10 DEVELOPERS. [AND STILL USE, PYTHON 3, WHEREAS USE PYTHON USE PYTHON 3 PYTHON AS THEIR 25% STILL USE THE REGULARLY, 21% USE [AS THEIR MAIN PRIMARY OR OUTDATED PYTHON 2 ITASA SECONDARY PROGRAMMING ‘SECONDARY LANGUAGE. VERSION. LANGUAGE, LANGUAGE. oe:WHAT IS AVAXHOME?Se Pee Cen uLey De See Cac Ree cea Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction All languages Brand new content One site AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icuZz 2 ) Welcome to Python How to Set Up Python in Windows Wn ete Ie ec aria MNT una Ly Look Celd ore NN Moree choo ae 1) TUNEL Pee meee Mom Cea imcore Meee CU cece ef elt aie INSTALLING PYTHON 3.X Microsoft Windows doesn't come with Python preinstalled as standard, so you're going to have to install it yourself manually. ‘Thankfully san easy process to follow. ‘tart by opening your web rows to wanton Sued ‘org/downloads/. Look For the button detailing the ounloadink for bython 3. Python reglaty updated, changing telat dg fr each bugfix and update. Tertere doit wary Yousee Python 373, ormare along sits thon 3thecadeln th ook wore PSTD lick the download button for version 3x, and save the fle to your Download folder. When the Fleis dovinloaded, daublecckthe executable and the Python installation wizard wil launch, From here you have two choices Install Now and Customise installation, We recommene opting for the Customise instalation link, Install Python 3.7.0 (32-bit) @ fe Siarmncsrona a ED wwrnsdnputiationscom Chovsingthe Cite option alow you to OG ‘specify certain parameters, and whilst you may. sayoithte deat ts goadhab ta apt ometnes it wath oyton anu states can ude unwanted addons features Onthe it ceen aves, ese al ove are hed dodclek the New beton ~~ eo = a ESTED Te next page of options include some interesting additions to Python. Ensure the Associate fle with Python, Create Shortcuts, Add Python to Enviconment Variables, recompile Standard Library and instal for All Users options are ticked, These make using Python later much easier, lickinstall when you're ready to continue, J Aavanced Options Optional Features £ | ees | puth :You may need to confirm the installation withthe Bea indows authentication notification, Simply cick Yes and Python will begin instal. Once the installation is complete the final Python wizard page wl allow you to view he ates release rotes,and follow some onine tutorials. Setup was successful python windows = FID) cefore you close the instal wizard window however, it’s best to ik onthe link next tothe shield detailed Disable Path Length Limi. Ths wil allow Python ta bypass the Windows 260 character limitation, enabli execute Python programs stored in deep folders arranger ‘Again, lk Yes to authenticate the process then you can Close the installation window ose STEP 7 zoo ndows 10 users can now — Findthe installed Python 4 Diepmnars ‘sx wathin the Stare button Recently Added section ——— he first link, Python 3.7 : (62-bit wil aunen che command ine version of Python when clicked (more cnthat ina moment). To ‘open the IDLE, type IDLE into Windows tart “4 1 How to Set Up Python in Windows ESTEEM licking onthe OLE (Python 3.7 32-bit lnk wil launch the Python Shel, where youcan besin your Python programming journey, Datt wary your version is ewer as long ast’ Python 3.x ou code works inside you Python 3 interface. If you now click onthe Windows Start button again SUEPD and this time type: CMD, you'll be presented with the Command Prompt lnk, Click t ta get tothe Windows commandline environment. To enter Python within the command ine, you need totype: python and press Enter FREED the command ine version of Python works in ‘much the same way asthe Shell you opened in ep 8 note the three leftfacing arrows (22>).Whist t's perfectly Fine environment, ts not too user friendly, so leave the command line fornaw. Enter: exit to leave and close the Command Prompt windowWelcome to Python How to Set Up Python in Linux PYTHON PENGUIN Linuxis such a versatile operating system that it's often difficult to nail down just one-way of doing something, Different distributions go about installing software in different ways so For this particular tutorial we will stick to Linux Mint. otsouredtaacetanubicnvesiont thon TRIAS) Orcs ne upnte andupode competes tt Sued is currently installed in your Linux system. To begin Sue python3. ==version again to see if Python 3.xis vith, drop nto Terminal sessonfiom yourdstre'smen orhtthe update, or even nstaled. slong asyouave Python 3x youre Cutest keys. funnin the mes recent major version the numbers after he 3. inate patches plus urthe updates. ORen theyre unnecessary, SeiddBaNRES I) bac they can conainvtal new elements. Fle Edt View Search Terminal Help Next enter: python’ =-version inthe Terminal Sue ‘screen, You should have the output relating to version 2.x of Python inthe display. Most Linux distro come with both Python 2 and 3 by default, as there's plenty of code out there stil avalabe or Python 2. Now enter pythons ~=verssien. davidedavie-mint: ~ Fle Ect View Search Terminal Help . TA aE] However, ifyou want the latest, cutting edge ee iy ED ern souttncestobuid Pith rom source eae ”y Startby entering these commands into the Terminak ma! ‘sudo apt-get install build-essential checkinstall sudo apt-get install Libreadline-gplv2-dev 7 a 5 * Vibncursesn5-dev libssl-dev Libsqlite3-dev tk-dev FEED | our case we have bath Python 2 and installed, ‘Libgdbm-dev libc6-dev Libbz2-dev As long as Python 32xxisinstalled, then the cade in cur tutorials wilwork k's always worth checking to see f the distro has been updated with the lates versions, enter sudo apt-get update && sudo apt-get upgrade to updatethe syster rides tine ~‘pen up your Linux web browser and goto the SEE Python download page: https://www.python.org/ downloads Click onthe Dounioacs,Followee bythe button under the Python Saurce window. This opens a download dialogue box, choose a location, then sart the download proces, @ python ie bouton Inthe Termin got the Dowload older Gey byentering: ed DownLoads/. Then unzip the Contersof the domloneaythonsource code with at 2 python-37-¥-tarnz ence the swith the ves umes Youve dovnload, now ener the nev upped ole i tython 3.7 Within the Python Folder, enter: -/confgure Sudo nake altinstall his could take awhile, depending on the speed of your computer. Once finished, enter python3.7 -version to check the latest installed version. You now have Python 3.7 installed, alongside older Python 3xx and Python 2 Ae ( How to Set Up Python in Linux For the GUIDLE,you'need to enter the fallowing Suz) ‘command into the Terminal: sudo opt-get install iale3 ‘The IDLE can then be started with the command: ide Note ha IDLE runs a diferent version to the one you installed From source. “tnisedvitn-/DominasPyban 3.72 PERRET DD Youll asoneed PP Pp installs Packages), which is atoolto help you install moe modules and extras, Enter: sudo apt-get install python3-pip (nce PiPis installed, check Fr the atest update with pip3 install when compete, close the Terminal and Python 3.xwillbe avalable athe Programming section inyour disto's menu, upgrade pip Installation of Python on macOS can be dane in much the ‘same way a the Windows instalation. Simply go tothe Python ‘webpage, hover your mouse pointer over the Downloads Uinkand el Mac 05X From the options. You will hen be ‘uidecto the Python relesres For Mac versions long with the ‘necessary installers For macs 64-bit For OS X 10.9 and aterPr Python on the Pi Aue Cun uM ie cticmiane enero aNear nee thought to one of the best coding bases available: the Raspberry Pi. The Pi has many Teel els (a col teers) el een el ey cen Me Recto ge LACUNA odo) om THE POWER OF PI While having a Far more powerful coding platform on which to write and test your code is ideal, t's not often Feasible. Most of usare unable to jump into a several hundred-pound investment when we're starting off and this is where the Raspberry Pi can help out. PT ogee en ees Pere Seger te are eae eed es oer eee tar eae Re Cees The Raspberry Pisa Fantasticpiece of mader hardware that has created, or rather re-created, the Fascination we once allhad pet eerie ete eee ee eee ec Bee ey ete ce en enn Se een) ee ea eee rete Firmly pushed tothe Forefront. The Raspberry Pi uses Raspbian eee Pee ee Une 05, orto be more accurate it's a Debiabased distribution Se re re nes CE ute eed Pre ee ie aca eS Raspberry Pi Foundation has gone the extra mile toinclude vast range of Python madules, extensions and even examples, ut of eee ee ese Follow the instructions on how to et one up (oy wing one of cur Pete ee eee eee ans ee Ceres ean ees arenes ee erect ecertir cs) Rees ee ese een ores ee eee eer ery eee eae neers ee enn ee een eee were a Pe ee eet Seater ‘Power socket anywhere in your house within range of your wireless router, Aslong asthe Piis connected, you willbe abe to remotely Se ere ete Pate cheats Using thismethod saves lat of money, as you dorit need another eu ue ea tee oe) Bee et eee ea ete) Cee eee ce) Peer nate reese ees Peete et ere) erate heme es ot ee gens wall under desk while stil being able to connect tot and code, ‘The main advantage i, of course the extra content that the Raspberry Pi Foundation has included out ofthe box. The reason For thisis that the Raspberry P's goalis to help educate the ser, whether thats coding electronics, or some other aspectof Pte See Cn Lerner crs IDEsFor the user to complie Python code on; a well as both Python cee ere care eT Penna ‘There are other advantages, suchas being ableto combine Python Pee ee eee ea ars
Configure IDLE, an clicking onthe Highlighting tab, However, we dont recommend that Just enteritinto the ILE as you've donein the previous steps. as you won't be seeing the same a our screenshots print¢*Hello everyone!”) Thesaltlemoetiondneyaieninchced EERE witht sogans ani epi e elem your First bit of code. The Print command is Fairly ue! ‘operating system, there are numerous shortcut seenpunatos tps hogs ton Sreqresthepuetiess Keys we dst have oor for th alr, bute the Ops aswell ac quotes inorder to autput content to the screen inthis > Configure IDLE and under the Keystab, youll see alist ofthe casethe Hello everyone bit current bindings. >>> _print(“Hello everyone a everyone! BETTER You'thave noticed the colourcoding within the PERBTD The Pithon ILE ea power interface, nd one Python IDLE. The colours represent ifferent thav’s actualy been written in Python using one elements of Python code. They are: cf the avalable CUItookits. you want to know the many ins and cuts For the Shel, we recommend you take a Few moments to view eta Darel Vere eae eee butps:/docs.ython.org/3/library/ile.html, which deta many of Green-Strings Dark Red Comments Pa eIeaRee Purple Functions ght Red—Error Messages Orange — Commands fame IDLE Colour Coding oreen | ares | meee wort eo Cone wmtineaicconon QEYour First Code Essentially, you've already written your First piece of code with the print(“Hello everyone!") Function from the previous tutorial. However, let's expand that and look at PR Mec Cen Cnr Mh eau acai cui cs D PLAYING WITH PYTHON ‘As with most languages, computer or human, it's all about remembering and applying the right words to the right situation. ‘You're not born knowing these words, so you need to learn them. EATER |" s0u've closed Python 3 IDLE, re-open itas you ESTESEDD You'tnotice that instead ofthe number 4, the ‘din the previous page. nthe Shell enter the ‘outputs the 2+2 you asked to be printed tothe Familiar Fllowing screen. The quotation marks ae defining what's being outoutted enone tothe DLE Shell to print the total of 2+2 youl need to remove 2 the quotes: PITRE %s predicted, the word Hello appearsin the Shetl FTES) You can continue as such, printing 2+2, 46442343 as blue text indicating output froma string, t's and so onto the Shell An easier way sto usea straightforward, and doesnt requretoo much explanation. _ variable, which something we will cverin more depth later. For Now ty row, enter woubampabiacenscom(_ Your First Code (2 mz PRPEED what youhave donehere's assign thelettersa and b twovalues:2 and 2. These are now variables, ‘hich can be calles upon by Python to autbut, ada, subtract, divide ‘and so on for as long as their sumbers stay the same, Ty this printca) printcb), FED Now lets adda sumame: surnane="Hayward” printCsurnane) \We now have two variables containing both a first nameand 3 surname, andwe can print them independently. Te output ofthe stop pate crent Bee values of a and b individually, as essentially you've ‘ed them to be printed separately you want toad the You canuse the folowing print(a+b) Tis code takes the value of both aand b, adds them together, and outputs the result ie were to appythe same routine as before, Sie using the + symbol, the name wouldn't appear coneay inthe outatin te Sel Ty printnanersurnane) ‘We need a space between the two, defining them as two separate values and not something you mathematically play around with. BETTER) You can play around with different kinds of variables together with the Print function. For example, we ‘could assign variables for someone's name: rame="Dovid”™ primtcnane) BETTE 2 Psthon 3 we can separate the two variables vith aspace by using commer print(nane, surname) ‘Alternatively, you can ad the space yourself print(nane+* “+surname) As you can ee, the se ofthe comma is much neater. Congratulation, you've ust taken your fst stes into the wide world of Python, vemebinpiationZz » Steps into Python ) Saving and Executing Your Code NUON a a esis eke eee cer) eleenleceN Cem cole TuN eel Maen een Oinleore ec coney-a DE Leelee Res emt ere Ree Reel kel EDITING CODE You will eventually reach a point where you have to move on From inputting single lines of code into the Shell. Instead, the IDLE Ecltor will allow you to save and execute your Python code, Fatepethe ron Steen toupck PETER Asyou cance te sane courcdogisnpacen Sued ‘on File > New File, this will open a new window with SIEE tthe IDLE Editor as its in the Shell, enabling you to Unttledas tame, Ths the Pthon DLE Eto, and vita you beter understanduhat going on wth your coe. To exeae the canenterthe cde you need to create your fate programs code, however, youreed to rst sveit PressS andyoullhave a Save, ..check box open, ESTEE Te ILE Ecitorisforallintents and purposes,a ERTS) lick on the OK button inthe Save box, and select 2 simple text edtor with Python features, colour destination where youl'save al your Python code. coding and so on. You enter code as you would within the Shell,so The destination canbe a dedicated folder called Python, or you can taking an example From the previous tutorial, enter just dumpit wherever you ke, Remember to keep atidy filesystem, poorest though itl hep you out inthe Future. ED wwrnsdnpuiationscomEGER [tera name for your code, ‘prin hello for ‘example, and click onthe Save button. As soon asthe Python codes saved, i's executed and the output willbe etal in the IDLE Shel inthis case, the words Hello everyone! TWisishow the vat maortyof our Python code Bee will be conducted. Enter it into the Editor, hit FS, save the code and cok atthe output nthe Shel Sometimes things wil fe depending on wheter youve requested a separate indo, tessa a's the proces and nes obherwe Sate, thsisthe method we wl se BETTER | you open the file location ofthe saved Python code, youll notice that it ends in apy extension, ‘This is the default Python Flename, any code youcreate willbe \whateverpy, and any code downloaded From the many Internat Python resource sites wile py. ust ensue that the code is written Fr Python 3 BSTETD eisextend the code and enter few examales From the previous tutorial: nz bez rane="David” surnanes"Hayward” printCnane, surname) print Ca+b) you press now, youllbe asked to save the fle again, asie’s been ‘maxified From before Hyuk the Ox button thee wl be verurten Sie with the new code entries, and executed; with the cxtput inthe Shel snot problem wth jt eee Ves, ut iF you were toed a larger ie averting can become anise, Instead, use ile > Save As From within the Editor to create a backup, [a pein ceercopetns BSTTSET BD Now create anew file. close the Ector, and open anewrinstance Fle > New File from the Shel. Enter the following, and saveit as hello.py ‘-"Python” boris” "cool !* print(a, b, ¢) ‘We willuse this cade inthe nex tutorial. ere o™ oe; Saving and Executing Your Code ClFirst Steps into Python Executing Code From the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, let's see how we can run code that was made in the Guat the command line level. Sie" routine automatically included all the necessary OE Python using the command python and pressing components to allow the execution of code outside ofthe GU the Enter key. Thiswil put you into the command ine version ofthe IDLE: in other words, the command ine. To begin with cick onthe Shel, withthe familar, three sghtfacing arcows asthe cursor (>>>), Windows Start Button and type: end, — = = EMER fi oninertrmeresut rom these he ala rede orevousysucas rand Prompt Aon, Tissiluncho new window, whoa — ep background and white text. This isthe command ne, ao called 3 2 erminal in macOS, Linux, and Raspberry Pl operating systems — Asyou can see, works exactly the same,Nowenter exit©) to leave the command tine Bea Python session, and return backto the command romp. Enter the folder where you saved the code from the previous tutorial, and lst the avaiable files within; you should see the hellopy fi Pian Masicy koma IF youive previously used Python 3 on a Maco Linux, and bsequenty the RaspbertyP, you maybe a ttle confused as towhy the Windows version of Python wsesthe command ine: python instead of python The feason behind this that UND Ike systems such as macOS and Linux, already have Pthan iraries preinstalled. These older branes are present because some ofthe macOSand Linuxsystem sities ely on Python 2, and therefore instaling a newer version ‘oF Python, and thus aerng the executable name, could have dire consequencesta te system, ‘ca recut developers decided thatthe best aparoach For macOS and Linux ystems would be to leave the commas line python’ asexcusive Python 2 use, and newer versions of usrinstlled Python would be python3 Executing Code from the Command Line ESTEE) From withinthe same folderas the code youre going torun enter the followinginto the commandline python hetlo.py This wll execute the code we created, which to remind you is: ="Python” boris” "cool!" printca, b, © Tiss an issue with Windows, a i dese use any Python laries other than the ones installed by the user th wen actully instaling Python. When a Windows user installs Pythan, the installation wizard wil auto-ncude the commang line Instance tothe core Windaws PATH variable, which you can view by entering path into the command tine, This points to the python. ‘exe file required to execute Python code from the commandline, ‘We don't recommend yauinstall both Python 2 and Python 3 within windows 10; natural, you canif you want, but realistically, although Python 2stilhasaFootholdin the coding world, Python 3is the newest version. He 149, hen you wil ned to Fenarne one ofthe Python versione nas as they will be installed in iferen Folders and both use python.exe asthe executable.’ litle long-winded, so unless there'sadre needto have both versions of Python installed it’s best stick to Python 3.=> First Steps into Python) Numbers and Expressions Meee nee Esurance REL ars like. Now let's expand on that, and see just how powerful Python is as a calculator. You can work within the IDLE Shel, or in the Editor, whichever you like. 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 nt all, programming languages. EER O2er uothe cutversionofPython3, as mentioned FEM voucanuseal - you can se ether the Shel or the Ecitor. For the thecustomary Se ES ony Opie Wind time being, we're goingtouse the Shell. Fyou've opted to use 9 Mathematical operations: divide, PSS third-party text editor note that youneedtogettothelDLE Shell multiply, brackets andso.on, pe sernianet, teeta" ox 11 Forthisparto the tora Practisewith afew, forexample: > * & eee ee eee Garay FETED the shellenterthe folowing: BED ‘ever eee Givsion producesadeciml | iber 7-9 Gs. oTaESOR a number nPython hese are 2 ‘a Caled lots orFenting pont ns Asyoucansee, Python canhandle some quitelage numbers. arithmetic however you assesses eed aninteger as opposed toa 2¢o%e2
>> #988726 seb sash — we SS ea cae 2S seas andsoon : sestonYou can also use an operation to see the remainder left over From vision. For example: vill display 3333333333, which is, ofcourse, 3 3recurting, you nowenter: ‘THis will cspla 1, whichis the remainder leftover fram dicing r0by3. Nextupwe SiGe ‘have the power operator a exponentiation you nant be techni “oworkout the power of something youcan wea double maton smo or doubestar onthe keyboard Essentially, e's 24232, but we're suteyou already know the basics behind maths operators ‘This show you would workit ‘cut in Python, ESTER) Numbers and expressions don't ‘stop there, Python has numerous bulla Functions to work out sets of numbers, absolute values, ‘complex numbers, anda host of Matheratical expressions and Pythogarian tongueswisters. For ‘example, to convert a number to binary, use: TB ria This willbe Draenor OF See, eee bit comerthatrenteger Sas it biryani re ret tbo the Font you woes remove the Ob then ou one : format(3, ‘b?) : ‘he Ferma command carvers abe he nbertoe fematedrepresenation as controlled by the format: sCiabttanananas Specfavon tesa Boolean Exessonis lage statement that wi Sie either be true or false. We can use these to compare data, and test to see fits equalto, less than or greater than. Try a: PERETD cxccute the code from Step, andyoulsee a sees of True or False statements depending on the resut ofthe two defining values: 6 and 7. I's an extension oF ‘what we've looked at, and an important part af programming. a wonbampabiatenscom (~ Numbers and Expressions Cl=> First Steps into Python) Using Comments TIER ane Rk Cae ea rein Pierre ine ey Un raeure oary eo eta ete ecu iat ea iene alc difficult to read. #COMMENTS! ‘A method used by most programmers For keeping their code readable, is by commenting on certain sections. For example, if ‘variable is used, the programmer comments on what it’s supposed to do, It's just good practise PEPER Wicltstarthy creating snewinstance ofthe oie BRB) resavethe code and execute it. Youllsee thatthe Eeitor File» New File and then reste asimole cutputin the IDLE Shell stilthe same as before, variable and print commman despite the extra lines being add. Sly put, the hash symbol notes ine of text the programmer ean inst, infor them NE and athers of what's going on, without the user Being aware. Savethe le, and execute the code Bree Se [Bpagag hese rsa sa rane re LS Petpet Ope meer es FETED Running the code witreturn the tne: The value of — PRTESIRIM Lets assume thatthe variable A we've crested is As, 10intothe IDLE Shel window— which is what the numberof ivesin a game. Everytime the player we expected. Now let's acd some ofthe types of comments you'd cis, the value decreases by 1. The programmer could insert 3 normally see within code: routine along the ines of sestonC (Using Comments Cl FB hieweiroutacthe arti Adeiesnber EERESA) nine corms corer lov wats of lives and the player has just lost one, 3 casual SEG section of code. Take our examples from above, viewer orsomeonechecing tecoce,may not non magineford_ineeadofseeng tect ona separate nm, ve cI a moment hat the codes twenty towsndineston,Psend ft tirseen Youcansee whan comments Bao >a x Essent the new codetogeterwith comments The comment, the hash symbol canal be wed to SiGe could look like: up ‘comment out sections of code you don’t want to be executed inyour progam. For tance you vantedtoremove # Set the start value of A to 10 Se ene a the frst print statement, you would # Print the current volue of A # print(*The value of A is,", a) print(*The value of A is,", a) 4 Player lost a life! (B -Conmen py = CPython Code'Commentspy 570)" omo-2 Fle Edt Fort Ran Optons Window Help + F Franc che current value of & 4 print ne value of A ae,", a] # Payer tose a uate! WTntorm player, and ateplay current of & (Lives) "You've just toa a ite!) ryou now haves, ay "ives Lefe!™) PRPTSEDD You can use comments in ifferent ays For PEPET BD You aio use three single quotes to comment ‘example, Block Comments are alae section of ‘outa Block Comment, muitvine setion oF text that details whats going on inthe code, suchas teling the cade comments. For ther to work, place them before and after the areas reader which variables you'r planning on using youwant to comment:=> First Steps into Python) Working with Variables eee ES sacar ey tee ecm ec Peo ast eco eMia air en resis fete TTR LU RL VARIOUS VARIABLES ‘We'llbe working with the Python 3 IDLE Shell inthis tutorial f you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. Ba In some programming languages, you're required touse adolarsignto denotea string, whichisa ‘arable made up of muluple characters, such as aname ofa person. In Python this sn necessary, so, for example, nthe Shell enter: rane="David Hayward? (use your ownname, unless you're also «alled David Hayward) Brann =a ‘As we've seen previously, variables can be concatenated using the plus symbol between the variable names. in our example, we can use: print (name + "2 *& tittle). The middle part between the quotations, allows. us to adda colon and a space. As variables are connected without spaces, we need toadd them manually You can checkthe type of variable in use by suing the type © command, placing the name of the variable inside the brackets. our example, this would be: ‘type (name). Adda new string variable: ti tle="Descended From Celts”. ED wewbanpsstzacenscam Wecanaso within another variable. For iene example, to combine both name and title variables into anew vatable, we use: ‘hen output the content ofthe ew variable as: print character) Numbers are stored ascifferent ii Which, as we know, ae integers(Working with Variables Cl PST However you cant combine both strings and integer type variables in the same command as you ‘woulda set of simiar variables You need to tun one into the ‘ther, o vice versa. When you do tyte combine bth, youl get an ‘error message: ‘Alternatively, you can use: print Character, “is*, age, “years old.") Notice again thatin the last example, you dont need the spaces between the words in quotes, as the commas treat each argument toprint separately. This presents abit ofa problem when you want towork with a number that’s been inputted by the user, for example, as age + 10isboth a string variable and an integer, it won't work. Instead, you need to enter: ‘Thiswill Typecast the age string into an integer that can be worked wth, a The wef ypeCsting ao imporant when Sie dealing with Floating point arithmetic; remember: umberstathaveadecnalpointinthem For rama, ent Now enter type(shint) and youl se that Python has allocated the number as float’, because the value contains a decimal pint. a BETTER) eather example of Typecastng is when you ask Forinput from the user, such asa number. for ‘example, enter: ‘age input (“How old are you? “) ‘Alldata stored fom the Input command s stored asa string vaiable BEET BD wen combining integers and oats Python Usually converts the integer toa flat, but should the reverse ever be applied, i's worth remembering that Python doesnt return the enact value, When converting afloat to an Integer, Python wil always round down tothe nearest integer, talled truncating; in ourcase instead of 19.93, it becomes 18 a os:=> t Steps into Python User Input MCR EC Ue olu Moreen ere MOR Reel MME Re Cue earlier, so now would be a good time to Focus solely on how you get information from the user, then store and present it, USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding. A game, for example, may ask fora character's name, whereas a database can ask for personal details. PEPID irs not already, open the Python 3 1OLE shell, and stata New File nthe Edltor. Let's begin with something really simple, enter: Seer Cae saver ae) BSED Nove that we have the user's name stored ina couple of variables, we cn call them up whenever we want ay cnr ar =e PTE Seve and execute the code, and, as you no doubt suspected, nthe IDLE Shel the program il ask for your fist name storing it asthe variable Firstname, followed by ‘yur surname; also stored its oun variable (surname). ry ED) -2erostcvoncon FED eccrine ssi sane ERD tesserae, ‘eetnnae tec nomar iron seem wee7 (User Input (2 mm BETTE You dor'talwayshave te include quotedtext within the input command, For example, you canaskthe userthetrname, andhave the input inthe line below tet eatin et =a x The code om the previous step isoten esarded SIES ‘as being alittle neater than having a lengthy ‘amount of tet inthe input command, buti's nat arule that’s etn ‘stone, so do as you lke in these situations. Expanding onthe code, tiythis What you've created here sa condition, based on the user'sinputn short, we're using the input From the user and measuring it against a condition. Therefore, the User enters David astheirname, the guard wil allow them to pass Unhindered. however, they enter aname other than Davi, the ‘uard challenges them to aight. Bea Asyoulearned previous, any input om user Sie is automatically a string, so you'll need to apply a “ype inorder totum Rint something eke, Th creates some Interesting addon to thet command. For exam EATER AD 52 9000 startto a text adventure game, pethaps? Now we can expand oni and use the raw input from the user to Flesh outthe game a ite: Ando nals the ate and distance code, we can ad distance = floatCinput(*Distance: *)) Print(“Time:", (distance / rate)) Saye and execute the code, and enter some numbers. Using the Float(input element, veve tld Python that anything enteredisa Floating point umber rather than astring, Bea wmtineciccoson CI=> First Steps into Python) Creating Functions Now that you've mastered the use of variables and user input, the next step is to tackle functions. You've already used a few Functions, such as the print command, but Python races eka scatman trem FUNKY FUNCTIONS ‘Afunction is a command that you enter into Python in order to do something It's little piece ofs takes data, works on Ba ‘and then returns the result. 1's not only data thata function works on. Functions cando all manner of useful things in Python, suchas. Sort data, change items from one Format to another, and check the length or typeof items. Basically, Functionisa short word followed bybrackets. For example, lend, list?) or typed) Dyan a ‘You can pass variables through functions in much the same manner, Le’ assume you want the rhumber of lettersin a person's surname, you could use the Flowing code (enterthe text editr fos ths example): ‘function takes data, usually 3 variable, works on itdepending on what the Function is programmed todo, and returns the end value, The data being worked on goes inside the brackets, sof you wanted to know how many letters aren the word antidsestabishmentararism, then you'd enter ‘enC*antidisestablishmentarianisa”), andthe number 28 would return, ry ED) -2erostcvoncon fython hastens of uncon ulin eto GUE) ‘many to get into in the limited space available here. vowevestoview telat of bun function nb Python 43, navigate to https://docs.python.org/3/library/Functions.htmi, “haere the predefined actions bt snes ets heve ceed many mare Beye ot the ony ones aaaPSTESED *sitional functions canbe added to Python through modules. Pyehon has avast ange of ‘modules available that can cover numerous programming duties, They add Functions and can be imported as and when required, For ‘example, to use advanced Mathematics Functions enter ‘import math Once entered, youll have access to allthe Math madule Functions: FORGING FUNCTIONS There are many different Functio Creating Functions Cl BETTE 10.use2 function froma module, enter the name of the module, followed by aful stop, then the name ofthe Function. Forinstance, using the math module, since we've just imported into Python, we can utise the square root function, mmath.sqrtC16) A yau can se, the codes presented a= module. function (data). created by other Python programmers, which you can import and you'll undoubtedly come Pee ae e en Sn tte ten Cen eee) PEI choose File> New File to enter the editor, et pase ee cost ay Fel lo) Gee STEP 2 isaatee ae eet Print CHetto™, nave) ee eee eee ee Sn ce ae BED to mociy ic fur ee een la Peers Petits aoe rn aren te ha ce ets eee eh ey aren [cer oddca, b):)=> First Steps into Python) Conditions and Loops eon nee eer ue ee MS nee Ce Ceca ee as Ute ut ea er mM ater cnn ere Rivet satan ed Cer cates essence Toots on TRUE CONDITIONS Keeping conditions simple, to begin with, makes learning to program a more enjoyable experience checking if something is TRUE, then doing something else ifit isnt. BEER Letscreatea new Python program thatwilaskthe ETE Now weil use anifstatementto checkifthe word_ ser to input a word, then checkittosee i's a length varable is equal to Fou, and pint friendly Fourletter word ornot. Start with Fle > New File, and begin with conformation iit applies tothe rule the input variable: FETED Now we cancreste anew variable, thenusethelen [PRT The colon atthe end off tells Python that this Function and pass te word variable through itto statement i true, do everything ater the colon ‘get the total numberof letters the userhasjust entered that's indented. Next, move the cursor backto the beginning oF the Editor vee >a x ssPRPEEM P1255 5 and save the code to executeit, Ente afourletter word in the Shel to begin with, you should havethe returned message thatthe words Four letters. Now press FS again, and rerun the program, but thistime, enter a Fiveletter word. The Shell wil display thatt’snot a fourletter word LOOPS Although a loop looks quite similar to a condition, they are somewhat dif Conditions and Loops Cl BETESTD Now expand the code ta include other conditions Eventually it could become quite complex We've added. condition for threeetter words wordinput(*Please enter @ four-letter word: “) ‘ord_lengthelenCword) if word length == 4: print (word, “is @ four-letter nord. Well done.”) elif word_length == 3: print (word, “is a three-letter word. Try again.”) else: print (word, “is not @ four-letter word.) eee ee same block of code a number of times, usually with the support of a condition, eter eet mere Pe unee estas Peeer ee ear er ene ne STEP 3 Hiden eet! ordseT "Cae "Doge print Gnord)} "Uni core Ce The Sr ca For x in range Ci, 10): eed irene eerie=> First Steps into Python Python Modules einen hare Mea ema ater ee eee uot ted Pema eet ee chee edie ana ne tec et alittle more time to them. MASTERING MODULES Think of modules as an extension that's imported into your Python code to enhance and extend its capabilites. There are countless modules available, and as we've seen, you can even make your own, Aiur gon het inceevihnp on EERE teresa erorine eso ate oe?) are limited. The use of modules, however, allows us SUE? S) ‘Pygame module isn’t recognised or installed in tomate mote sophteatedprogarns Asyousreoware modes, Pho, Total mode we canuse i PpinsalsPelaged de thon sits tata mpared sch sinoor mah Close down the DLE shel ane dopo a commend promote Terminal session, At an elevated admin command prompt, enter: pip install pygane Some modules, espedalyon the Raspberry are The PP instaaton requresan ee Biee included by default; the Math module is a prime SUE toitinstaling components a diferent locations ‘example. Sed, other modules aren't always avalable. A goed Stare with asearch For CMD, via the Start button, ight-click the example on nan platforms isthe Pygame module, which contains result, and then click Run as Administrator. Linux and Mac users an ‘many functions to help create games. Try-import pygame. Use the Sudo command, with sudo pip install package.Python Modules ‘Pygane, the module willbe imported ino the code without any problems. oul find that most code downloaded, or copied, From the Internet will contain amodule, msinstream or unique, and their absence is commonly the source of errors in execution ‘lose the command prompt or Terminal, nd re- launch the ILE Shel. When you now enter import & ‘The modules contain the extra code needed to achieve a certain result within your own code, with hich we've previously experimented. For example: ‘import random: Brings inthe code From the Random number generator module. We can then use this madule to create something Ike: for i in range(to): pprint(random.randint(1, 25)) ww ESTEEM ultple modules can be imported within your code. To extend our example, use ‘mort random for I in rangeC5): print(random.randint(1, 25)) rint(math. pi) (a nny cheat The results astring of random numbers followed by the value of, as pulled from the math ‘madule using the print(math.i) function. You can also pullin certain functions From a module by using the From and import commands, suchas: from randon import randint for i in rangecs): print(randint(1, 25)) oe This code, when saved and executed, wil display ten Siery random numbers from 1 to 25. Youcan play around vith the code to display more or less, and from a greater or lesser range. For example: ‘import random for i in range(2s): pprintCrandom.randint(1, 100)) This helps create a more streamlined approsch to Sy programming, You can also use: import module*, hich willimport everything defined within the named module. However is often regarded as a waste of resources, butit works onetheles. Finally, modules canbe imported as alases ‘import math as m print(m.pi) OF course, adding comments helps to tell others what's going on es=> First Steps into Python) Python Errors Ieee Tes Cate ere eur mec RT Event sc rics not able to continue due to something being missed out, wron CP oan aon cate nunca oh T acca DEBUGGING Errors in code are called bugs, they're perfectly normal and can often be easily rect isto keep looking, experimenting, and testing. Eventually your code will be bug free. Code ct as fluid a the written word,.no matter how good the procramming language's. Python is certainly easier than most languages, bt even tis prone to some “annoying bugs. The most common are typos bythe user, and while easy to find in simple dozertne code, imagine having to debug ‘mult-thousand tne code. Ba 1d with a litle patience. The ‘Thankfully Python is helpful when it comes to displaying error messages. when yourecelve an error inredink from the IDLE Shel til define the error itself, ‘alongwith the line number where the error has occurred, While in the IDLE Ector this alte daunting for lots of code, text editors help by including tine numbering Asie ve mentioned, the most common oF rors it Biee the typo, often at the command level, mistyping the pn commander example. However, the ale occ whee ‘ot numerous arable allof wich have lengthy names The est. ‘thceisto simply othvough the cade and checkyour speling (Dremirone =e x seston PEPE Syntax rors are probably the second most common erors you'll come across a programmer. Evenif the spellings corcect, the actual command teal wrong, In Python 3 ths often occurs when Python 2 syntaxes ae applied. The ‘mast annoying of these is the print Function In Pythan 3, we use print words"), whereas Python2 uses print “words” oineasvia =a x(_ Python Errors Cl ATED Pes) brackets are also a culos of programming ‘errs, especially when you have something ke: print(batanced_checkCinput©))) Remember tat for every''there must be an equal numberof There are thousand of online Python resources, Bee code snippets, and lengthy discussions across forumton how best to aleve something We 99% fk good cose, dart ays be re inte copsng an pasting random codeine your edt More ften than ot, won warkand Trateatingy, you wont have earned aryhing FRED csvset vores from the Conditions and Loops section, where the colon means everything indented Fellowing the statementisto be executed along as t's true? Missing the indent or having too much oF an indent, will come back with an errr, Anexcellent way to check your code step-bystep is touse Python Tutor's Visualse web page, Found at ‘wurw pythontutor.com/visvalizehtmlsmode=edit. Simply paste your code into the editor and cick the Visualize Execution button to run the code line-byine. Thishelp to ear bugs, andany rmisunderstandings. Planing mates fr good code, While te old Sie ‘school, it's a good habit to plan what your code will obefore sting down totypeteout Usk thevaribes that lle Used, along with the modules, and write outa serpt for any user Interaction o outputs, PRPETBD Purely cut of interest, the word debuaging in ‘computing terms comes From Admiral Grace Hopper, who, back inthe 0s, was working on a monolithic Harvard Markl lectromechanical computer. According to legend, Hopper Found a moth tuck n a relay, thus preventing the system from working. Removal ofthe moth was hence called: debuosing,ZZ » Steps into Python ) Combining What You Know So Far NST A TM To ure Rol a ree CEL eo coke EA looked at so Far and apply it to writing a piece of code. This code can then be used to Resa ane eM aa usu n Ua PLAYING WITH PI For this example, we're going to create a program that will calculate the value of Pito a set number of decimal places; as described by the user. It combines much of what we've learned, anda litle more. BEER %2"tby opening Python and creating a New Fein thatcan accurately calculate P without rendering the computer's (CPU useless For several minutes. The recommended calculation Lsedin such creumstancesis the Chudnovsky Algorithm, you can find more information about at enwikipedia.org/wik/ (Chudnovsky_algorithm, the Editor Fist, we need to get hold of an equation ‘We can utilise the Chudnovsky Algorithm to create (ur own Python script based on te calculation. \We'l begin by importing some important modules and Functions within the modules Bee from decinal import Decimal, getcontext ‘import math ‘This uses the decimal and getcontext functions from the decimal ‘module, both of which deal with lage decal place numbers, and, naturally, the math module BRPED ow we can incertthe Pi calculation algorithm pattof the code. This is aversion ofthe CChudnovsky Algorithm: ED -serostcvoncon The preiosstep define the les that makeup Siz both the algorithm and creating the string that wi evetualy ply thevalve of according tothe Chudrovaly brothers algo. syou have na doubt alead surmise, would be hands tact autpt the value of ito the scree, To recy that wean ad printGcale(1)) aE You c27 save and execute the code at this pont if you tke. The output wil print the value of Pito 27 decimal places: 3.181592653889734207668453591. hile pretty impressive on its on, we want some user interaction to ask the \seras to how many places Pishouid be calculated. ESTED Wc can insertan input tine before the Pi calculation Def command need to be an integer, ast wl otherwise default toastring, We cancallit umberofdgits, and use the getcontext function: nunberofdigits = intCinput(“please enter the runber of decimal place to calculate Pi to: “)) getcontext().prec = nunberofdigitsPSTTSERD Wiccan execute the code now, anditilaskthe user tohow many decimal places they want to calculate Pi,and then output the result inthe IDLE Shel. Try it with 1000 places, but dont go too high or else your computer will be locked up freatedting Partofprogenmingis SEO being able to modify code, making more preserabe ernie dreomert tha tines ow ong tales Conputrtocalesatethe dial pares ond preset the hformatonin afferent {Stour Forth chopintothe comand ire soderpo the cea oe wee aeadyhavet stated pinnate From decimal import Decimal, getcontext import math import time import colorana fron colorana import Fore colorana.imit© runberofdigits = intCinputC“please enter the nunber Of decimal places to calculate Pi to: “)) getcontext().prec = nunberofdigits start_time = tine. time) ef cale(n): Combining What You Know So Far Cl BRPEED Now we nced to import the colorama module (nhich wil output textin diferent colours), along with the Fore Function (which cctates the Foreground, ink, colour, and the time module to start a virtua stopwatch to see how long ‘ur ealeulations take: import time import colorana from colorana inport Fore = Decinal(a) i = Decimal (a) ‘deno = Decina(@) k=o for k in range(n): t = @ecimal(-1)**K)*(nath. factorial Decimal (6)*K))*(13591409+545140134*K) deno = rath. factorial(3*k)*(nath. Factorial (k)**Decimal (3))*(640320**(3*K)) i 4= Decimal (t)/Decimal (deno) pi = pi * Decimal (12)/ Decimal (640320**Decimal(1.5)) pi = pi return str(pi) print cale(1)) rintCFore.RED + “\nTine token:”, time.time() ~ start_time)Manipulating DataData is everything. It’s more valuable than gold or oil. With data, governments can change the world, politicians can rise or fall, and companies, large or small, can impact our Future in ways we wouldn't have imagined just a Few years ago. Data is power, and learning how to manipulate and control it are essential aspects of any coding language. Here we'll take a look at how you can use date and time functions, write to filesin your system, and even create graphical user interfaces that will take your coding skills to new levels and open more doors for you. sts Tuple Dictionarie: and Time 9 File toFile Pyth mbiniFE) Weritnoose Lists Lists are one of the most common types of data structures you will comes across in Python. 4 list is 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 iss, ‘and lists within lst. Brea Alistisa sequence of data values called tems. You create the name of your ist followed by an equal ‘sign, then square brackets and the items separated by commas, note that strings use quotes: (Beuirone = ERT Once youve defined your list. you can call each by referencing its name folowed by number. ists starthe fist tem entry a5 0, followed by 1, 2,3, and so on. Forexample: ‘umber ‘ocalluptheentie contents of the Uist. ‘umbers[3] “Tocallthe tem thie rom zero inthe list (21 inthis cas). You can also access or index, the lastitem in alist by Using the minus sign before the item number [-1], or the second to las item with [2], and so on. Trying to reference an Rem that isnt in thelist, such as [10] will rebum an error FEEL Sicraissimiarto indexing, butyou can retrieve ‘multiple items ina ist by separating tem numbers vith acolon.For examle: ‘willoutput 4 and 7, those beng item numbers 1 and2. Note that the returned values don’ include the second index position (as you ‘would numbers{t:3] to return 4 7 and 21),Bea You can update items within an existing list, remove items, and evenjoin ists together, For example, to Join two lists we can use: ‘everything = nunbers + mythical_creatures ‘Then view the combined lst with PD tems canbe added toa list by entering runbers=nunbers+[201) OcForstrings (Or by using the append function: FE scr icn excite soe ntn is yer BED veovcaneeee tmowaierortee avatar ceos eta roe Inserts the number 62 at tem index 4. Ane: ill emove FEAT) You alo use thelist function tobreak string down Into its components. Fr example: ListC*Devid") Breaks the name David into'D, toanewist: 1, V, 1, 'e This can then be passed Siery is by the item number: “The second, byitem name: Removal ofitems can be done n two ways. The First ‘Based on that, we can create a program to store someone'sname and age asalist: “The combined name and age ist called user, which canbe called byentering ser into the Shel. Experiment and see what you can do, oeED) ov Tuples Tuples are virtually identical to lists, however, where lists can be updated, deleted, or changed in some way, a tuple remains a constant. This is called immutable, and pened une neek elo THE IMMUTABLE TUPLE Reasons for having tuples vary depending on what the program is intended to do. Mostly a tupleis reserved for something ‘special, but they/re also used, as an example, in an adventure game where non-playing character names are stored. FSPTSEM 2 tule iscreatedthesame mayacalis, but inthis BRIER You can create grouped tuples int its that contain Instance you use curved brackets instead of square multiple sets of data. For instance, here we havea brackets For example: tuple called NPC (Non Playable Characters) containing the character ‘name, and their combat rating, for an adventure game: Dineen =e | [Brmmivonn aaa ries rd ws heencaon, a PR Ea *Svithlists.theitemswithinanamestuplecenbe — EATER Each ofthese dota items canbe accessed asa whole indexed according to their position in the data range: ‘by entering NPC into the Shell, or they can be mieetnorse Coermminihcll econeonderbe sorted Shaolin wtom eo tase on Horr amy aang det rag toene NCIC Sireinatereneset vie.’sworth noting that when referencing mutiple tuples within ais, the indexing is ight different From the norm. You would expect the 95 combatting ofthe character Valeria to be NPC[a[], however its not, k's actually wecr2]t1 cy FID this means, of couse, thatthe indexing follows thus: This, as you can imagine, gets little confusing when you have alot of tuple data to deal with, Now unpack the tuple into two Bea corresponding variables: ‘You can now check the values by entering name and combat_rating cr Remember, as witht, you can also index tuples sing negative numbers, which count backwards Fromthe end ofthe data. So, Fr our example, using the tuple with multipe data items, we would reference the Valera character wit: Nect2]¢-01 iB BETTER) Terles though, utilse a feature called unpacking, where the data items stored within a tuple are ‘assigned variables Fst, create the tuple with two ers (name and ‘combat rating) we can vsethe max andmin fonctions to rhe SuzMO highest and lowest values of a tuple composed of rpumbers For example: “The numbers canbe integers and floats. To output the highest and lowest, use rimtCnaxCnunbers)) Print(minCnunbers)) a oe:ED) ov 70 Dictionaries Lists are extremely useful, but dictionaries in Python are by Far the more technical way of dealing with data items. Although they can be tricky to get to grips with at First, Nem er ee ee cen ence KEY PAIRS ‘A dictionary is tke a list, But instead each data item comes as a pair, the {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 like. Brea Lev'ssay you want to create a phonebook in Python. You would create the dilonary name, and contain the data in curt brackets, separating the key and value bya colon Key: Value. For example: 789} J swine ts tunes, nd0 on tings need Gue2 to be enclosed in quotes (single or double), while itegrscanbe left epen Remerser tht these on De ee ‘ing or anitege you ist need tense he eleven one owes honebook2={“David": “0987 654 321"} Bresso =a x woubampabiacenscom ‘swith ss and tuples, you can checkthe contents of adicionary by caling the icionary name; phonebook, in this example. This will display the data tems youve enteredin similar fashion toa lst, whichyyouire no doubt familar with by now. Doane x The benefit of using a dctonarys that you 5 ceca eee ae Phonebook exemple from the previous steps, we can enter: Brenton 7‘Adding toa dctionarys easy too. You can include Bea ‘anew data item entry by adding the new key and valueitemsas such: renin ‘nd you can also remove items from a dictionary byissuing the del command followed bythe IRem’skey-the value will aso be removed aswel since both ‘work as pair of data items: oe Next, we need to define the user inputs and variables, one forthe person's name, the other for their phone number (we wil keep it simple to avoid lengthy Python code) Note we've kept the number as an integer instead (oF astring eventhough the value can be both aninteger anda string, Now we need to ade the user's inputted variables tothe newly created blank dictionary. Using the same process asin Step 5, we can enter Phonebook[nane] = nunber Dice come FER sacs ssntwes encour cesegs ED eee ee trannaousaronantine hero eceal eaten cy BETTE Now when we save and execute the code, Python wil ask fora name and a number. wil then insert those entries int the phonebook dictionary, which we can test by entering nto the Shell: Ifthe number needs to contain spaces youineedto makeita string, so remove the int par-of the input. wonbampabiatenscomManipulating Data Splitting and Joining Strings When dealing with data in Python, especially from a user's input, you will undoubtedly 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. 7 STRING THEORIES. ‘We've already looked at some list functions, using .nsert, remove, and .pop, but there are also functions that can be applied tostrings. FRB te main tool inthe string Function arsenalis split) ‘witht you'e able to split apart a string of data, based on the argument within the brackets. Fr example, here's a string with threeitems, each separated by a space: Sr Nowe’ tun the string into alist, and spitthe contentaccordingy: panes=text. split“) ‘And enter the name ofthe new lst, names, to see the three items, Bem woubampabiacenscom Note thatthe text split part containsthe brackets, quotes then a space followed by closing quotes and brackets. The spaceisthe separator, indicating that each Uist Item entry is separated by a space. Likewise, Sv (Comma Separated \Value) content hasa comma, owe would se: Bee Be We've previously seen how using aname, we can Bea! sola string into individual letters asa “The returned values‘, v7, While it may seem aitle ‘seless under ordinary circumstances, it could be hand) for creating aspeling game, For example aFEE he coneseore stenoses ‘lphabet ‘This wil splay ‘abede' in the Shell Ferm the name: ‘nane="". joinCname) ‘pane ‘we've joined the string back together and retained the lst called name, passing Itthrough th join Function. & we canthetefore apply jinto the separated name SiGe ‘we made in Step 4, combining the letters again to C Splitting and Joining Strings Cl ‘swith the splltfuncton, the separator doesn't havetto be a space it can also be a comma, ora Full stop, or hyphen or whatever you tke: Bea 5 Theres some teretog nctons youcan apoyo up ‘a string, such as capitalize and title. For example: ‘titlesconan the cimmerian” title.capitalizeQ title CeO a ‘good example of sing the jon functions when you have list of words you want to combine into ‘asentence Note the space between the quotes before the jon function (where there were no quotesin Step 6 joi). Te? 10 ERD secrete Meee tpewaterscriortracencematienes wmtinesicconon QIManipulating Data Formatting Strings As you work with data, creating lists, dictionaries, and objects you'll often want to print eaten raha ses ear alo eeu Meso Rel a a ane ee neon coe oes] 8 RU acid 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 ways recommended. FSPEB the basic formatting in Python ito call each ED Wiccan, of course, also include integers into the mix: variable nto the string using the cury brackets: potent BSTIEED Remember oclosethe pinefunction with wosets EINEM) there are many cifferent waysto apply string OF brackets, 2s you've encased the varabein one, formating. some are aie simple, aswe've shown ‘andthe print Functonin another. You can include multiple cases oF _youhere, and others can be significantly more complex. all string frmatingin single pit Function:
a x EE te incinccrsitmonreuge: seve EREEPB) tec wenmesowsrutins te EESD wiscercnsctow es ae Tree Sette oon tee Tom mcnonnbetoen derbies sated wih eoeaieoreet ae ae arguments asi converts the time tuple into a string For exemple, to display the current day ofthe week we can use: tinder aes ‘ime. strftime KA") 8 kage ye os (Doenane a : ond 061 (06 me apse) © coyotes 096 (0 Monday) 7 oyot yee 12026 eta dy) © bape saings 0,1, 2 means tary eters OST BED vserostcvonconNaturally this means you can incorporate various Functions into your own code, such a5: Bea Note the last two entries, with SH and HIKM, as {you can see, these ae the hours and minutes and as the lst entry indicates entering them as GM doesnt display the time carecly inthe Shell we can easy rectify this wath ‘ime. steftine 38") @ (Date and Time Cl ‘example, taking the above code, we can alter itsightly by including \We can also use the Time maduleto display the amount o time taken fr an event to happen. For The output wil look similar tothe screenshot below. ‘The timer Function needs tobe ether side oF the input statement, as thats when the variable name f being created — ‘epending on havi long the user took taog in The length of time & then displayed on the last ine ofthe code, asthe endtime variable. Pod = x ‘This means you'te going to be abe to display ether thecurene ime, orthe time when something ‘eccurted such asa user entering ther name. Try this code inthe Eto ‘Trytocextendit further toinclude day, month, year, and s0 on BPE there's alot thatcan be done with the Time rmadule, some of itis quite complex too such aslsplaying the number of seconds since January 1st 1970. Fyou ‘ane to dill dawn Futher into the Time module, then inthe Shel, enter-he1pCtime to display the curent Python version help ile For the Time madule. @ 7Manipulating Data Opening Files ene u ican aN hemor Car) eae ee lor in en Mat Me ene tical etter Tne eos era h Cn eRe ot ti os OPEN, READ AND WRITE InPython, you create a file objec, similar to creating a variab usualy categorised as text or binary. Startby entering some textinto your system's text editor. The text editor is preferable toa word processor, 3s word processors incude background Formatting and ‘other elements. n our example, we have the poem The Cimmerian, byRobert E Howard, and we've saved the leas poem. You se the open Fnceonto pass the eins Gie2 variable as an object. You can name the file object anything yo tte, bt youve tall enon the ame oe lortonof the text ieyos reopening ‘The eason fr the double slash (\)isbecause Python wil read this _as Unicode Error, thinking you've entered: \U-Thisis Windows-only, Lux and Mac worthave tis sue Donnene : seston only you pass in the file using the open() Function. Files are ESTED "you now enter poem into the Shell you wil get some information regarding the tet file you'vejust asked tobe opened, We can now use the poem variable to read the contents ofthe Fle: Note than a/nentryin the textrepresents 2 newline, as wehave sed previous. [a Ifyou enter poem ead) a second time, you wil notice tat the texthas been removed From the file, You wil need to enter poeriopen("C:\\Users\\david\\ Docurtent's\\poem. txt”) again to recreate the ile, Thistime, however, enter: Now the /nenties ae removed in Favour of new tinesand Feadabletext. Demian 5Bea Forexample: oem.read(S) Dispaysthe Fis Five characters, while entering; oem.read(S) ‘llislay the next ve. Entering (1 wil display one character at atime, ‘As with sts, tuples, dictionaries and soon, you're able ta index individual characters ofthe text & poem.readlinec) ‘ll display the Fist ine ofthe text. And poem.readlinec) ‘ll display the nest tne of text. Similarly, you can dsplay one tine of text at atime by {sing the readline Function. For example. FEE cscs cstroecyncnsreieoe BED sitccrecnaeiees multiple tists, These canthen be stored as variable ‘We can also use the fr statement to read the lines cof text backtous: ‘And, since hiss Python there are other ways to produce the same output: ‘As you may suspect, you can pass the readtine() Function into a variable, allowing youto calli again, Letsimagine that you wanted to print the text character at time, a5 would an old dot matiix printer. We can use the Time madule mixed with what we've looked there. Ty this: oe: (0 Cl (Opening FilesManipulating Data Writing to Files Being able to read external files within Python is certainly handy, but writing to a file can be even more useful. Using the write() Function, you're able to output the results of a program to a file, which you can then use to read() back into Python, or as a text Geert WRITE AND CLOSE “The write() Function is slightly more complex than read(). Along with the filename, you must also include an access mode that. determines whether the file in question isin read or write mode. Start by opening IDLE and enter the following (ebviously entering your oun username location): ‘Thiscode wil create tent Fle, called text.btin write mode, using the variable there's no fil ofthat name inthe locaton, it wl ‘create one. Fone already exis, iwll overmite so be careful vein ox wean nou totetexFlewng the wnte0 Guee function. This works opposite to read(), writing lines instead of reading them Try this: Note the 109, t's the numberof characters you've entered. (Bet =a * However, the actual text fief still blank (you can check by opening itup) This is because you've "urtten the line oF text tothe fle object, but not committed itto the fle itsel Part ofthe write Functions that we needto commit the changes tothe Fle, we can dothisby entering: Hyourowopen the tex feithatet ear yout see thatthe line you created has been writtento the fle This gives us the Foundation Fo some interesting posses, perhaps the creation of your own logfile, or even the begining oF an adventure game, SS Ry Sgar one te a a, hr 8Fe occa neces ED ieee sen sreewoticgn ie mest tesdetne we can keep extending the text tne byline SiGe ending each with a new line (\n). When you're done, Finish the code wth tclose(),and open the filein text ‘editor ta see the results: (writing to Files Cl \We can pass variables toa file that we've created In ython, Perhaps we want the value of Pito be ‘written toile, We can cal Pifrom the Math module, create anew file, and pass the output of Pinto the new file: | Wie also need to create anew file to write Pi to Now e's create a variable called pi, and assign itthe value oF i Remember to change you le location to your own particular system setup, & FE re vcs iperottcesta coer ED icc esses rere sancti encore Tenth we en vesting fomatingtoclthe SuzMO variable and write it to the file, then commit the changes and close the file: ‘Asyou can see from the results, you're able to passany variable to afle,ED) ov Exceptions PON ee EI on ean a Ec eee ess cr circumstances that are mostly out of your control. Let’s assume you aska user to divide two numbers, and they try to divide by zero. This will create an error, and break your code. EXCEPTIONAL OBJECTS Rather than stop the flow of your code, Python includes exception objects, which handle unexpected errors in the code. We ‘can combat errors by creating conditions where exceptions may occur. You can create an exception error by simply tying \We can use the Functions raise exception to create todivide anumber by zero. This wil report back ‘our awn eror handling code within Python. Lets ‘ith the ZeraDivsiontrror: Division by zero message, as seen assume your code has you warping around the cosmos, to0 much, the screenshot. The ZeroDiisionéiror parts the exception class, of however, results ina warp core breach Tostop the game from hich there ae mary. exting ue t the warp core going supernova, we can create 3 ——— asst exception: 5 Nostexeptons Tolzagarveorin theca we can erase the ue are raised ue? potential error within a try: block. This block consists: dutomataly when Pon oF ty excep can here ode heist nef eres Conese samen tats sree ianenede odessa a inert wrong with che cde. fowevee wees ese curt, = sy ‘exceptions that are designed to ‘contain the potential ertor and Feact tot, 35 opposedto letting the code fall.Deornig Sinica * lets assume you want to open afile and write to ERT Fo" example, using the divide by zero error, we can create an exception where the code can handle the ‘error without Python quitting due to the problem: TED ¥0u can useexcentions to hance a variety of useful tasks, Using an example from our previous tutorials, (Exceptions Cl ESTE i2tuclly, we can quickly Fixthe issue by changing the read onl instance with a"w' for wte This, asyoualready know, wil create the Fle and write the content then ‘ommitthe changes to the ie, The end result wil report aifferent seto cumstances in this case, a successful execution of the code 5 You canals us aia back which woksina up ‘Similar Fashion, but you cannot use else with it. Hint: ‘ound to delete the este ile om your folder. being opened as read only (the “part. So inthis. ‘ase rather than Python teling us we're doing something wrong we've created an exception, using the IOError clas, informing the user that the permissions ae incorrect. — = or Obviously this wont work due to the fie textfiletxt ‘Asbeforeanerrorwilocau seve wed the Sie read-only permission. IF we change itto a “w", then the code will enecute without the eror being depayed inthe DLE Shel. Nedless to say, it can bea tricky getting the exception code right the first time. Practise though, and you will get the hang of i ew Base ms wmiinesicconon CEManipulating Data Python Graphics RGR een insta eee eee ue ne ae aie Rem eu se neces ee hia einte ne) has numerous ways in which to include graphics, and they're surprisingly powerful too. 5 GOING GRAPHICAL ‘You can draw simple graphics, tines, squares and so on, or you can use one of the many Python modules available to bring out some spectacular effects. ne ofthe best graphical modules to begin learning Python grapicsis Turtle. The Turtle module sas the name suggests, based onthe turtle robots used in many schools that canbe programmed to draw something ona large piece of paper on the Floor. The Turtle madule can be Imported with: Import tutte. Let's beain by Grawing a simple circle. Start a New SLED tren ever the folowing cove ‘import turtle turtle. circle so) ‘turtle. getscreen()._root.nainloop) ‘As usual pres FS to save the code and execute It This wll open up ew window and the Turtle’ wil draw circle. woubampabiacenscom The command trtecrle(S) i what draws the circle on the sceen, with 50 being the size. You «can play around withthe sizes i you tke, going upto 100, 150, and beyond: you can draw an ar by entering tuntle-cincle(S0, 180), where the sizes 50, but ou'e telling Python to only draw 480° ofthecirce, ‘The ast part of the cicle code tes Python tokeeo 5 SeatdechesSescers ersten remain open, sothe user can cco else it. Now let's make a square ‘You'l notice weve inserted loop to draw the sides ofthe square.PTET To add some colour we can addanewlineto the square code turtle.color¢“Red”) ‘And.we can even change the character to an actual turtle by entering turtle. shopec“turtle") ‘we can aso use the command turtle begin Fill, andturtle.end_ Fill to filin the square with the chosen colours inthis ase, red outline, and yellow il PETTSTD) *syoucan see, the Turtle madule can draw out some pretty good shapes, and become alittle more complex, asyou begin to master the way it works. Enter this example: from turtle import * color¢‘red’, *yellow’) begin ALIO | while True: formard(200) ef EC170) if abs(pos@) 1 erenatogan in ws FS atreaty eee) Toguneapet hep tncinent/ loping. ty pense “erent 8S Gdn PIM ovr to create the olduser Function: ‘There's a fairbithanpening here. We have login and pasow variables, which are then matched tothe users dictionary IF theresa match, then we have a successfllogin ‘andthe time and date ofthe loginis outputted. If they don't match, then we printan error, and the process starts again and gan Stil ope seen on, came scene) (Combining What You Know So Far Working with Modules ) / Calendar Module Beyond the Time module, the Calendar module can produce some interesting results Rieu te ten anol Rer Ma cae enema Cates time module-like Format, you can actually call up a wall-calendar type display. WORKING WITH DATES ‘The Calendar modules built into Python 3. However, if, it’s not installed, you can add it using pip instal calendar, as 2 ‘Windows administrator, or sudo pip install calendar for Linux and macOS. ESTEE 2uncneython3 andenter: import calendarto RSTSEY «al up the module andisinheretFuetons. Once istoaded into memory, startby entering ‘There are numerous Functions, within the Calendar ‘module that may be of interest to you when Forming your own code. For example, you can splay the number oF sep=cal endar.TextCatendar calendar .SUNDAY), panels sep.prmonth(2019, 9) eops=calendar.Lecpdays(1900, 2019) — _ Print Cleaps) Rar eka es ae eT ‘The result fs 29, starting From 1904 onward. Fn fot Su Oy Cis Winton tp ATES) You cansee that the days oF September 2019 are EBABY You could even Fashion that particular examole into displayedina wall calendar fashion, Naturally you apiece of working, ser interactive Python code: ‘an change the 2019, 9 partofthe second ine to any year and ‘month you want, a birthday for example (1973, 6 The Fist ine ‘configures TextCalendar to start ts weeks ona Sunday; you can ont For Monday if you prefer. EE) -serostasoncon
You might also like
Python_Complete_Manual_-_January_2025
PDF
No ratings yet
Python_Complete_Manual_-_January_2025
164 pages
The Complete Coding Manual (21th Ed., 2024)
PDF
100% (2)
The Complete Coding Manual (21th Ed., 2024)
164 pages
Information Systems 511 Learner Guide
PDF
No ratings yet
Information Systems 511 Learner Guide
95 pages
The Complete Python Coding Manual - 21th Edition, 2024
PDF
No ratings yet
The Complete Python Coding Manual - 21th Edition, 2024
164 pages
Components of Android
PDF
No ratings yet
Components of Android
36 pages
Python The Inventory Project
PDF
No ratings yet
Python The Inventory Project
52 pages
Object Oriented Programming Methodology (CS and IT)
PDF
No ratings yet
Object Oriented Programming Methodology (CS and IT)
2 pages
PHP Work Book
PDF
0% (1)
PHP Work Book
25 pages
Network Monitoring System
PDF
No ratings yet
Network Monitoring System
25 pages
Functional PHP
PDF
No ratings yet
Functional PHP
39 pages
The Ultimate Python Coding
PDF
30% (10)
The Ultimate Python Coding
194 pages
Python & C++ For Beginners - Vol. 33, 2019
PDF
No ratings yet
Python & C++ For Beginners - Vol. 33, 2019
164 pages
The Complete Coding Manual - 5th Edition, 2020
PDF
No ratings yet
The Complete Coding Manual - 5th Edition, 2020
195 pages
Docker Django Development
PDF
No ratings yet
Docker Django Development
22 pages
Keith Tab W Tkinter Tutorial Learn Tkinter
PDF
No ratings yet
Keith Tab W Tkinter Tutorial Learn Tkinter
241 pages
PDI-Labguide ETL Using Pentaho Data Integration
PDF
No ratings yet
PDI-Labguide ETL Using Pentaho Data Integration
36 pages
Error Handling in PHP
PDF
No ratings yet
Error Handling in PHP
18 pages
C Programming
PDF
100% (1)
C Programming
294 pages
Core Python Programming and Problem Anal
PDF
No ratings yet
Core Python Programming and Problem Anal
232 pages
Javascript Cheatsheet: Musa Al-Hassy
PDF
No ratings yet
Javascript Cheatsheet: Musa Al-Hassy
9 pages
Programing With Java - Course 1
PDF
No ratings yet
Programing With Java - Course 1
152 pages
2 IntroductionToRDBMS
PDF
No ratings yet
2 IntroductionToRDBMS
192 pages
SQL Talk
PDF
No ratings yet
SQL Talk
176 pages
Python & C++ For Beginners, 2nd Edition (2020)
PDF
No ratings yet
Python & C++ For Beginners, 2nd Edition (2020)
82 pages
Python Crash Course
PDF
No ratings yet
Python Crash Course
12 pages
Data Analysis Tutorial
PDF
No ratings yet
Data Analysis Tutorial
152 pages
Ict S122 - Windows-Commands
PDF
100% (1)
Ict S122 - Windows-Commands
10 pages
Future - Python The Complete Manual - 16th Edition 2023
PDF
No ratings yet
Future - Python The Complete Manual - 16th Edition 2023
134 pages
1.3.1 Hardware Specification
PDF
No ratings yet
1.3.1 Hardware Specification
6 pages
The Complete Python Manual by The Complete Python Manual
PDF
No ratings yet
The Complete Python Manual by The Complete Python Manual
197 pages
The Complete Python Manual (5th Edition) - April 2020-NoGrp
PDF
No ratings yet
The Complete Python Manual (5th Edition) - April 2020-NoGrp
197 pages
Plete Python Manual 5th Edition 2020 PDF
PDF
No ratings yet
Plete Python Manual 5th Edition 2020 PDF
195 pages
The Ultimate Python Coding Manual, 5th Edition 2021
PDF
100% (1)
The Ultimate Python Coding Manual, 5th Edition 2021
194 pages
2022-07-23 Python For Beginners
PDF
No ratings yet
2022-07-23 Python For Beginners
94 pages
The Essential Coding Manual November 2019
PDF
No ratings yet
The Essential Coding Manual November 2019
198 pages
Python Complete Manual (Coding & Programming)
PDF
No ratings yet
Python Complete Manual (Coding & Programming)
165 pages
The Complete Python Coding Manual - 3rd Edition, 2023
PDF
No ratings yet
The Complete Python Coding Manual - 3rd Edition, 2023
196 pages
Python Coding and Programming
PDF
No ratings yet
Python Coding and Programming
162 pages
The Complete Coding Manual – 19th Edition, 2023
PDF
No ratings yet
The Complete Coding Manual – 19th Edition, 2023
196 pages
Python For Beginners Ed7 2021t
PDF
100% (7)
Python For Beginners Ed7 2021t
92 pages
Coding For Python - 2020-06
PDF
100% (2)
Coding For Python - 2020-06
164 pages
The Complete Coding Manual 5th Edition - April 2020
PDF
No ratings yet
The Complete Coding Manual 5th Edition - April 2020
197 pages
The Complete Coding Manual (5th Edition) - April 2020
PDF
No ratings yet
The Complete Coding Manual (5th Edition) - April 2020
197 pages
The Complete Coding Manual - Issue 4 - February 2024
PDF
No ratings yet
The Complete Coding Manual - Issue 4 - February 2024
161 pages
Coding For Beginners - 12th Edition 2022 - Coding For Beginners
PDF
100% (1)
Coding For Beginners - 12th Edition 2022 - Coding For Beginners
97 pages
Coding User - Issue 08 December 2023
PDF
No ratings yet
Coding User - Issue 08 December 2023
242 pages
2020-05-01 The Essential Coding Manual
PDF
100% (3)
2020-05-01 The Essential Coding Manual
194 pages
.Python For Beginners SAMPLE
PDF
No ratings yet
.Python For Beginners SAMPLE
5 pages
The Complete Coding Manual August 2019
PDF
No ratings yet
The Complete Coding Manual August 2019
197 pages
The Complete Coding Manual Vol. 31 2019
PDF
No ratings yet
The Complete Coding Manual Vol. 31 2019
163 pages
The Complete Coding Manual - 5th Edition, 2020
PDF
No ratings yet
The Complete Coding Manual - 5th Edition, 2020
195 pages
Python & C++ Guides - August 2019
PDF
No ratings yet
Python & C++ Guides - August 2019
166 pages
Phython and C++ Learning
PDF
No ratings yet
Phython and C++ Learning
164 pages
Complete Coding Manual - Papercut 2023, 196p
PDF
No ratings yet
Complete Coding Manual - Papercut 2023, 196p
196 pages
The Complete Coding Manual December 2019
PDF
No ratings yet
The Complete Coding Manual December 2019
165 pages
BDM's Coding For Beginners - 2018 UK
PDF
100% (1)
BDM's Coding For Beginners - 2018 UK
164 pages
Python Beginners
PDF
0% (1)
Python Beginners
23 pages
PCL. the Complete C++ & Python Manual 15ed 2023
PDF
No ratings yet
PCL. the Complete C++ & Python Manual 15ed 2023
148 pages
Coding User - Vol 8 2023
PDF
No ratings yet
Coding User - Vol 8 2023
242 pages