contentsineasysteps.com/wp-content/uploads/2013/07/python-toc+ch1.pdf · introducing python python...

22
Contents 1 3 2 Getting started 7 Introducing Python 8 Installing Python on Windows 10 Installing Python on Linux 12 Meeting the interpreter 14 Writing your first program 16 Employing variables 18 Obtaining user input 20 Correcting errors 22 Summary 24 Performing operations 25 Doing arithmetic 26 Assigning values 28 Comparing values 30 Assessing logic 32 Examining conditions 34 Setting precedence 36 Casting data types 38 Manipulating bits 40 Summary 42 Making statements 43 Writing lists 44 Manipulating lists 46 Restricting lists 48 Associating list elements 50 Branching with if 52 Looping while true 54 Looping over items 56 Breaking out of loops 58 Summary 60

Upload: others

Post on 17-Jun-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

Contents

1

3

2

Getting started 7

Introducing Python 8Installing Python on Windows 10Installing Python on Linux 12Meeting the interpreter 14Writing your first program 16Employing variables 18Obtaining user input 20Correcting errors 22Summary 24

Performing operations 25

Doing arithmetic 26Assigning values 28Comparing values 30Assessing logic 32Examining conditions 34Setting precedence 36Casting data types 38Manipulating bits 40Summary 42

Making statements 43

Writing lists 44Manipulating lists 46Restricting lists 48Associating list elements 50Branching with if 52Looping while true 54Looping over items 56Breaking out of loops 58Summary 60

Page 2: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

5

6

4

7

Defining functions 61

Understanding scope 62Supplying arguments 64Returning values 66Using callbacks 68Adding placeholders 70Producing generators 72Handling exceptions 74Debugging assertions 76Summary 78

Importing modules 79

Storing functions 80Owning function names 82Interrogating the system 84Performing mathematics 86Calculating decimals 88Telling the time 90Running a timer 92Matching patterns 94Summary 96

Managing strings 97

Manipulating strings 98Formatting strings 100Modifying strings 102Converting strings 104Accessing files 106Reading and writing files 108Updating file strings 110Pickling data 112Summary 114

Programming objects 115

Encapsulating data 116Creating instance objects 118Addressing class attributes 120Examining built-in attributes 122Collecting garbage 124Inheriting features 126Overriding base methods 128Harnessing polymorphism 130Summary 132

Page 3: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

8

9

Processing requests 133

Sending responses 134Handling values 136Submitting forms 138Providing text areas 140Checking boxes 142Choosing radio buttons 144Selecting options 146Uploading files 148Summary 150

Building interfaces 151

Launching a window 152Responding to buttons 154Displaying messages 156Gathering entries 158Listing options 160Polling radio buttons 162Checking boxes 164Adding images 166Summary 168

Developing applications 169

Generating random numbers 170Planning the program 172Designing the interface 174Assigning static properties 176Initializing dynamic properties 177Adding runtime functionality 178Testing the program 180Freezing the program 182Deploying the application 184Summary 186

Index 187

10

Page 4: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

PrefaceThe creation of this book has been for me, Mike McGrath, an exciting personal journey in discovering how Python can be used today for procedural and object-oriented programming, to develop applications and to provide online functionality. Example code listed in this book describes how to produce Python programs in easy steps – and the screenshots illustrate the actual results. I sincerely hope you enjoy discovering the exciting possibilities of Python and have as much fun with it as I did in writing this book.

In order to clarify the code listed in the steps given in each example I have adopted certain colorization conventions. Components of the Python programming language are colored blue, programmer-specified names are red, numeric and string data values are black, and comments are green, like this:

# Write the traditional greeting.greeting = ‘Hello World!’print( greeting )

Additionally, in order to identify each source code file described in the steps, a colored icon and file name appears in the margin alongside the steps:

For convenience I have placed source code files from the examples featured in this book into a single ZIP archive. You can obtain the complete archive by following these easy steps:

l1 Browse to http://www.ineasysteps.com then navigate to the “Free Resources” tab and choose the “Downloads” section

l2 Find “Python in easy steps” in the “Source Code” list, then click on the hyperlink entitled “All Code Examples” to download the archive

l3 Next, extract the MyScripts and MyProjects folders to your home directory (such as C:\ ) and copy all contents of the htdocs folder to your web server’s documents directory

l4 Now, follow the steps to call upon the Python interpreter and see the output

PY

script.py page.html image.gif

Page 5: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

Welcome to the exciting

world of the Python

programming language.

This chapter demonstrates

how to install Python and

create your first program.

Introducing Python

Installing Python on Windows

Installing Python on Linux

Meeting the interpreter

Writing your first program

Employing variables

Obtaining user input

Correcting errors

Summary

8

10

12

14

16

18

20

22

24

Getting started1

Page 6: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

8G

etti

ng s

tart

ed

Programming languages that group blocks by indentation are said to adhere to the “offside rule” – a pun on the offside rule in soccer.

• Beautifulisbetterthanugly

• Explicitisbetterthanimplicit

• Simpleisbetterthancomplex

• Complexisbetterthancomplicated

• Readabilitycounts

Introducing PythonPythonisahigh-level(human-readable)programminglanguagethatisprocessedbythePython“interpreter”toproduceresults.Pythonincludesacomprehensivestandardlibraryoftestedcodemodulesthatcanbeeasilyincorporatedintoyourownprograms.

ThePythonlanguagewasdevelopedbyGuidovanRossuminthelateeightiesandearlyninetiesattheNationalResearchInstituteforMathematicsandComputerScienceintheNetherlands.Pythonisderivedfrommanyotherlanguages,includingC,C++,theUnixshellandotherprogramminglanguages.Today,PythonismaintainedbyacoredevelopmentteamattheInstitute,althoughGuidovanRossumstillholdsavitalroleindirectingitsprogress.

ThebasicphilosophyofthePythonlanguageisreadability,whichmakesitparticularlywell-suitedforbeginnersincomputerprogramming,anditcanbesummarizedbytheseprinciples:

Discover all the latest Python news online at www.python.org

AsPythonisintendedtobehighlyreadableitusesEnglishkeywordsfrequentlywhereotherlanguagesmayusepunctuation.Mostsignificantly,itusesindentationtogrouptogetherstatementsintocode“blocks”whereasotherlanguagesmayusekeywordsorpunctuationforthispurpose.Forexample,inthePascalprogramminglanguageblocksstartwiththekeywordbeginandendwiththekeywordend,andintheCprogramminglanguageblocksareenclosedwithincurlybrackets({ }braces).GroupingblocksofstatementsbyindentationissometimescriticizedbyprogrammersfamiliarwithlanguagesthatgroupbypunctuationbuttheuseofindentationinPythoncertainlyproducescodethathasanunclutteredvisuallayout.

Page 7: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

9

Python 3.x is not backward compatible with Python 2.7.

…cont’d

SomeofPython’skeydistinguishingfeaturesthatmakeitanattractivechoiceoflanguageforthebeginnerinclude:

• Python is free–isopensourcedistributablesoftware

• Python is easy to learn–hasasimplelanguagesyntax

• Python is easy to read –isunclutteredbypunctuation

• Python is easy to maintain–ismodularforsimplicity

• Python is “batteries included” –providesalargestandardlibraryforeasyintegrationintoyourownprograms

• Python is interactive–hasaterminalfordebuggingandtestingsnippetsofcode

• Python is portable –runsonawidevarietyofhardwareplatformsandhasthesameinterfaceonallplatforms

• Python is interpreted–thereisnocompilationrequired

• Python is high-level–hasautomaticmemorymanagement

• Python is extensible–allowstheadditionoflow-levelmodulestotheinterpreterforcustomization

• Python is versatile –supportsbothprocedure-orientatedprogrammingandobject-orientatedprogramming(OOP)

• Python is flexible–cancreateconsoleprograms,windowedGUI(GraphicalUserInterface)applications,andCGI(CommonGatewayInterface)scriptstoprocesswebdata

AsdevelopmentofPythoncontinuesnewerversionsarereleasedaswithmostsoftware.Currently,thefinal2.7versionisout,withastatementofextendedsupportforthisend-of-liferelease.The2.xbranchwillseenonewmajorreleasesafterthat.

The3.xbranchisunderactivedevelopmentandhasalreadyseenseveralstablereleases.Thismeansthatallrecentstandardlibraryimprovements,forexample,areonlyavailableinPython3.x.ThisbookdescribesanddemonstratesfeaturesofthepresentandthefutureofPythonwiththelatest3.xversion.

Python is named after the British television comedy series “Monty Python’s Flying Circus” – you may encounter references to this in the Python documentation.

Page 8: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

10G

etti

ng s

tart

ed

Support for MSI installer files is included with all recent versions of Windows and free from microsoft.com/downloads – search for “Windows Installer”.

Installing Python on WindowsBeforeyoucanbeginprogramminginthePythonlanguageyouneedtoinstallonyourcomputerthePythoninterpreterandthestandardlibraryoftestedcodemodulesthatcomesalongwithit.Thisisavailableasafreedownloadathttp://python.org/downloadForWindowsusersthereisanMSIinstalleravailableinboth32-bitand64-bitversions.

l1 Launchawebbrowserthennavigatetopython.org/downloadanddownloadtheappropriateinstallerversionforyoursystem–inthisexampleit’saninstallerfilesnappilynamed“Python3.3.2WindowsX86-64MSIInstaller”

l2 Whenthedownloadcompletesruntheinstallerandchoosewhethertoinstallforallusersorjustyourself,thenclicktheNextbuttontoproceed

l3 Now,acceptthesuggesteddefaultinstallationlocation,whichwillbeadirectoryonyourrootC:\drivenamed“Python”andversionnumber–inthisexampleit’sadirectoryatC:\Python33forPythonversion3.3.2

Installers for Mac OS X in both 32-bit and 64-bit versions are also available for download at python.org/download

Page 9: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

11

The letter V in the command must be uppercase. Ensure the command responds with the version number before proceeding to the examples in this book.

…cont’d

l4 ClicktheNextbuttontoproceed,thenbesuretoselectthefeatureto“Addpython.exetoPath”

Ensure that all features in the Customize Python dialog are selected for installation – as illustrated here.

l5 ClickonNexttobegincopyingfilesontoyourcomputerthenclicktheFinishbuttontocompletetheinstallation

l6 ToconfirmPythonisnowavailablerestartyourcomputer,launchaCommandPromptwindow(runcmd.exe)andentertheexactcommandpython -V–thePythoninterpretershouldrespondwithitsversionnumber

Page 10: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

12G

etti

ng s

tart

ed

Don’t remove the default 2.7 version of Python from your system in case some applications depend upon it.

Installing Python on LinuxLinuxdistributionswill,typically,includePythonbutgenerallyhavethe2.7versionastheirdefault.Fordevelopmentonthe3.xbranchofPythonreleasesyouwillprobablyhavetoinstallthelatestreleasealongsidethedefaultversion.

l1 LaunchaterminalwindowandpreciselyenterthiscommandtorevealtheinstalleddefaultPythonversionpython -V

l2 Next,preciselyenterthiscommandtorevealthedefaultversionofaPython3.xbranch,ifanyisinstalledpython3 -V

l3 Now,launchyourLinuxsystem’spackagemanagertoseeifalaterPythonversionisavailableforinstallation–forexampleusetheSoftwareCenteronUbuntusystems

Consult your Linux distro’s documentation for further help on installing Python.

Page 11: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

13

You may also, optionally, install IDLE for Python 3.3 but this is not an absolute requirement as the Python programming examples in this book are all created in a plain text editor such as Nano.

…cont’d

l4 Searchfor“python”inthepackagemanagertoseewhatPythonversionsandcomponentsareinstalledoriflaterversionsareavailableforinstallation

You can now use the command python3.3 to have that version of the Python interpreter process your programs.

l5 Finally,installthelatestversionofthePython3.xbranch–inthiscaseit’sPython3.3

l6 ToconfirmthelatestversionofPythonisnowavailableonyourcomputerlaunchaTerminalwindowandpreciselyenterthisexplicitcommandpython3.3 -V

Page 12: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

14G

etti

ng s

tart

ed

Meeting the interpreterThePythoninterpreterprocessestext-basedprogramcodeandalsohasaninteractivemodewhereyoucantestsnippetsofcodeandisusefulfordebuggingcode.Python’sinteractivemodecanbeenteredinanumberofways:

• FromaregularCommandPrompt–simplyenterthecommandpythontoproducethePythonprimaryprompt>>>whereyoucaninteractwiththeinterpreter

• FromtheStartMenu–choose“Python(commandline)”toopenawindowcontainingthePython>>>primaryprompt

• FromtheStartMenu–choose“IDLE(PythonGUI)”tolaunchaPythonShellwindowcontainingthePython>>>primaryprompt

Page 13: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

15

Spaces in expressions are ignored so 8+4 can be also be entered with added spaces for clarity – as illustrated here.

“IDLE” is an acronym for Python’s Integrated DeveLopment Environment but has limited features so is not used to demonstrate examples in this book.

…cont’d

IrrespectiveofthemethodusedtoenterinteractivemodethePythoninterpreterwillrespondinthesamewaytocommandsenteredatits>>>primaryprompt.Initssimplestformtheinterpretercanbeusedasacalculator.

l1 EnterPythoninteractivemode,usinganymethodoutlinedopposite,thentypeasimpleadditionandhitReturntoseetheinterpreterprintoutthesumtotal

ThePythoninterpreteralsounderstandsexpressionssoparenthesescanbeusedtogivehigherprecedence–thepartoftheexpressionenclosedwithinparentheseswillbecalculatedfirst.

l2 Next,atthePythonpromptenteranexpressionwiththreecomponentswithoutspecifiynganyprecedenceorder

l3 Now,atthePythonpromptenterthesameexpressionbutaddparenthesestospecifyprecedenceorder

Interactive mode is mostly used to test snippets of code and for debugging code.

Page 14: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

16G

etti

ng s

tart

ed

The directory created at C:\MyScripts will be used to contain all Windows examples in this book.

Don’t use a word processor to create program files as they add format information to the file.

Writing your first programPython’sinteractivemodeisusefulasasimplecalculatorbutyoucancreateprogramsformoreextensivefunctionality.APythonprogramissimplyaplaintextfilescriptcreatedwithaneditor,suchasWindows’Notepad,thathasbeensavedwitha“.py”fileextension.Pythonprogramscanbeexecutedbystatingthescriptfilenameafterthepythoncommandataterminalprompt.

Thetraditionalfirstprogramtocreatewhenlearninganyprogramminglanguagesimplyprintsoutaspecifiedgreetingmessage.InPython,the print() functionisusedtospecifythemessagewithinitsparentheses.Thismustbeastringofcharactersenclosedbetweenquotemarks.Thesemaybe“ ”doublequotemarksor‘ ’singlequotemarks–butnotamixtureofboth.

l1 OnWindows,launchanyplaintexteditorsuchastheNotepadapplication

l2 Next,preciselytypethefollowingstatementintotheemptytexteditorwindowprint( ‘Hello World!’ )

l3 Now,createanewdirectoryatC:\MyScriptsandsavethefileinitashello.py

l4 Finally,launchaCommandPromptwindow,navigatetothenewdirectoryandpreciselyenterthecommandpython hello.py –toseethePythoninterpreterrunyourprogramandprintoutthespecifiedgreetingmessage

PY

hello.py

Page 15: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

17…cont’d

TheproceduretocreatethetraditionalfirstPythonprogramisidenticalonLinuxsystemstothatonWindowssystems.Itis,however,importanttobeaware,onanyplatform,wheredifferentversionsofPythonareinstalled;youmustusethecorrectcommandtocallupontheparticularPythoninterpreterrequired.ThisisespeciallyimportantonLinuxsystemsthatoftenshipwiththePython2.7versioninstalledastheirdefault.Thismeansthatthecommandpythonwillassumeyouwanttocallthatinterpreter.WherePython3.3isinstalled,andyouwanttocallthatparticularinterpretertoprocessascript,youmustusethecommandpython3.3toexplicitlycalluponthatversion’sinterpreter.

l1 OnLinux,launchanyplaintexteditorsuchastheNanoapplication

l2 Next,preciselytypethefollowingstatementintotheemptytexteditorwindowprint( ‘Hello World!’ )

l3 Now,savethefileinyourhomedirectoryashello.py

All further examples in this book are illustrated on Windows (simply because that platform has most users) but they can also be created and executed on Linux.

l4 Finally,launchaTerminalwindowandnavigatetoyourhomedirectoryandpreciselyenterthecommandpython3.3 hello.py – toseethePythoninterpreterrunyourprogramandprintoutthespecifiedgreetingmessage

PY

hello.py

Page 16: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

18G

etti

ng s

tart

ed

Programming languages that require variable types to be specified are alternatively known as “strongly typed” whereas those that do not are alternatively known as “loosely typed”.

Employing variables

String data must be enclosed within quote marks to denote the start and end of the string.

Inprogramming,a“variable”isacontainerinwhichadatavaluecanbestoredwithinthecomputer’smemory.Thestoredvaluecanthenbereferencedusingthevariable’sname.Theprogrammercanchooseanynameforavariable,exceptthePythonkeywordslistedontheinsidefrontcoverofthisbook,anditisgoodpracticetochoosemeaningfulnamesthatreflectthevariable’scontent.

DatatobestoredinavariableisassignedinaPythonprogramdeclarationstatementwiththe=assignmentoperator.Forexample,tostorethenumericvalueeightinavariablenamed“a”:

a = 8

Thestoredvaluecanthenbereferencedusingthevariable’sname,sothatthestatementprint( a )willoutputthestoredvalue8.Thatvariablecansubsequentlybeassignedadifferentvalue,soitsvaluecanvaryastheprogramproceeds–hencetheterm“variable”.

InPythonprogramming,avariablemustbeassignedaninitialvalue(“initialized”)inthestatementthatdeclaresitinaprogram–otherwisetheinterpreterwillreporta“notdefined”error.

Multiplevariablescanbeinitializedwithacommonvalueinasinglestatementusingasequenceof=assignments.Forexample,toinitializevariablesnamed“a”,“b”and“c”eachwithanumericvalueofeightlikethis:

a = b = c = 8

Alternatively,multiplevariablescanbeinitializedwithdifferingvaluesinasinglestatementusingcommaseparators.Forexample,toinitializevariablesnamed“a”,“b”and“c”withnumericvaluesofone,twoandthreerespectivelylikethis:

a , b , c = 1 , 2 , 3

Some programming languages, such as Java, demand you specifywhat type of data a variable may contain in its declaration.Thisreserves a specific amount of memory space and is known as“static typing”.Pythonvariables,on theotherhand,havenosuchlimitation and adjust the memory allocation to suit the variousdata values assigned to their variables (“dynamic typing”). Thismeans they can store integer whole numbers, floating-pointnumbers,textstrings,orBooleanvaluesofTrueorFalseasrequired.

Page 17: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

19…cont’d

Optionally,commentscanbeaddedtoyourPythonscriptstodescribethepurposeofstatementsorsectionsofcodeifprecededbya# hashcharacter.Everythingfollowingthe# hashcharacteruptotheendofthelineisignoredbythePythoninterpreter.Itisusefultocommentyourcodetomakeitspurposecleartoothersorwhenrevisitingthecodeyourselflater.

l1 Launchaplaintexteditorthendeclareandinitializeavariable–thendisplayitsstoredvalue# Initialize a variable with an integer value.var = 8print( var )

l2 Next,assignanewvalueanddisplaythatstoredvalue# Assign a float value to the variable. var = 3.142print( var )

l3 Nowassignadifferentvalueanddisplaythestoredvalue# Assign a string value to the variable.var = ‘Python in easy steps’print( var )

l4 Finally,assignanothervalueanddisplaythestoredvalue# Assign a boolean value to the variable. var = Trueprint( var )

l5 SavethefileinyourscriptsdirectorythenopenaCommandPromptwindowthereandruntheprogram–toseethestoredvaluesoutputastheprogramproceeds

PY

var.py

Multi-line comments can be added to a script if enclosed between triple quote marks “““...””” .

Page 18: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

20G

etti

ng s

tart

ed

Notice that the prompt string ends with a space that is displayed in output – so the user entry is separated from the colon when typed in.

Obtaining user inputJustasadatavaluecanbeassignedtoavariableinaPythonscript,auser-specifiedvaluecanbeassignedtoavariablewiththePython input()function.Thisacceptsastringwithinitsparenthesesthatwillprompttheuserforinputbydisplayingthatstringthenwaittoreadalineofinput.

Userinputisreadasatextstring,evenwhenit’snumeric,andcanbeassignedtoavariableusingthe=assignmentoperatorasusual.Likeanyothervariablevalue,thatassignedbyausercanbedisplayedbyspecifyingthevariablenametotheprint()function–toreferencethatvariable’sstoredvalue.

Multiplevaluestobedisplayedcanbespecifiedtotheprint()functionasacomma-separatedlistwithinitsparentheses.

l1 Launchaplaintexteditorthendeclareandinitializeavariablebyrequestinguserinput# Initialize a variable with a user-specified value.user = input( ‘I am Python. What is your name? : ‘ )

l2 Next,displayaresponsemessageconfirmingtheinputbyreferencingthestoredusername# Output a string and a variable value. print( ‘Welcome’ , user )

l3 Now,savethefileinyourscriptsdirectorythenopenaCommandPromptwindowthereandrunthisprogram–enteryournamethenhitReturntoseetheresponsemessageincludeyourname

PY

input.py

Page 19: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

21…cont’d

You can explicitly specify a newline to the end parameter, for example end=’!\n’ adds both an exclamation mark and a newline character.

Whenmultiplevaluesarespecifiedtotheprint()functionitwilldisplayeachvalueinoutputseparatedbyasinglespacebydefault.Analternativeseparatorcan,however,bespecifiedbyaddingasepparametertothecomma-separatedlist.Forexamplesep = ’*’ willdisplayeachvalueinoutputseparatedbyanasteriskcharacter.

Outputdisplayedbytheprint()functionwill,bydefault,addaninvisible\n newlinecharacterattheendofthelinetoautomaticallymovetheprintheadtothenextline.Analternativelineendingcan,however,bespecifiedbyaddinganendparametertothecomma-separatedlist.Forexample,end = ’!’ willdisplayeachvalueinoutputthenendthelinewithanexclamationmark.

l4 Editthescripttodeclareandinitializeasecondvariablebyrequestingmoreuserinput# Initialize another variable with a user-specified value.lang = input( ‘Favorite programming language? : ‘ )

l5 Next,displayaresponsemessageconfirmingtheinputbyreferencingthestoredlanguagename–andspecifyingacustomseparatorandacustomlineending# Output a string and a variable value. print( lang , ‘Is’ , ‘Fun’ , sep = ‘ * ‘ , end = ‘!\n’ )

l6 Now,savethefileoncemore,thenopenaCommandPromptwindowthereandrunthisprogramagain–enteryournameandaprogramminglanguagethenhitReturntoseetheresponsemessageincludeyouruserinput

You can include space characters around the separator character for clarity – like those shown around the asterisk character in this example.

Page 20: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

22G

etti

ng s

tart

ed

Programming errors are often called “bugs” and the process of tracking them down is often called “debugging”.

Typically, the syntax error indicator points to the next character after an omission in the code.

Correcting errorsInPythonprogrammingtherearethreetypesoferrorthatcanoccur.Itisusefultorecognizethedifferenterrortypessotheycanbecorrectedmoreeasily:

• Syntax Error–occurswhentheinterpreterencounterscodethatdoesnotconformtothePythonlanguagerules.Forexample,amissingquotemarkaroundastring.Theinterpreterhaltsandreportstheerrorwithoutexecutingtheprogram

• Runtime Error–occursduringexecutionoftheprogram,atthetimewhentheprogramruns.Forexample,whenavariablenameislatermis-typedsothevariablecannotberecognized.Theinterpreterrunstheprogrambuthaltsattheerrorandreportsthenatureoftheerrorasan“Exception”

• Semantic Error–occurswhentheprogramperformsunexpectedly.Forexample,whenorderprecedencehasnotbeenspecifiedinanexpression.Theinterpreterrunstheprogramanddoesnotreportanerror

Correctingsyntaxandruntimeerrorsisfairlystraightforward,astheinterpreterreportswheretheerroroccurredorthenatureoftheerrortype,butsemanticerrorsrequirecodeexamination.

l1 Launchaplaintexteditorthenaddastatementtooutputastringthatomitsaclosingquotemarkprint( ‘Python in easy steps )

l2 SavethefileinyourscriptsdirectorythenopenaCommandPromptwindowthereandrunthisprogram–toseetheinterpreterreportthesyntaxerrorandindicatethepositioninthecodewheretheerroroccurs

PY

syntax.py

Page 21: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

23…cont’d

l3 Insertaquotemarkbeforetheclosingparenthesistoterminatethestringthensavethefileandruntheprogramagain–toseetheerrorhasbeencorrected

l4 Next,beginanewprogrambyinitializingavariablethentrytooutputitsvaluewithanincorrectvariablename–toseetheinterpreterreportaruntimeerrortitle = ‘Python in easy steps’print( titel )

l5 Amendthevariablenametomatchthatinthevariabledeclarationthensavethefileandruntheprogramagain–toseetheerrorhasbeencorrected

l6 Now,beginanewprogrambyinitializingavariablethentrytooutputanexpressionusingitsvaluewithoutexplicitprecedence–toseeapossiblyunexpectedresultof28num = 3print( num * 8 + 4 )

l7 Addparenthesestogrouptheexpressionas3 * ( 8 + 4 )thensavethefileandruntheprogramagain–toseetheexpectedresultof36,correctingthesemanticerror

PY

runtime.py

PY

semantic.py

Details of how to handle runtime Exception errors in your script code are provided on page 74.

Page 22: Contentsineasysteps.com/wp-content/uploads/2013/07/Python-TOC+Ch1.pdf · Introducing Python Python is a high-level (human-readable) programming language that is processed by the Python

24G

etti

ng s

tart

ed

• Pythonisahigh-levelprogramminglanguagethatisprocessedbythePythoninterpretertoproduceresults

• Pythonusesindentationtogroupstatementsintocodeblocks,whereotherlanguagesusekeywordsorpunctuation

• Python2.7isthefinalversionofthe2.xbranchofdevelopmentbutthe3.xbranchhasthelatestimprovements

• WindowsuserscaninstallPythonwithanMSIinstallerandLinuxuserscaninstallPythonwiththeirpackagemanager

• ThePythoninterpreterhasaninteractivemodewhereyoucantestsnippetsofcodeandisusefulfordebuggingcode

• APythonprogramissimplyatextfilecreatedwithaplaintexteditorandsavedwitha“.py”fileextension

• ThePythonprint()functionoutputsthestringspecifiedwithinitsparentheses

• Stringvaluesmustbeenclosedbetweenquotemarks

• WheremultipleversionsofPythonareinstalledonthesamesystemitisimportanttoexplicitlycallthedesiredinterpreter

• APythonvariableisanamedcontainerwhosestoredvaluecanbereferencedviathatvariable’sname

• APythonvariablecancontainanydatatypebutmustbegivenaninitialvaluewhenitisdeclared

• ThePythoninput()functionoutputsthestringspecifiedwithinitsparenthesesthenwaitstoreadalineofinput

• Syntaxerrorsduetoincorrectcodearerecognizedbytheinterpreterbeforeexecutionoftheprogram

• Runtimeerrorsduetoexceptionsarerecognizedbytheinterpreterduringexecutionoftheprogram

• Semanticerrorsduetounexpectedperformancearenotrecognizedbytheinterpreter

Summary