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

Python Complete Manual (Coding & Programming)

The essential step-by-step manual to improving your Python coding skills.

Uploaded by

Mustafa K. Salih
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
233 views

Python Complete Manual (Coding & Programming)

The essential step-by-step manual to improving your Python coding skills.

Uploaded by

Mustafa K. Salih
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 165
Sa BDM's Complete 7% Manual Series Python Coding & Programming The essential step-by-step manual to improving your Python coding skills a Black Dog Media PRINT yt | FEATURED INSIDE: Navigating the Start Menu ! Connecting to the Internet ~ % se % gs % ¢ “a ys Ym w “Cy we TTT “ny hls oven s% oF Dox oF ALL rrsesrmarep nconniendeD raceaoox posts rier oven 75% OF conrenrenownerux "sate PueneD NhSxs woneetow TSGENERATED OM THROUGHPYTHON- ‘AuTOWATION a THE LSS, USE PYTHON. 16,000 feititit seetiitt There are over 16,000 Python jobs posted every six months in the UK. A G Python Data Science is thought to become the most sought-after job in the coming years. Google isthe top ‘company for hiring Python developers, closely Followed by Microsoft. (3 %) ] i 95% OF ALL BEGINNER 75% OF ALL PYTHON CODERS START WITH DEVELOPERS USE ‘AND STILLUSE, PYTHON 3, WHEREAS PYTHON AS THEIR, 25% STILL USE THE PRIMARY OR. ‘OUTDATED PYTHON 2 ‘SECONDARY LANGUAGE. ‘VERSION. i PYTHON SKILL-BASED POSITIONS ARE THE 6th: MOST SOUGHT-AFTER JOBS IN THE UK. real Data Science, Blockchain ‘and Machine Learning are the Fastest growing Python coding skills. mun suuun 79% OF ALL PROGRAMMERS USE PYTHON ON A DAY-T0- DAY BASIS, 21% USE ITAS A SECONDARY LANGUAGE. sebirotensom (_ Python in Numbers Cl ¥¢ New York and San Francisco are the top Python developer cities inthe world. % (0) 49% OF WINDOWS. 10 DEVELOPERS USE PYTHON 3 AS THEIR MAIN PROGRAMMING. LANGUAGE. z= Getting Started Why Python? SEMA icens ieee EMME eee Aen uncon sc Pees een kaa eet celkian ete nee Pek estntehceea] yee Rel ei] Gen arte PYTHON POWER ic work, others for mobile platforms and such. So why choose Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee hours, slaving over an overheating heap of circuitry to create something akin to magic. “These pioneers of programming carved their way into anew Frontier, Forging smal routines that enabled the letter to scroll across the screen. Itmay not sound terribly exciting toa generation that’s used to ultra high-definition graphics and open world, multi- player online gaming. However, Fortysomething years agoiit was, blindinaly briliant. Naturally these bedroom coders helped form the Foundations for ‘every piece oF ciital technology we use today. Some went on to, become chief developers for top software companies, whereas ‘thers pushed the available hardware to its limits and Founded the billion pound gaming empire that continually amazes us. Regardless of whether you use an Android device, OS device, PC, Mac, Linux, Smart TV, ames console, MP3 player, GPS device builtin to. car, set-top box ora thousand other connected and ‘smart’ appliances, behind them allis programming. Allthose aforementioned digital devices need instructions to tell them what to do, and allow them to be interacted with, These instructions Form the programming core of the device and that core canbe built using a variety of programming languages. ‘The languagesin use today differ depending on the situation, the platform, the device's use and how the device wil interact with its Raver o0e en |], Seetinsaen! j oid Arrayctrl::chiLdLostrocus() t itleurgor >= 0) Befreshfow cursor): centri tabosteocust): void arraycerLs:Paint(Orave w) {eTIMTNGE Paine Yar({e'= 0; y= < column. cetcoune(); jst) 4 iP CT get ew breaks d Color fe = glend(scolorbisabled, scolorPaper|; Srrenatt a) waileta © cetcount()).( top = cettiner i) Sitebeop > tze-ey) brea fabottom = Freep cettanecy(i)s fern 3° itlen" 0) o0011110 PHOT 1 0 0001 1 i oe reader ctf abwadtn (jai veregrad’+ (is << colum.cetcnune(}: j++) lee catramaratngy int em = cotumiji-margin: colum.Getcount() 1) >= 0) sb 0 0 =o00 00-0 O00 JOO Baca OO 20 oO ‘environment or users. Operating systems, such as Windows, macOS. ‘and such are usually a combination of C++, CH, assembly and some Form of visual-based language. Games generally use C++ whilst web pages can use a plethora of available languages such as HTML, Java, Python and so.on, More general-purpose programming is used to create programs, _apps, software or whatever else you want to cal them. They're ‘widely used across all hardware platforms and suit vitually every ‘conceivable application. Some operate Faster than others and some are easierto learn and use than others. Python isone such general- purpose language. Python is what's known asa High-Level Language, in thatit ‘talks! tothe hardware and operating system using a variety of arrays, variables, objects, arithmetic, subroutines, loops and countless ‘more interactions. Whilst t's nat as streamlined as a Low-Level Language, which can deal directly with memory addresses, call stacks and registers, its benefits that i's universally accessible ~and easy to learn, ite! ravoke. java ae java. ‘ang: reflect.*; lass tavoke { public static void main( string [] args) { "Tikes = class.foryama( arostol 3: vathod'g' Hello, world ») Getting to Know Python Python is the greatest computer programming language ever created. It enables you to fully harness the power of a computer, in a language that’s clean and easy to understand. WHAT IS PROGRAMMING? It helps to understand what a programming language is before you try to learn one, and Python is no different. Let’s take 3 look at how Python came about and how it relates to other languages. i PROGRAMMING RECIPES Programs are like recipes for computers. A recipe to bake a cake could go like this: ‘A programming language {salist of instructions that <8 computer Follows. These Instructions can be as simple 2s displaying yourname cr playing a music file, or ascomplexas building a whole virtual world. Python 3 Add 108 willititres of milk Put 100 grams ofselF raising flour ina bow, ‘Add 100 grams of butter to the bow. ‘Add 100 mililtres oF milk Bake for halFan hour, Ea progamminglanquge conceived in the late 1980s CODE by Guido van Rossum, Just lke a recipe, a program consists of instructions that you Follow centrum wistande & inorder A program tha desrbes ke mightrn ke this Informatica (CW in the Netherlands as asuccessor to 7 flour = 100 ‘riser "loo the ABC language. ae are Guido van Rossum, the father of Python. ‘bow append [flour, butter, mill ) sake..cook (bowl) PROGRAM COMMANDS. ‘You might not understand some of the Python commands like bowl append and cake.cook(bowl) The firsts alist, the second an object; well look at both n this book. The main thing to know is that it’s easy to read commands in Python. Once you learn what the commands do, i's easy to figure outhow a program works. HIGH-LEVEL LANGUAGES Computer languages that are easy to read are known as “high-level” “hiss because they Fy high above the hardware (also referred to as the metal’). Languages that “fly close to the meta," lke Assembly, ‘are known as“Iowrlevel’. Lowrlevel languages commands read abit likethis:meg db ,oxa len equ $ - meg. PYTHON 3 VS PYTHON 2 eee ene Cre A tnee WORLD OF PYTHON Te ee oe Caer Toe ae oy Gre nO ceria Psa aes Posse originally PYTHON 2.X eee On aed Bin Poe Dae ( Getting to Know Python eC ZEN OF PYTHON Python lets you access al the power of a computer ina language that humans can understand. Behind all this is an ethos called "The Zen of Python." This isa collection of 20 software principles that influences the design of the language. Priciplesinclude "Beautiful isbetter than ualy’ and “Simple isbetter than complex." Type import thie into Python and it wll display all the principles. Da eau eet ese nee Seu eu er pene oo erat Cy mae) eee ae Pose re stu. seas PYTHON ee Soeied Re Pts ee ered Se es an oe Pieper acre z= Hello, World ) How to Set Up Python in Windows Windows users can easily install the latest version of Python via the main Python Downloads page. Whilst most seasoned Python developers may shun Windows as the platform of choice For building their code, it’s still an ideal starting point for beginners. INSTALLING PYTHON 3.X Microsoft Wit lows doesn't come with Python preinstalled as standard, soit will be necessary to install it yourself manually ‘Thankfully, it’s an easy process to follow. Stay opengsourwedtrovertowwnuson, ETREEEB Chooins te Cutan con slows sot Sue4l org/downloads/. Look for the button detailing the SUP ‘specify certain parameters, and whilst you may Download inkFor Python 3x Pithoniseglalyupdated chaning stay withthe deft t's agoodhabto adopts, sometimes oot, thelast dit or each Bugfixand update, Therefore, dontworryf” wth ython thankful nstallrsanincude unwanted adatinal Yousee Python 8, ocmore, along sits Python the codelnthis ears On the istsceenavelbl, ersie all bxes are ticked book wi workin an kth Next Dutton J Optional Features oven hon erste an — : ~— FETED lick the Download button for version 3.xand ESTEEM The next page of options include some interesting save the file to your Downloads Folder. When the additions to Python, Ensure the Associate file with Fileis downloaded, double-click the executable and the Python Python, Create Shortcuts, Add Python to Environment Variables, installation wizard will launch. From here, you have two choices: recompile Standard Library and Install for All Users options are Install Now and Customise Installation. We recommend opting for __ticked. These make using Python later much easier. Click Install when the Customise installation link. you're ready to continue. a honoree =) mst a Install Python 3.8.0 (22-bit) J ‘Advanced Options Suc at Nor wa ye th tas ting rene Bitrate | sa Pen nom tin Pram Fs) eB? = You iy need to contr the talon vith SHAPE the Windows authentication notification. Simply cick Yes nd Python wl beginto tal Once the staan s complete, the inal Python wizard page wil lw youtoview the latest release rotes and Flow some onine tutorials Setup was successful i @ python windows FETED Gefore you close the install wizard window however, it's best to click on the link next to the shield detailed Disable Path Length Limit. This wil allow Python to bypass the Windows 260 character imitation, enabling you to execute Python programs stored in deep Folders arrangements. Click Yes again, to authenticate the process, then you can Close the installation window. © Disable pathlength limit Close Windows 10 users can now ind the instal Python SUPT 3.x within the Start button Recently Added section. Theft ink Python 3x (22 wil auch the command ine \ession of Python when cicked (more on that ine moment, To open thelDLE,pelDLE nto Windows start How to Set Up Python in Windows [> Cleng onthe OLE (thon 3 32) nk aun suas the Python Shell, where you can begin your Python programming journey Do ory your version newer ong tsitsython 3x our code vorks side your Python interface BETTER | younow click on the Windows Start button again, {and this time type: CMD, you'll be presented with the Command Prompt link. Clckit to get tothe Windows command line environment, To enter Python within the command line, you need to type: python and press Ente BESET BD) the commandtine version of Python worksin ‘much the same way as the Shell you opened in Step & note the three left Facing arrows (>>>). Whistits a perfectly Fine environment, it's not too user-friendly, so leave the command line for now. Enter: ext () to leave and close the Command Prompt window. Hello, World How to Set Up Python in Linux PYTHON PENGUIN Linux is such a versatile operating system that it’s often difficult to nail down just one-way of doing something. Different distributions go about installing software in different ways, so For this particular tutorial we will stick to Linux Mint, irst you need to ascertain which version of Python 's currently installed in your Linux system. To begin ‘with, drop into a Terminal session from your dstro’s menu, or hitthe CUrtsaltsT keys. davidedavid-mi Help Fle Ect view Search Terminal Nex enter python version tothe Terminal sure ‘screen. You should have the output relating to version 2.x of Python in the display. Most Linux distro come with bboth Python 2 and 3 by default, as there's plenty of code out there stillavalable for Python 2, Now enter: python3 --version. davidedavid-Mi Help File Edt View Search Terminal rT) Python 2.7.15rcl ST rary Paar nour case we have both Python 2 and 3 installed SUP) ‘As long as Python 3.x.x is installed, then the code in ‘ur tutorals wil work t's alvays woth checking to see the tro hasbeen updated ith te latest versions enter sudo apt-ge= update se mudo apt-get upgrade toupdatethe stem avid@avi ating ~ wera bémpubiations.com Once the update and upgrade completes, enter: python’ --version again to see if Python 3x Updated, or even installed. As long as you have Python 3.x, you're running the most recent major version, the numbers after the 3. ingicate patches plus Further updates, Often they/re unnecessary, but they can contain ital new elements, Siar However, fyou want the latest, cating edge ou ‘version, you'll need to build Python from source. Startby entering these commands into the Termin sudo apt-get install build-essential checkinstall sudo apt-get install libreadline-gplv2-dev LibncurseswS-dev libssl-dev libsqlites-dev tk-dev Libgdba-dev Libes-dev Libbe?-dev ‘Open up your Linax web browser and go tothe LEED 2 sron cowrioad poe: hips /wwnpython oral downloads, lk on the Downloads followed bythe button under the Python Source wincow. This opens a downoed dialogue bo, choose alocation, then start the download process. Inthe Terminal goto the Downloads oder Sue? by entering: cd Downloads /. Then unzip the contents of the downloaded Python source code with ta -xvf ython-3..¥ ear (eplacethe Y'suith the version nmbers Solve downloaded), Now enter he new unippes older with: yehon-3¥.¥/ FEED Within the Python Folder, enter: -/eonfiguee audo make altinetall ‘This could take a while, 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 3.xx and Python 2. How to Set Up Python in Linux sudo apt-get install idles For the GUIIDLE, youll need to enterthe following ‘command into the Terminal: The IDLE can then be started with the command: idea, Note, that IDLE runs different version to the one you installed from source. ‘eave david Min: -/Downlone/ython3.72 Youl aso need PP (Pp instal Packages, whichs SUZ O a tool to help you install more modules and extras. Enter: sudo apt-get install python3-pip (Once PIP is installed, check for the latest update with: pip3 install --upgrade pip When complete, close the Terminal and Python 3. willbe available via the Programming section in your distro's menu. ‘ovidadavitin -/Domianerthan372 Installation of Python on macOS can be done in much the same way as the Windows installation, Simply goto the Python ‘webpage, hover your mouse pointer over the Downloads link and select Mac 05 X from the options. You will then be guided to the Python releases for Mac versions, along with the necessary installers For macOS 64-bit for OS X 10.9 and later. wwwbmpubliations.com => Hello, World) Starting Python for the First Time The Raspberry Pi offers one of the best all-round solutions on which to learn and code, in particular, Python. Raspbian, the Pi’s recommended OS, come pre-installed with the latest stable version of Python 3, which makes it a superb coding platform. STARTING PYTHON Everything you need to begin programming with Python is available from the Raspberry Pi desktop. However, if you want, drop into the Terminal and update the system with: sudo apt-get update. ETE ERD With the Raspbian desktop loaded, click on the ERED [oc eample in the Shell enter: 242 3 (DLE). This opens the Python 3 Shell. Windows and Mac users.can__answer: 4. Basically, Python has taken the ‘code’ and produced the Find the Python 3 IDLE Shel from within the Windows Start button relevant output. menu and via Finder ESTEEM The Shelliswhere youcan entercode andseethe [ESSN The Python Shell acts very much lke a calculator, responses and output of code you've programmed since code is basically a series of mathematical, into Python. Tiss akind of sandbox, where you're able to try out interactions with the system. Integers, which are the infinite ‘some simple code and processes. sequence of whole numbers can easly be added, subtracted, rmultiptied and so on, print ("Hello everyone!") While that's very interesting, i's not particularly ‘exiting, Instead, try this: Just enteritinto the IDLE as you've done in the previous steps, (Starting Python for the First Time Cll ‘The Python IDLEs a configurable environment. IF you dont lke the way the colours are represented, then you can always change them via Options > Configure IDLE and clicking on the Highlighting tab. However, we don’t recommend, that, a you won't be seeing the same as our screenshots, Fe nase sncyovepa pec ‘ase the ‘Hello everyone bit. >>> print("Hello everyone!") Hello everyone! >>] You may have noticed the colour cading within Saag the Python IDLE, The colours represent different ‘elements of Python code. They are: Bleck Data and Variables Green-Strings Purple—Functions (Orange Commands Blue User Functions Dark Red —Comments Light Red Error Messages IDLE Colour Coding eee eee] Puple | Funatons | eat) _peineo Blue | Usertnetons [opt area teed [Ener messspas | _syntaesevor TERED estlike most programs available, regardless of the ‘operating system, there are numerous shortcut keys available. We don't have room for them all here but within the ‘Options » Configure IDLE and under the Keys tab, you can see a list of the current bindings. BETISETB) the Pthon DLE isa powerinterface andone that's actually been written in Python using one of the available GU! toolkits. If you want to know the many ins and ‘outs ofthe Shel, we recommend you take 3 few moments to view wurw.docs.python.org/3/library/idle.html, which detalis many oF the IDLE's Features, ED istonoia ) Your First Code [otal ARONA EL R= INL ee UR Volt Mae aye Ke eons RULE MELA a0) everyone!”)’ Function from the previous tutorial. However, let's expand that and look at Nac ECM Mente oys tcc PLAYING WITH PYTHON ‘With most languages, computer or human, it’s all about remembering and applying the right words to the right situation. You're not born knowing these words, so you need to learn them. STEERED "youve closed Python 3 IDLE, reopenit in FETED) 01 con see that instead of the number 4, the Whichever operating system version you prefer. In ‘output isthe 242 you asked to be printed to the the Shell enter the Familiar Following: screen. The quotation marks are defining what's being outputted en tthe DLE Selo pn the tal of 22 youreed nremove Ere 2ust2s predicted, the word Hello appearsin the Ere ou can continue as such, printing 2+2, 46442343 Shell as blve text, indicating output from a string, ‘and so onto the Shell An easier way isto use a Ie fairly straightforward and doesn't require too much explanation. variable, which is something we will cover in more depth later. For Now try now, enter: What you have done here's assign the letters 8 and b two values: 2 and 2. These are now variables, ‘hich can be called upon by Python to output, add, subtract, divide ‘and s0.0n for as ong as their numbers stay the same. Try this: Sia) print (a) print (b) ‘The output of the last step displays the current SUES values of both a and b individually, as you've asked them tobe printed separately. you want to add them up, you can Use the following: print (ax) ‘This code simply takes the values of a and b, adds them together and outputs the result. ‘oe Ear Set Geng Sos neo RES oe TTT Se aso cmt BEPTSED You can play around with different kinds of variables and the Print function. For example, you could assign variables For someone's name: nane="David" Print (name) ‘ie Eat Sah Dg re races sew Pee Epa ee Your First Code ( 0 mm PET) Now let's adda surname: ‘surnane="Hayward” print (surname) ‘You now have two variables containing a first name anda sumame and you can print them independently IF we were to apply the same routine 3s before, using the + symbol, the name wouldn't appear correctly in the output in the Shel. Try it: print (namessurnane) ‘You need a space between the two, defining them as two separate values and not something you mathematically play around with Sel B09 sane Hos He print (name, surname) ‘Alternatively, you can ad the space yourself: InPython 3 you can separate the two variables with a space using a comma’ print (names* “+surname) “The use of the comma is much neater, as you can see. Congratulations, you've just taken your ist stepsinto the wide world of Python wwwubdmpubliations.com Va AVAXHOME? eee UC Ce chs fe oO reese eee oe oe Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction Oy rey 4-43 Pie Ma a meolouls OTT) ONES da lelil tem (ola alo a EL We have everything for all of your needs. Just open https://avxlive.icu => Hello, world ») Saving and Executing Your Code While working in the IDLE Shell is perfectly Fine for small code snippets, it’s not designed For entering longer program listings. In this section you're going to be introduced to the IDLE Editor, where you will be working from now on. EDITING CODE ‘You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the IDLE Editor will allow you to save and execute your Python code. First, open the Python IDLE Shell and when is up, EEp You can see thatthe same colour coding isin place Sue4 click on File > New File. This will open a new window Su? in the IDLE Editor as it is in the Shell, enabling you with Untled a ts name. Thsisthe Python ILE Edtr and within t_tobeter understand whats going on withyour code, However, 0 you can enter the cade needed to create your future programs, execute the code you need to first save it. Press FS and you get a Save...Check box open. BRTEEERD The IDLE Editor is, for all intents and purposes, @ FETED lickon the OK button in the Save box and selecta simple text editor with Python Features, colour destination where youl save all your Python code. ‘coding and so on; much in the same vein as Sublime. You enter The destination can be a dedicated folder called Python or you code as you would within the Shell so taking an example from the can just dump it wherever you like, Remember to keep a tidy drive previous tutorial, enter: though, tohelp you outrin the future print ("Hello everyone!*) |-=eee STEER Enter a name for your code, ‘print hello! For ‘example, and click on the Save button. Once the Python cade is saved it's executed and the output will be detailed in the IDLE Shell n this case, the words ‘Hello everyone!” Tiss how he vst maory of your Python code EAD ive conics tert tote tdvor ners savethe code andlook atthe output nthe Shel Sometimes things will differ, depending on whether you've requested a separate Window, but essential that's the process ts the process we wl Use throughout ths book, unless otherwise stated ie £8 Se) Sein to sor So i \F you open the file location ofthe saved Python code, you can see that itendsin a.py extension, ‘Thisis the default Python file name. Any code you create willbe \whateverpy and any code downloaded from the many Internet Python resource sites wil be py. Just ensure that the code is written For Python 3. — EE Sia) anz >. nane="David" surname="Haywara’ print (name, surname) print (asb) IFyou press 5 now you'llbe asked to save the file, again, as t's been modified from before, Let's extend the code and enter afew examples From the previous tutorial: you ckthe OX button, the fle wllbe SARE servitien vith the nevecde ents and execute, wth the oututin the Shel es nota problem uth ist these Few lines but if you were to edit a larger file, overwriting can become an issue insead us le» Save as rom within the Er tocteate aback. Now create anew file. Close the Editor, and open Sra a new instance (Fle > New File from the Shel), Enter the following and save itas hello py: astPython* bere! e=teoolt print(a, By ©) ‘Youwill use this code in the next tutorial fa valor a: Saving and Executing Your Code Cll Hello, World Executing Code from the Command Line COMMAND THE CODE Using the code we created in the previous tutorial, the one we named hello.py, let's see how you can run code that was made in the GUI at the command line level. f Now you'eat the on Sua? Python. For Python waysiswith thon 2 whist the other uses the yt command python and pes Enter Tis ptyu it the and soon. First though, drop into the command line or Terminalen command line version of the Shell, with the familar three right: Your operating system Facing arrows asthe cursor (=>), EGZD ose EEE icnpeponsapergetertecsey dows users will Raspberry reed to click the Stat button and search For CMD, then click the Line returned search print (a) You can see that it works exactly the same. Go > Utlities > Terminal ee FTE Now enter: exit( to eave the command tine Python session and return you back tot prompt. Enter the Folder where you saved th previous tutorial and list the available files within; hopefully you should see the hellopy file. command ine rom within the same folder as the code you're going to run, enter the Following into the python} hello.py This ill execute the code we created, which to remind yous: as"Python” berier e="ecol!" Print (a, b, ¢) Naturally, since thisis Python 3 cade, using the ‘works when you use the python3 command. IF you lke, try the same with Python 2 by entering python hello.py Executing Code from the Command Line 7 The result of running Python 3 code from the Uae Python 2 command line is quite obvious. Whilst it does error out any way, due tothe dferencesbetweenthe way Python 3 andes the rnecommandover Python 2, the esl [sites we expected: Ung Sublime Fr the moment open the hal py ie. PEPER Since Sublime Text isnt available forthe Raspberry Pi, you're going to temporarily leave the Pifor the ‘moment and use Sublime as an example that you dor't necessarily need to use the Python IDLE. With the hello.py file open, alteritto include the Following: ane=input (*hat is your nane? print (*Hello,”, name! ‘Save the hellopy file and drop backto the ‘command line. Now execute the newly saved code with python hello.py The result willbe the original Python is cool statement, together with the added input command asking you for your name, and displaying it in the command window. C) Hello, world Numbers and Expressions WeSC One es eue eet eae OMI Cet iene nena eee aE Meese hue nice eect cml eT Rol tail eal Anan) 2) Ment Melm an ey 8 ello alan moO Lm IT’S ALL MATHS, MAN ‘You can get some really impressive results with the mathematical powers of Python; as languages, maths is the driving force behind the code. ‘most, ifnot all, programming FETESERD Oper up the Gulversion of Python 3, as mentioned REEMM You can use all the usual mathematical operations: you can use either the Shell or the Editor. For the New Fle) and create a simple variable and ‘rer py-hoplOccare Pon Comscanrnerspy(942)— 8 Lie Eat Fama sere arson He BRTeED Runnin the code will return the line: The value of A 's, 10 nto the IDLE Shell window, which is what we ‘expected. Now, add some ofthe types of comments you'd normally ‘see within code: # Sot the start value of A to 10 ‘an10 4 Print the current value of A Print ("The value of A is,, a) sem ngtatoscom Resave the code and execute it: You can see that the ‘outputin the IDLE Shellisstil the same as before, despite the extra lines being added, Simply put, the hash symbol (#) denotes ane of text the programmer can insert to inform them, and others, of what's going on without the user being aware. x pt Lie 60 St rine ros PEPTSPDD ct's2ssume thatthe variable A that we've created isthe number of livesin a game. Everytime the player des, the value is decreased by 1. The programmer could insert a routine along the lines of: ara print ("You've just lost a life!) print ("You now have", a, “lives lett!*) Whilst we know that the variable is tives, and that the player hasjust lost one, a casual viewer or ‘someone checking the code may not know. Imagine for a moment that the code is twenty thousand lines long, instead of just our seven. You can see how handy comments ae. Sia) eer # Set the start value of A to 10 as10 4 Print the current value of A Print ("The value of A is,", a) # Player lost a life! aca-1 # Inform player, and display current value of A (ives) Print ("You've just lost a life!" Print ("You now have", a, “Lives left!*) Essentially, the new code together with comments could look ike: You can use comments in different ways. For ‘example, Block Comments are a large section of text that detalls what's going on in the code, suchas telling the code reader what variables you're planning on using: # This is the best gane ever, and has been developed by a crack squad of Python experts who haven't slept or washed in weeks. being very smelly, the code at least W works really well. Despite ¢ Using Comments Cll FETED ine comments are comments that follow section (of code. Take our examples from above, instead of inserting the code on a separate line, we could use: asl0 # Set the start value of A to 10 print (*The value of A is,", a) # Print the current value of A ava-i # Player lost a life! print ("You've just lost a life!") print ("You now have", a, “lives left!*) # Inform player, and display current value of A (lives) The comment he hash symbol cn also be used o Sa) comment out sections of code you don’t want to be executed inyour program. or stace you wanted remove thefirstpnt statement you would use # print ("the value of A is,", ab ance Windows Help 7 Set the start vals of A to 10 A F print"The value of A is,", ay) = Player lost’ life! Fnform player. and display current value of 4 (lives) prane("rou've just lost a life!) Print(-You non have", a, “Lives left!) | 2 Prine the current value of A You also use three single quotes to comment ‘outa Block Comment or multitine section of comments. Place them before and after the areas you want to comment For them to work ‘This is the best game ever, and has been developed by a crack equad of Python experts who haven't slept or washed in weeks. Despite being very smelly, the code at least works really well. wmbirotiacsen CE C) Hello, world Working with Variables eee cusCkm Ie Canaries ec ea ta ee es Mer enlatemr eee en hearers uss arte INT Aco RVI 12) VARIOUS VARIABLES ‘You'll be working with the Python 3 IDLE Shell in this tutorial. you haven't already, open Python 3 or close down the previous IDLE Shell to clear up any old code. in some programming languages you're required touse a dollar sign to denote a string, whichis a variable made up of multiple characters, such as a name of a person, In Python ths isn't necessary. For example, inthe Shell enter: nane="David Hayward” (or use your own name, unless you're also called David Hayward). [ie Est Bob Gt ro You've seen previously that variables can be concatenated using the plus symbol between the variable names. In our example we can use: print (name +" % 4 E8tLe). The middle part between the quotations alows us to adda colon and a space, as variables are connected without spaces, so we need to add them manually He 5 Shel Se ans Meso EA PE Ee ee TTT i Se oe the variable inside the brackets. In our example, this would be: ‘type (name). Add a new string variable: titles"Descended from vikings”. You can check the type of variable in use by [ssuing the type () command, placing the name of Youcan aso SUP) combine variables within another vartble. or example, to combine both name andttlevaiablesintoa ne varblewe use oe at Bag ge eo charactersnane +": * + title “Then output the content of the new variable as: print (character) Numbers are stored as different variables: agent ‘Type (age) Which, as we know, are integers. However, youcan't combine both strings and integer type variables in the same command, as you Sia) ‘would a set of similar variables. You need to either turn one into the ‘other or vice versa, When you do try to combine bath, you get an ‘error message: print (name + age) Working with Variables Cll FETTER) This presents abit ofa problem when you want to ‘work with a number that's been inputted by the User, as age + 10 won't work due to being a string variable and an integer. Instead, you need to enter: int(age) + 10 ‘This wil TypeCast the age string into an integer that can be worked with. ea gt for mee ttn, This @ process known as TypeCasting. The Python BaD s": print (character + * is * + str(age) +“ years old.") ‘or you can use: print (character, "is", age, "years old. Notice again that in the last example, you don't need the spaces between the words in quotes asthe commas treat each argument to print separately >>> print (mane + age) Traceback (most recent call Last): Pile s rine (name + age) Typetrrer: Can't convert “int* object to str inplicitly S8Sprane (character #32"! + str(age) +" years eld David Hayward: Descended fron Viking years lg. So>iprane (character, "is", age, "yt years ole center: ‘Another example of TypeCasting s when you ask for input From the user, such as a name. for example, Anput ("How old are you? *) All data stored from the Input command is stored as string variable. ‘le Et shel Debug ptons worden Hp on Fa7 (aetaol Oct 9 2018. TTY ie ow SES ae yous 8 feclast ste" ior ESTEE The use of TypeCasting is also important when dealing with Floating point arithmetic; eemember: ‘numbers that have a decimal point in them. For example, enter: shixe=19.99 Now enter type (shixrt) and youtl see that Python has allocated the number as a float, because the value contains 8 decimal point. 2 (Gataalt, Oct 19 2014, TBST tion linay acpyrsghes Merits” or “License fo Soe Secantee) clase fieat'> \When combining integers and Floats Python usually converts the integer to a float, but should the reverse ever be appliedit's worth remembering that Python doesn't return the exact value. When converting afloat to an integer, Python will always round down to the nearest integer, called truncating; in our case instead of 19.99 t becomes 19. ‘le Eat Shel Debug Options indows Help python 38-3 (aetaale, Get 19 2aTe, TBST Hope Scopytahe™. Seresits” of "Licensed" f DB enareciates | Sseinecanire) e eal wwwubdmpubliations.com Hello, World ED ietonois) User Input We've seen some basic user interaction with the code from a few of the examples Senn ere maecteec en Maree C camel from the user then store and present it. USER FRIENDLY ‘The type of input you want from the user will depend greatly on the type of program you're coding. For example, a game may ‘ask For a character's name, whereas a database can ask For personal details. BRTEEERD i’snotalready, open the Python 3 IDLE shell, FETESE DD Now that we have the user's name stored in a and start a New Filein the Editor Let's begin with couple of variables we can call therm up whenever ‘something realy simple, enter: we want, print ("Hello") prineon icons» trutnae, surname" bape you're wel tay.) BD Sccrivecuetecoseodersuatenyno EERE sun tnecateandyoucnseeasighiiethe SUE? doubt suspected, in the IDLE Shell the program will SUP) full stop after the surname follows a blank space. 2skfor our fst name sorngitarthe erable frstname, alowed Toelmnats tat we can ada 3 plssininstead ofthe comma byyoursuname; ab tres in tsonn varabieuinme) thecode ©] as ver trate oe PRTESEER You don't always have to include quoted text within the input command. For example, you can ask the User their name, and have the inputin the line below: Print ("Hello. What's your name?") nane=input () le Edt Farmat sun Qptions windows Help Drint(Helle. What's your none?) anesinput() The code from the previous tp soften regarded SUES as being alittle neater than having a lengthy amountof text inthe npucomman, but t's nota ue tat’ stin ‘stone, 0 do as you lke in these situations. Expanding on the code, try this Print ("Halt! Who goes there?") nane=input () EPID 2 good start toa text adventure game, pechape? [Now you can expand on it and use the raw input From the user to flesh out the game alittle: Af name=="Davia' + print ("Welcone, good sir. You may pass.”) elee: print (*I know you not. Prepare for battle!") userinput py -/home/pi/Documnents/Pythan Code/ust (User input Cll ‘What you've created here is aconeition, which we will cover soon. In short, we're using the input from the user and measuring itagainsta condition, So, ifthe user enters David as their name, the guard wil allow them to pass unhindered, Else if they enter a name other than David, the guard challenges them to fight. FETED ust2s you learned previously, any input froma user is automaticaly a string, so you need to apply 2 “TypeCastin order to turn itinto something else. This creates some interesting additions to the input command. For example: # Code to calculate rate and distance print ("Input a rate and a distance) PEPPER Toinalise the rate and distance code, we can add: Aistance = float (input (Distance: ” print ("Time:™, (distance / rate)) Save and execute the code and enter some numbers. Using the Float(input element, we've told Python that anything entered isa Floating point number rather than a wwwbdmpubteatonscon QE) Hello, World Creating Functions Near seh uses eg ur ee alma nee rl eed Teme ECU eet eee intents oTaen Encl ek Caneel nee FUNKY FUNCTIONS ‘Afunction is a command that you enter into Python to do something. It's little piece of selFcontained code that takes data, ‘works ont and then returns the result. BETISEDD snot ust data thata function works on. they can [RIBEMB You can pass variables through functions in much do all manner of useful things in Python, such as the same manner, Let's assume you want the sort data, change items from one format to another and checkthe numberof lettersin a person's surname, you could use the following lenath or type of items. Basically, afunctionisashort word that's code (enter the text editor For this example) followed by brackets. For example, len(), ist) or type). _— _ count=1en (nane} print ("Your surnane has", count, “letters in att} Press F5 and save the code to execute it. ESTEE A function takes data, usuallyavariable, workson — RTBEVFBBS pytinon hastens of Functions built nt it, ar too it depending on what the Function is programmed many to get into in the limited space available here. todo and,eturns the end value. The data being worked on goes However, to view thelist of built-in functions available to Python 3, inside the brackets, so if you wanted to know how many letters navigate to wwru.docs python.org/3/ibraryffunctions html, These ‘arein the word antidisestablishmentarianism, then you'denter: __are the predefined functions, but since users have created many en (*antidisestablishnentarianien") andthe number 28 more, they/re not the only ones available. ‘would return, ED vvbsmpubicavonscom FETED “citional functions can be added to Python through modules. Python has a vast range of ‘modules available that can cover numerous programming duties. “They add functions and can be imported as and when required. For ‘example, to use advanced mathematics Functions enter: import math (Once entered, you have access to all the Math module Functions. ee) ( Creating Functions BETTS) 0 vse a function from a module enter the name of the module Followed by afull stop, then the name of the Function. For instance, using the Math module since you've just imported it into Python, you can utlse the square root function, Todo so, enter: math. sqrt (26) You can see that the code i presented as module function(data}. [reer S258 =z FORGING FUNCTIONS ie uae ao ear uee Uae ea perenne Co tnt eee Me eee! FR ose Fie > New File to enter the etor t's CIB LPAI mo ne tier Be Cee Roi ans STEP 2 Peter feet Hello (name) fRetio ("david") gta Oe ee og eu eee eee me ren eee ere Eeisienies rom Heli tnzore Fall STEP 4 ete nea ay hello to David This is how modules and functions work ese ea eget wt os Cnet) Hello, World Conditions and Loops eo Ce Se SU Cee MIs nn R CULAR Cl Con ea Ue entre tRenMrset ent Naf or eat they could be the number of lives left in a game or just displaying a countdown. TRUE CONDITIONS Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let's start then by checking if something is TRUE, then doing something else if itisn’t. FERRED 2c create ancw Python program that wll ak the user toinput a word, then checkitto se if i's 2a fouretter word or not, Start with File > New File, and begin with the input variable: word=input ("Please enter a four-letter word: *) Now wecan create a new variable, then use the en SUEP2 function and pass the word variable through it to ‘get the total numberof letters the user has just entered: word-input ("Please enter a four-letter word: *) ED wmbsmpubicaonscom Now you can use an fstatementto check ifthe ‘word length variable is equal to four and print a Friendly conformation ifit applies to the rule: word-input (“Please enter a four-letter word: ") word_length=len (word) if word_length == 4: print (word, “is a four-letter word. well done.’ ‘The double equal sign (==) means check iF something is equal to something ese. Sse} The colon atthe end of Fels Python that this statements true do everything after the colon that'sindented, Nest, move the cursor backto the beginning of the Editor word-input (“Please enter a four-letter word: ") word_length=len (word) if word_length Siar print (word, “is a four-letter word. Well done.) else: print (word, "is not @ four-letter word.") PRTESIRD ess 5 and save the code to execute it. Enter ‘a fourletter word inthe Shell to begin with, you should have the returned message that it's the word is four letters Now press FS again and rerun the program but this time enter a five-letter word, The Shell wil display that it’s not a four-letter word LOOPS. Conditions and Loops Cll added a condition for three/letter words: a four-letter word: *) if word length print (word, one." elif word_length == 3 print (word, “ie a three-letter word. Try again.) else print “is a four-letter word. Well (word, “is not @ four-letter word.*) es ees Ler se eeu block of code a number of times, usually STEP 1 eee Pen Maree ie ant ae aes ie pee eee er CS ee Brera Iie atis seated th the support of a condition. oa COP eg em ear ees Cee, ee ees STEP 4 Ce as Geena Tos Hello, World Python Modules MASTERING MODULES ‘Think of modules as an extension that’s imported into your Python code to enhance and extend its capabilities. There are countless modules available and as we've seen, you can even make your own EED Seistgont te butintcion niin econ BEBE teresutsaeorinte Ouse ote are Python scripts that are imported, such as import math Close down the IDLE Shell and drop into a command prompt or Terminal session. At an elevated admin command prompt, enter: pip install pygane Fe yeeE Some modules, especially on the Raspberry Pi ary PIP installation requires an elevated status are included by default, the Math module being a ue itinstalling components at different locations prime example. Sadly, other modules aren't always avalable. A good Windows users can search for CMD via the Star button and right: ‘example on non-Pi platforms isthe Pygame module, which contains click the result then click Run as Administrator. Linux and Mac users ‘many Functions to help create games. Try: import pygame, can use the Sudo command, with sudo pip install package. {lose the command prompt or Terminal and relaunch the IDLE Shel. When you now enter: import pygane, the module willbe imported into the code ‘without any problems Youll find that most code downloaded or copied from the internet will contain a module, mainstream of Unique, these are usually the source of errorsin execution due to them being missing The modules contain the extra code needed to achieve a certain result within your awn cade, as ‘we've previously experimented with. For example: import random Brings in the code from the Random Number Generator module, ‘You can then use this module to create something ike: for 4 in range(10) + print (random.randint (1, 25)) ‘with the code to display more or less, and from agreat or lesser This code, when saved and execute, will display ten random numbers from 1 to 25. You can play around range. For example: import random for i in range(25) print (random.randint (1, 100)) C Python Modules Cll Multiple modules can be imported within your code. Sia) Toextend our example, use import random import math for I in range(S): print (random.randint (1, 25)) print (math.pi) {a The resuisasbing of randor ruber followed illite by the value of Pias pulled From the Math module using the print(math.pi) function. You can also pull in certain Rants fom a mode by sng the fom andor commands, Siena from random import xandint for i in range(S) : print (randint (1, 25)) B BETeEREOR Tishelps create a more streamlined approach to programming, You can also use import module*, ‘which will mport everything defined within the named module, However, it's often regarded as a waste of resources but it works ‘nonetheless. Finally, modules can be imported as aliases: import math asm print (mpi) OF course, adding comments helps to tell thers what's going on, tinny Cin snitmmenlpienatinbe BA - a x wmcirosiacsen CIE Hello, World Python Errors It goes without saying that you'll eventually come across an error in your code, where Python declares it’s not able to continue due to something being missed out, wrong or simply unknown. Being able to identify these errors makes For a good programmer. DEBUGGING Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important thing is to keep looking, experimenting and testing. Eventually your code will be bug free. FETEEERD Codeisntasftuid asthe written word, no matter NEB Thankfully Python ishelpful when t comesto how good the programming language i. Python is displaying error messages. When you receive an certainly easier than most languages but even its prone to some red text from the IDLE Shell, it wil define the error itself annoying bugs. The most common are typos by the user and whilst along with the line number where the error has accurred. Whilst in ‘ea5y to find in simple dozertine code, imagine having to debug _the IDLE Editor thisis@ litle daunting for lots of code; text editors rmult-thousand ine cade. help by including line numbering, eo. EEE D the mostcommonoferrorsisthe typo, aswe've EWM syntaxerrors are probably the second most mentioned. The typos ae often atthe command common errors youl come across as a programmer. level: mstyping the print command for example. However, they also Evenif the speling is corect, the actual command tsa is wrong. ‘occur when you have numerous variables, all of which have lengthy _InPython 3 ths often occurs when Python 2syntaxes are applied names. The best advice Isto simply go through the code and check The most annoying of these isthe print Function. Python 3 we use your speling, Brin( "words", whereas Python? ses print “words” ue Eat Gay Gens nds Ea ‘oe Got Sh Dave Stes aces te Sia) print (balanced_check (input ())) esky brackets are also a nuisance in programming errors, especially when you have something like: Remember that For every (there must be an equal number of 9 feterene =) , 2 enaacter tn reference ty) ack sppenlcheracter) C Python Errors Cll FETED excellent way to check your code step-bystep isto use Python Tutors Visualise web page, found atwwrw-pythontutor.cony\visualize.htmlsmode=edit. Simply paste your code into the editor and click the Visualise Execution button to run the code line-by-tne. This helps to clear bugs and any misunderstandings. There are thousand of online Python resources, SUES code snippets and lengthy discussions across Forums cnhow bes to achieve something Wnt 99 percent oes good Code, dot avaysbe lured nto copying and pasting random code ite youredor Moe often than nt eon workand the worst parts thatyou hover earn anything jor ony Supe aepsn eet nea Obes nee PPE ircents are a nasty part of Python programming that alot of beginners fall foul of Recal the Flop From the Conditions and Loops section, where the colon means. ‘everything indented folowing the statement is to be executed as long asit's true? Missing the indent, or having too much of indent, will come back with an error. © Peed anieresiek = Planing makes for good code. Whistle old Ss) ‘school, it's a good habit to plan what your code wild before iting downto ype ot Usk the varibles that De sed andthe meres to; then we ou 2 scp fray user interaction or outputs Purely out of interest, the word debugging in computing terms comes from Admiral Grace Hopper, who back in the 40s was working on a monolithic Harvard "Markl electromechanical computer. According to legend Hopper Found a moth stuck ina relay, thus stopping the system from ‘working, Removal ofthe moth was hence called debugging. entrain

You might also like