Learn to Use Python

download Learn to Use Python

of 176

Transcript of Learn to Use Python

  • 8/10/2019 Learn to Use Python

    1/176

    Lesson 1, Getting Started

    Preface

    What you will learn

    This is the first in a series of online tutorial lessons designed to teach you how toprogram using the Python scripting language.

    There is something for just about everyone here. Beginners start at the beginning,and experienced programmers jump in further on. You simply need to enter theseries of lessons at the point that best fits your prior programming knowledge.

    Beginners

    f you don!t know anything about programming, these lessons will take you fromground "ero to the outer#space habitat of the modern object#oriented computerprogrammer.

    Programmers

    f you already know how to program, these lessons will teach you how to programusing the Python scripting language.

    Python programmers

    f you already know how to program using Python, these lessons will teach you how

    to use the Python scripting language to take advantage of the ever expanding $avaprogramming environment, without the re%uirement to learn how to program in$ava.

    Java programmers

    f you already know how to program using $ava, these lessons will teach you how touse Python for rapid prototyping of $ava programs.

    Overall

    &hen you complete this series of tutorial lessons, you will have completed the

    e%uivalent of three or four semesters of computer programming studies at thecommunity college level.

    Prerequisites

    There are only two prere%uisites'

    (nowledge of how to use a computer on the web.

  • 8/10/2019 Learn to Use Python

    2/176

    ) strong desire to learn how to write computer programs.

    How to use a computer on the web

    The fact that you are reading this page probably means that you already know howto use a computer on the web. !m not talking about rocket science here. am

    talking about knowing how to download and install software from specified web sites,and how to execute that software offline.

    Windows would be handy

    )lthough not absolutely necessary, it would also be very handy for you to haveaccess to, and know how to use *icrosoft &indows. The programming skills that am going to teach you are applicable to a broad range of operating systems.+owever, will use *icrosoft &indows as my teaching platform, so you will need tobe able to follow instructions explained in &indows jargon.

    Strong desire to learn

    This should be self#explanatory, but just in case it isn!t, will make a couple ofcomments in this regard.

    Dont e!pect a miracle to happen

    imply reading these lessons won!t cause you to experience a miraculoustransformation that will cause recruiters to start waving money at you.

    Practice" practice" and more practice

    am going to provide you with a lot of information, but you will also need to put your

    brain in gear and write a lot of programs to make the information stick in your brain.-ery few people become expert musicians without a lot of practice. imilarly, veryfew people become expert programmers without a lot of practice.

    o, if you want to learn to program, plan to spend a lot of time in front of yourcomputer, not just reading, but programming as well.

    Why #se Python$

    &ith so many programming environments available, why did select Python

    /irst of all, it!s free. like that. You won!t need to invest an arm and a leg just to getstarted. )ll you will need to do is go to http'00www.python.org0 and download thesoftware. Yes, -irginia, there really is a anta 1laus, and he lives on the &eb.

    What is Python$

    You might also want to visit http'00www.python.org0doc0ummary.html , which iswhere extracted the following'2Python is an interpreted, interactive, object#oriented programming language...

    http://www.python.org/http://www.python.org/doc/Summary.htmlhttp://www.python.org/doc/Summary.htmlhttp://www.python.org/
  • 8/10/2019 Learn to Use Python

    3/176

    Python combines remarkable power with very clear syntax. t has modules, classes,exceptions, very high level dynamic data types, and dynamic typing. There areinterfaces to many system calls and libraries, as well as to various windowingsystems 3455, *otif, Tk, *ac, */16. 7ew built#in modules are easily written in 1 or188. Python is also usable as an extension language for applications that need aprogrammable interface.

    The Python implementation is portable' it runs on many brands of 974, on&indows, :;, ;0

  • 8/10/2019 Learn to Use Python

    4/176

    the big picture of what your program is intended to accomplish without gettingbogged down in detail.

    Snea)ing up on OOP

    &ith Python, you can 2sneak up2 on object#oriented programming concepts. You

    don!t have to deal with the object#oriented nature of the language on the first day, orfor a long time, for that matter. 3&ith $ava, you can!t write even the simplestprogram without encountering a need to understand object#oriented programmingconcepts.6

    Python has an interactive mode

    The interactive mode makes it easy to try new things without the burden of the edit-compile-execute cycle of other programming languages such as $ava. nteractivemode is a very friendly environment for persons in the learning stages of a language.

    Python has a non(interactive mode

    ;nce you know that something works properly, it is very easy to "put it in a can"soto speak, and then execute it as a script. This lets you execute it without retyping itevery time.

    Python combines interactive and non(interactive modes

    This combination gives you the ability to use previously written script files whileworking in the interactive mode. 9sing this approach, you are able to minimi"e yourinteractive typing effort while still writing and testing large Python programs ininteractive mode.

    Small core" large library

    Aike $ava, Python has a small compact core and a large, extensible library. Thus,much of what you will need to do has already been written and tested for you. Yourtask will be to write the code to glue those library components together, and to writenew capabilities on an as#needed basis.

    'ets Write a Program

    Download and install the software

    The first step is to go to http'00www.python.org0with your web browser. :ownload,

    and install the Python software using the download link that you will find there.

    !m going to assume that either you already know how to do this, or you can get helpfrom a friend. n other words, !m not going to try to explain how to download andinstall the Python software.

    Starting the programming environment

    http://www.python.org/doc/current/lib/lib.htmlhttp://www.python.org/http://www.python.org/doc/current/lib/lib.htmlhttp://www.python.org/
  • 8/10/2019 Learn to Use Python

    5/176

    )s mentioned earlier, all of my instructions will be based on the use of Pythonrunning on my &indows 7T operating system. believe that those instructions willalso be directly applicable to &indows C and &indows D.

    +owever, as mentioned earlier, you have many choices for using Python. f you arerunning on some other platform, you will need to translate my instructions from

    &indows jargon into the jargon of your platform.

    *nough tal)+ lets begin

    /ind the Startbutton on the task bar on your &indows desktop. elect

    Start/Programs/Python x.y

    where x.y is the version of Python that you have downloaded and installed. )t thetime of this writing, have version 5.C.< installed on my computer, and the selectionshows on the menu as Python ,-..

    What do you see$

    &hen you make this selection, you should see a menu having at least the followingfour options

    :AE 3Python F96

    Python 3command line6

    Python *anuals

    9ninstall Python

    /he python manuals

    :on!t be bashful about reading the manuals. There is a wealth of informationcontained there, including a short, to#the#point tutorial written by the author ofPython, Fuido van @ossum.

    /he library reference

    ) good way to get a feel for the breadth and power of Python is to select Python&anualsfrom the menu and then select the 'ibrary 0eferencelink. 3The Aibrary@eferenceis also available online as of the time of this writing.6

    *ost of what you see there probably won!t mean much to you at this point in time,but hopefully will be familiar territory after you complete this course.

    1D'* 2Python 3#14

    &hen select the first item on the menu on my &indows 7T machine, get an errormessage about a missing :AA file. But when click ;(, the message goes away andeverything seems to work anyway.

    http://www.python.org/doc/current/lib/lib.htmlhttp://www.python.org/doc/current/lib/lib.htmlhttp://www.python.org/doc/current/lib/lib.htmlhttp://www.python.org/doc/current/lib/lib.html
  • 8/10/2019 Learn to Use Python

    6/176

    This selection brings up a window entitled "Python Shell."This is one of theinteractive programming environments available with Python on *icrosoft &indows.

    What does it loo) li)e$

    &hen you bring up the Python hell, you should see something like /igure 5at the

    top of the window. 37ote that inserted some line breaks to force the text to fit inthis narrow page format.6

    What is a 3#1$

    F9 is an acronym for Fraphical 9ser nterface. This window is a F9. t can beused for interactive Python programming.

    To make it go away when you are finished, simply click the button in the upper#rightcorner that is labeled with an 4.

    /he Python 2command line4 selection

    &hen select the second item in the menu mentioned above, get essentially thesame thing as the F9, but in a 2black screen2 window commonly referred to as a:; box, a console, a command#line window, or whatever you choose to call it.

    /he command(line window

    This window can also be used for interactive Python programming in much the sameway that the Python hell can be used. Each has some practical advantages anddisadvantages.

    To make this screen go away, hold down the 1trl key and press the G key 31trl#"6.

    Then press the Enter key. 3You can also click the 4 in the upper right#hand corner.6

    5our first Python program

    You can use either of these windows to write and execute your first Python program.

    Hello World in Python

    )s has become the custom in programming circles, we will make our first Pythonprogram one that displays 2+ello &orld2 on the computer screen. &e will write andexecute it interactively.

    /he Python prompt 666

    The three right#angle brackets that you see in both of the interactive screens 3HHH6make up the Python interactive prompt. &hen the cursor is blinking to the right ofthat prompt, you can enter a Python programming statement interactively.

    'ets do it

    http://www.dickbaldwin.com/python/Pyth0001-fig01.htmhttp://www.dickbaldwin.com/python/Pyth0001-fig01.htm
  • 8/10/2019 Learn to Use Python

    7/176

    Type the following text to the right of the Python prompt and press the Enter key'print 2+ello &orld

    f all goes well, your interactive Python screen should then look something like /igure

  • 8/10/2019 Learn to Use Python

    8/176

  • 8/10/2019 Learn to Use Python

    9/176

    Let's Do Numbers

    PrefaceThis document is part of a series of online tutorial lessons designed to teach you howto program using the Python scripting language.

    Something for everyone

    There is something for just about everyone here. Beginners start at the beginning,and experienced programmers jump in further along. Aearn to Program usingPython' Aesson 5, Fetting tartedprovides an overall description of this onlineprogramming course.

    1ntroduction

    Because this course is designed for beginning programmers, am going to take itslow and easy for the first few lessons. *y discussion will be informal, and will bedesigned to get you familiar and comfortable with the Python interactiveprogramming environment. Aater on, will get a little more formal.

    % programmable calculator

    am going to start out by showing you how to use Python as a programmablecalculator. n the process, will introduce you to some programming concepts, such

    as operatorsthat will explain in a more formal way in subse%uent lessons.

    'ets Program

    Start the interactive Python environment

    The first thing that you need to do is to start the interactive programmingenvironment. f you have forgotten how to do that, see Aesson 5.

    There are two ways to start the interactive Python environment from the &indowsStartmenu. You can either'

    elect :AE 3Python F96, or elect Python 3command line6.

    Either way, the interactive programming environment should look something like/igure 5when it starts running'

    The 666that you see on the last line is the Python interactive prompt, which willrefer to simply as the prompt.

    http://www.developer.com/article/1,,625901,00.htmlhttp://www.developer.com/article/1,,625901,00.htmlhttp://www.dickbaldwin.com/python/Pyth0004-fig01.htmhttp://www.developer.com/article/1,,625901,00.htmlhttp://www.developer.com/article/1,,625901,00.htmlhttp://www.dickbaldwin.com/python/Pyth0004-fig01.htm
  • 8/10/2019 Learn to Use Python

    10/176

    Program comments

    Before we go any further, need to introduce you to the concept ofprogramcomments.

    n programming jargon, a comment is text that you insert into the program that is

    intended for human consumption only. 1omments provide a %uick and easy form ofdocumentation. They are ignored by the computer and are intended to explain whatyou are doing.

    How useful are comments$

    1omments aren!t terribly useful when doing interactive programming. Presumablyyou already know what you and doing and don!t need to explain it to yourself usingcomments.

    +owever, comments are very useful when you are writing scripts that you will storein files and use again later after you have forgotten how you did what you did.

    n these lessons, will use comments occasionally to explain what am doing foryour benefit, even in interactive mode.

    What is the comment synta!$

    )ccording to The Python @eference *anual 2) comment starts with a hashcharacter 3M6 ... and ends at the end of the physical line.

    /igure

  • 8/10/2019 Learn to Use Python

    11/176

    Everything that appears on a line without a prompt is output from the interpreter.3You didn!t type it. The interpreter produced it, so it was output.6

    What was the input in this case$

    Your input was the expression

  • 8/10/2019 Learn to Use Python

    12/176

    operators, and

    parentheses

    3 will defer a discussion of variables until a subse%uent lesson.6

    What are operators$

    f you have ever used a hand calculator, you already know what operators are. Theplus sign is an operator in the expression shown in /igure K.

    n programming jargon, operators are said to operate on operands.

    What are operands$

    n /igure K, the < is the left operand and the C is the right operand of the plusoperator.

    #nary and binary operators

    7ormally, operators are said to be either unaryor binary.

    ) unary operator has only one operand while a binary operator has two operands.

    Some can be either

    ome operators, such as the minus sign, can be either unary or binary operators.

    n its unary mode with a single operand, a minus sign is usually a sign changingoperator, while in its binary mode with two operands, a minus sign is usually a

    subtraction operator.

    )ll of the operators discussed in this lesson are being used as binary operators.

    Some arithmetic operators

    Python has numerous operators. You can find a complete list of operators in thePython @eference *anual.

    /or the time being, we will concentrate on the follow arithmetic operators'

    The addition operator, 8

    The subtraction operator, # The multiplication operator, N

    The division operator, 0

    The modulus operator, ?

    /igure Lshows some examples of using these operators that probably won!t presentany surprises to you.

    http://www.dickbaldwin.com/python/Pyth0004-fig06.htmhttp://www.python.org/doc/current/ref/operators.htmlhttp://www.dickbaldwin.com/python/Pyth0004-fig07.htmhttp://www.dickbaldwin.com/python/Pyth0004-fig06.htmhttp://www.python.org/doc/current/ref/operators.htmlhttp://www.dickbaldwin.com/python/Pyth0004-fig07.htm
  • 8/10/2019 Learn to Use Python

    13/176

    f you add < and C, you get L. f you subtract C from

    1nteger division

    The next result, shown in /igure D, may surprise you until explain it. n this case,

    we are dividing the integer 3whole number6 < by the integer C producing an integerresult.

    7ormally, a hand calculator would tell you that the answer is >.J, but that is not aninteger result. @ather, it is a decimal fraction.

    )s you can see in /igure D, Python tells you that the result of dividing the integer .

    0emember long division$

    Think back to when your second grade teacher taught you how to do long division

    with whole numbers. he told you that if you divide < by C, you get a %uotient of >and a remainder of C. ;r, if you divide .

    7ote that in the first expression, changed the numerator from < to 3 couldhave left off the "ero, but adding the "ero makes the decimal point easier to spot6.

    http://www.dickbaldwin.com/python/Pyth0004-fig08.htmhttp://www.dickbaldwin.com/python/Pyth0004-fig09.htmhttp://www.dickbaldwin.com/python/Pyth0004-fig10.htmhttp://www.dickbaldwin.com/python/Pyth0004-fig08.htmhttp://www.dickbaldwin.com/python/Pyth0004-fig09.htmhttp://www.dickbaldwin.com/python/Pyth0004-fig10.htm
  • 8/10/2019 Learn to Use Python

    14/176

    This caused Python to perform decimal arithmetic instead of integer arithmetic,producing the decimal %uotient value of >.J.

    did essentially the same thing to the denominator in the second expression,producing the same result.

    3rouping terms with parentheses

    &hat is the result of evaluating the expression shown in /igure 55

    Try it on your hand calculator. 3You will probably need to use an 4 instead of an N toindicate multiplication.6 *y hand calculator gives an answer of I

  • 8/10/2019 Learn to Use Python

    15/176

    n the first expression, forced Python to perform the addition first by placing theaddition inside the parentheses. This produced an intermediate value of D when thesub#expression inside the parentheses was evaluated. The remaining part of theoverall expression was then evaluated by multiplying the intermediate value by J,producing a result of I

  • 8/10/2019 Learn to Use Python

    16/176

    small percentage of potential Python users, !m not going to provide any of thedetails. f this is something that interests you, see an example at this 9@A.

    Programming *rrors

    ometimes, you may make an error and enter an expression that can!t be

    evaluated. n this case, you will get an error message. ) typical error message isshown in /igure 5K.

    Briefly, this error message means that the Python interpreter doesn!t know how toadd the value @to the value .a. will discuss error messages in more detail in asubse%uent lesson. just wanted to show you a programming error here at thebeginning.

    &ono spaced font

    You may have noticed that the font that used in /igure 5K is different from the fontthat have been using in previous examples.

    n the previous examples, have used a font that allows me to put more informationon each line in order to accommodate a narrow page format. +owever, that fontdoes not allocate the same amount of space to each character. 7arrow charactersconsume less space than wider characters. 3That explains why am able to getmore text on each line.6

    ?ote the pointer

    n this case, needed a font that allocates the same amount of space for eachcharacter so that the little pointer 3O6 below the awill be in the correct spot. Thispointer is Python!s way of giving you a hint as to where the error occurred.

    0eview

    5. Python programming comments are ignored by the computer, True or /alse

    %ns; /rue- Programming comments are used for program documentation and areintended for human consumption.

  • 8/10/2019 Learn to Use Python

    17/176

    J. The output produced by the Python interactive system appears on a line withouteither of the prompts mentioned above, True or /alse

    %ns; /rue-

    C. f you enter an expression at the prompt and press the *nterkey, the result of

    evaluating the expression will be displayed on the next line without a prompt, True or/alse

    %ns; /rue"unless the expression can!t be evaluated, in which case an errormessage will appear.

    K. 1omputer programs are composed of expressions, which are made up ofstatements, True or /alse

    %ns; :alse- $ust the reverse is true. Programs are made up of statements, whichare composed of expressions.

    L. n the following expression, . :escribe how to force Python division to produce a decimal result.

    %ns; @epresent either the numerator, the denominator, or both as a decimal value,appending a decimal point and a > if necessary to cause it to be represented as adecimal value 3actually, the decimal point alone is sufficient, but the "ero makes thedecimal point easier to detect visually6.

    55. The modulus operator is used to produce the %uotient in division, True or /alse

    %ns; :alse, the modulus operator is used to produce the remainder.

  • 8/10/2019 Learn to Use Python

    18/176

    5

  • 8/10/2019 Learn to Use Python

    19/176

    This lesson provides an introduction to the use of variables, and the re%uired syntaxof the identifiers used to represent variables.

    What 1s % Aariable

    )s the name implies, a variable is something whose value changes over time.

    % pigeonhole in memory

    )s a practical matter, a variable is a pigeonhole in memory, which has a nickname,where you can store values.

    You can later retrieve the values that you have stored there by referring to thepigeonhole by its nickname 3identifier6. You can also store a different value in thepigeonhole later if you desire.

    1s Python strongly typed$

    ;ne of the main differences between Python and programming languages such as$ava is the concept of type.

    n strongly-typed languages like $ava, variables not only have a name, they have atype. The type determines the kind of data that you can store in the pigeonhole.

    It is probably more correct to say that the type determines thevalues that you can store there and the operations (addition,subtraction, etc.) that you can perform on those values.

    Python is not strongly typed

    ;ne of the characteristics that makes Python easier to use than $ava is the fact that,with Python, you don!t have to be concerned about the type of a variable. Pythontakes care of type issues for you behind the scenes.

    Declaration of variables

    )nother difference between Python and $ava is that with $ava, you must declarevariables before you can use them. :eclaration of variables is not re%uired withPython.

    &ith Python, if you need a variable, you simply come up with a name and start usingit as a variable.

    Dangerous curves ahead>

    &ith this convenience comes some danger. You can only have one variable with thesame name within the same scope 3 will discuss scope in a subse%uent lesson6.

    Dont use the same name for two variables

  • 8/10/2019 Learn to Use Python

    20/176

    &ith Python, if you unintentionally use the same name for two variables, the first willbe overwritten by the second. This can lead to program bugs that are difficult to findand fix.

    % more subtle danger

    ) more subtle danger is that you create a variable that you intend to use more thanonce and you spell it incorrectly in one of those uses. This can be an extremelydifficult problem to find and fix. will illustrate what mean by this later with asample program.

    0ules for 1dentifiers

    The name for a variable must follow the naming rules for identifiers that you will findin the Python Language Referenceat this 9@A.

    3ive me the rules in plain *nglish

    The notation used in the Python Language Referenceto define the naming rules is alittle complicated, so will try to interpret it for you.

    believe that the Aanguage @eference is saying that identifiers must begin witheither a letter or an underscore character. /ollowing that, you can use an unlimitedse%uence of letters, numbers, or underscore characters.

    7ase is significant

    The letters can be uppercase or lowercase, and case is significant. n other words,the identifier %!is not the same as the identifier a.

    %ny old digit will do

    7umbers can be any of the digit characters between and including > and .

    Watch out for underscore characters

    recommend that you not use the underscore character unless you know exactlywhy you are using it. n some situations, the use of the underscore character has aspecial meaning. will discuss some of those situations in subse%uent lessons.

    'ets Program

    Start the interactive Python environment

    The first thing that you need to do is to start the interactive programmingenvironment. f you have forgotten how to do that, see Aearn to Program usingPython' Aesson 5, Fetting tarted.

    7reate and use some variables

    http://www.python.org/doc/current/ref/identifiers.htmlhttp://www.developer.com/lang/other/article.php/625901http://www.developer.com/lang/other/article.php/625901http://www.python.org/doc/current/ref/identifiers.htmlhttp://www.developer.com/lang/other/article.php/625901http://www.developer.com/lang/other/article.php/625901
  • 8/10/2019 Learn to Use Python

    21/176

    The interactive fragment shown in /igure 5'

    HHH xK M create and populate xHHH yC M create and populate yHHH x8y M add x to y and display the sum55HHH

    :igure ,

    1reates two variables named !and y,

    Populates them by assigning values of K and C to them respectively

    )dds their values together to produce the sum value of 55.

    Bac) to the pigeonholes

    9sing the informal jargon from an earlier paragraph, two pigeonholes are establishedin memory and are given nicknames of !and y.

    /he assignment operator

    nteger values of Cand .are stored in the two pigeonholes using the assignmentoperator 36.

    The use of the assignment operator in this fashion causes the value of its rightoperand to be stored in the pigeonhole identified by its left operand.

    What is an operand$

    3f you don!t recogni"e the use of the term operand, see an earlier lesson for anexplanation.6

    n this case, the right operands of the two variables are literal numeric values.

    The left operands of the two variables are the nicknames identifying the two memorylocations that constitute the variables named !and y.

    %ddition of variables

    Then, in the third line of code, the values are retrieved from each pigeonhole and

    added together. The result of the addition 3556 is displayed as output from theexpression !=y.

    %ssigning the same value to several variables

    Python allows you to assign the same value to several variables, causing them tocome into existence 3begin to occupy memory6 at the same time if necessary.

  • 8/10/2019 Learn to Use Python

    22/176

    1onsider the interactive fragment shown in /igure M assign 5> to severalvariablesHHH a8b8c M add them togetherI>HHH abcHHH

    :igure to each of them.

    They are then added together, in the second line of code, to produce an output valueof I>.

    %ssign different values

    The boldface statement in the fourth line assigns the value of to the same threevariables, replacing what was previously there with the new value. )gain they areadded together, this time producing an output value of K>.

    /ype considerations

    n most modern programming systems, values having fractional parts, such asI.5J5C are commonly referred to as floating pointtypes. 3This terminology comesfrom the fact that the decimal point can float back and forth from left to right.6

    imilarly, whole number values are commonly referred to as integertypes. 3Theseare values with no decimal parts, such as, 2 have @whole apples.26

    %dvantages and disadvantages

    Each type has advantages and disadvantages relative to the other.

    /he range of values

    /or example, in some systems, the total range of values for an integer type isrestricted to the set of whole numbers between #I

  • 8/10/2019 Learn to Use Python

    23/176

    )lthough the range of an integer type will be different on different systems, it willalmost always be less than the range of a floating point type on the same system.

    Speed

    +owever, on some systems integer arithmetic is performed much faster than floating

    point arithmetic. ;n those systems, if speed is important, using integers may bemore attractive than using floating point types.

    :loating point provides greater range

    ;n most systems, the floating point type provides a much greater range in terms ofthe values that can be maintained and used for arithmetic. /or example, a particularsystem might be capable of representing the following two values as well as millionsof values in between'

    >.>>>>>>>>>>IIIIIIIIII>>>>>>>>>>.>

    Sometimes range is important" and sometimes not

    ometimes range is important, and sometimes it isn!t. +owever, as mentionedabove, in many cases this greater range is obtained at some sacrifice in arithmeticspeed relative to integer types.

    %ppro!imate results

    )lso, as will explain in the Reviewsection, floating point arithmetic often producesapproximate results instead of exact results.

    &hile approximate results might he ;( for scientific calculations, they might not be;( for financial calculations.

    %utomatic type handling in Python

    n strongly-typedlanguages such as $ava, it is the responsibility of the programmerto make certain that types are handled correctly. /or example, it is often notpossible to store a floating point value into a variable previously declared to be forthe storage of integer values. There is a very strong possibility that it simply won!tfit.

    Python takes care of the routine type issues for us automatically.

    1onsider the interactive code fragment shown in /igure I.

    HHH xCHHH yKHHH x8y55

  • 8/10/2019 Learn to Use Python

    24/176

    HHH xC.CCCCCHHH yK.KKKKKHHH x8y5

  • 8/10/2019 Learn to Use Python

    25/176

    HHH C8K55HHHF=>>

    :igure .

    3)s indicated earlier, variable names cannot begin with a digit. They must beginwith either a letter or an underscore character 6

    The result shown in /igure C is generally self#explanatory. The little pointer points tothe !in the intended variable name, ,!, reporting that this is a syntax error.

  • 8/10/2019 Learn to Use Python

    26/176

    Aariable name spelling errors

    The interpreter assumes that you know what you are doing, and won!t help youavoid spelling errors in variable names 3unless the spelling error produces an illegalvariable name6.

    % serious potential programming problem

    7ow will illustrate a very subtle and serious potential problem. 1onsider theinteractive code fragment in /igure K. The programmer expected to get a finalanswer of 5K8C

  • 8/10/2019 Learn to Use Python

    27/176

    &eaningful variable names

    ome meaningful variable names follow. 7ote the judicious use of upper and lowercase to visually break up the variable name into separate words. This is a namingconvention that has become very popular, particular among $ava programmers.

    my9pperAimit your9pperAimit

    the;verhead@ate

    the/inalPrice

    0emember" case is significant in variable names

    The variable named &y#pper'imit is not the same variable as the one namedmy#pper'imit.

    )s a practical matter, it is poor programming practice do distinguish between twovariable names simply by using subtle differences in case. This will almost surelylead to spelling errors later.

    0eview

    5. ) variable is the same as a constant, True or /alse

    %ns; :alse- The value of a variable is intended to change during the execution ofthe program. The value of a constant 3which haven!t discussed yet6 is not intendedto change.

  • 8/10/2019 Learn to Use Python

    28/176

    K. -ariable names can begin with the digit characters, True or /alse

    %ns; :alse- -ariable names must begin with a letter or underscore character.

    L. The underscore character should be used liberally in variable names, True or/alse

    %ns; :alse- You should use the underscore character in a variable name only whenyou know exactly why you are using it. ;therwise, you may create conflicts withspecial system variables whose names contain underscore characters.

    D. &rite a simple program that illustrates case sensitivity in the names of variables.

    %ns; )n example of such a program is shown in /igure L.

    HHH a45> M this is one variableHHH )x M this is a different variableHHH a48)xI>HHH

    :igure

    7ote that the names of the two variables have the same letters, but different case.The fact that the two variables are different variables is illustrated by the fact thateach is assigned a different value. The sum of the two variables demonstrates thatthe two variables contain different, and correct, values.

    1ontrast the above result with the program in /igure D where a variable whose namecontains the same letters and the same case is used.

    HHH ax5>HHH axHHH ax8axJ>HHH

    :igure I

    )ll this program accomplishes is the assignment of two different values to the samevariable. t then adds the variable to itself using its current value of producing aresult of J> 3instead of I> as in the previous example6.

    . Explain the use of the assignment operator.

  • 8/10/2019 Learn to Use Python

    29/176

    %ns; The assignment operator causes the value of its right operand to be stored inthe memory location identified by its left operand.

    5>. &hich type usually provides the greater range for storage of numeric values,integer or floating point

    %ns; /loating point usually provides the greater range for storage of numeric values.

    55. hould you just always use floating point instead of integer to be safe

    %ns; Probably not. /loating point arithmetic often suffers from speed penalties. naddition, integer arithmetic produces exact results while floating point arithmeticusually produces approximate results 3although the approximations may be veryclose to being exact in many cases6.

    50I. 8 0I.5>.>HHH

    :igure

    +owever, in this case, Python returned an answer of 5>.>, indicating that the answeris accurate to three significant figures. This is not really the correct answer, but as apractical matter, it may be the bestanswer. will leave that for you to decide.

    5I. Explain the purpose of the automatic continuation variable whose name is simplythe underscore character.

    %ns; The primary purpose of the automatic variable named Q is to make it easier foryou to string calculations together in interactive mode and to display theintermediate results as you go.

  • 8/10/2019 Learn to Use Python

    30/176

    Learn to Program using Python:Strings, Part I

    Preface

    This document is part of a series of online tutorial lessons designed to teach you howto program using the Python scripting language.

    Something for everyone

    Beginners start at the beginning, and experienced programmers jump in furtheralong. Aearn to Program using Python' Aesson 5, Fetting tartedprovides an overalldescription of this online programming course.

    1ntroduction

    am taking it slow and easy for the first few lessons. *y informal discussion isdesigned to familiari"e you with the Python interactive programming environmentwhile teaching you some important programming concepts at the same time.

    This lesson provides an introduction to the use of strings.

    What 1s % String

    The common interpretation of the word string in computer programming jargon isthat a string is a se%uence of characters that is treated as a unit. /or example, aperson!s first and last names are often treated as two different strings.

    ) person!s first name usually consists of several characters, and these characters aretreated as a unit to produce a name.

    What is a literal$

    Perhaps the best way to describe a literal is to describe what it is not.

    ) literal is not a variable. n other words, the value of a literal doesn!t change withtime as the program executes. You might say that it is taken at face value.

    %n e!pression using variables

    /or example, the following expression describes the sum of two variables namedvar,and var

  • 8/10/2019 Learn to Use Python

    31/176

    The result of this expression can vary depending on the values stored in var5 andvar< at the instant in time that the expression is evaluated.

    %n e!pression using literals

    ;n the other hand, the following expression describes the sum of two literal numeric

    values'

    sum = 6 + 8

    7o matter when this expression is evaluated, it will always produce a sum of 5J.

    String literals

    Aiteral values can also be used for strings.

    >>> "Dick Baldwin"

    'Dick Baldwin'>>> 'Dick Baldwin''Dick Baldwin'>>> Dick BaldwinFile "", line 1Dick Baldwin

    SyntaxError: invalid syntax>>>

    Figure 1

    /or example, the interactive code fragment in /igure 5 shows

    *y name entered three times, in three different ways, on the interactive

    command line 3highlighted in boldface6 The output from the interpreter for each entry.

    Oops>

    The first two entries are valid string literals. )s you can see, in the first two cases,the interpreter displays my name in the output.

    7ote that in the first two cases, my name is surrounded by either %uotes 3sometimes

    called double %uotes6 or apostrophes 3sometimes called single %uotes6.

    % synta! error

    +owever, the third entry is not a valid string literal, and the interactive interpreterproduced a syntax error message. n the third case, my name is not surrounded byeither double %uotes or single %uotes, and that is what produced the error.

  • 8/10/2019 Learn to Use Python

    32/176

    So" what is a valid string literal$

    )ccording to the Python @eference *anual, string literals can be enclosed inmatching single %uotes 3!6 or double %uotes 326.

    This explains why the first two input lines in the above interactive code fragment

    were accepted and the third line produced an error.

    Proper synta!

    n the first line, my name was surrounded by matching double %uotes. n the secondinput line, my name was surrounded by matching single %uotes.

    Bad synta!

    +owever, in the third input line, my name was not surrounded by %uotes of eithertype and this produced a syntax error.

    &ore e!amples

    /igure < shows two more examples of valid string literals with the input valuehighlighted in boldface.

    >>> """Dick Baldwin"""'Dick Baldwin'>>> """Dick... Baldwin"""'Dick\012Baldwin'>>>

    Figure 2

    37ote that purposely colored the 2RE,

  • 8/10/2019 Learn to Use Python

    33/176

    :eal with strings that occupy more than one line

    :eal with all of the lines that make up the string as a unit

    Preserve newline characters that separate the lines in the process.

    This is illustrated in /igure I, which shows my name, surrounded by matching triple%uotes and split onto two consecutive lines of input.

    >>>"""Dick... Baldwin"""'Dick\012Baldwin'>>>Figure 3

    /he newline 2KE,

  • 8/10/2019 Learn to Use Python

    34/176

    What %re *scape Sequences$

    Escape se%uences are special se%uences of characters used to represent othercharacters that

    1annot be entered directly into a string, or

    &ould cause a problem if entered directly into a string.

    /he newline character

    )n example of the first category is the newline character. Except when using triple%uoted strings, you cannot enter the newline character directly into a string.

    &hy Because when you press the nterkey in an attempt to enter a newline, thatsimply terminates your input for that line. t doesn!t enter the newline character intothe string.

    #sing the newline character

    The interactive code fragment in /igure J illustrates the use of an escape se%uenceto enter the newline character into a string. 7ote the KE,>> print "Dick\012Baldwin"DickBaldwin>>>Figure 4

    What doesprintmean$

    This fragment uses a printstatement. haven!t explained that statement to youbefore, but you can probably guess what it means.

    &hen printis used interactively, it is a re%uest to have its right operand 3theexpression to its right6 printed on the next line. n this case, it is a re%uest to havemy name printed on the next line.

    1ncluding the newline character

    n this fragment, entered the newline escape se%uence between my first and lastnames when constructed the string. Then, when the string was printed, the cursoradvanced to a new line following my first name and printed my last name on the newline. That is what escape se%uences are all about.

    print renders according to meaning

    7ote also that the printstatement rendered the newline character according to itsmeaning.

  • 8/10/2019 Learn to Use Python

    35/176

    &hat mean by this is that the printstatement did not print something thatrepresented the newline character 3KE,>> print "ic!ard \"Dick\" Baldwin"Richard Dick Baldwin

    >>>

    Figure

    &hat mean by this is that if you want to include a double %uote inside a string thatis surrounded by double %uotes, you must enter the double %uote inside the string asfollows' \"

    %voiding the quote problem

    Because this is such a common problem, and because the escape solutionis so uglyand difficult to read, Python gives us another way to deal with %uotes inside of

    %uotes. This solution, shown in /igure K, is the use of single and double %uotes incombination.

    >>> print #ic!ard "Dick" Baldwin#Richard Dick Baldwin>>>

    Figure 6

    n Python, double %uotes can be included directly in strings that are surrounded bysingle %uotes, and single %uotes can be included directly in strings that are

    surrounded by double %uotes. This is much easier to read than the solution thatre%uires you to place a lot of backslash characters inside your string.

    'ist of escape sequences

    ) complete list of the escape se%uences supported by Python is available in thePython @eference *anual.

    http://www.python.org/doc/current/ref/strings.htmlhttp://www.python.org/doc/current/ref/strings.html
  • 8/10/2019 Learn to Use Python

    36/176

    &ore Ways to Span 'ines

    $ust when you thought that you had seen it all, am going to show you three moreways to span multiple lines with strings. ;ne of them is shown in /igure L.

    >>>print "Richard \... Baldwin"!icard Baldwin>>>

    Figure $

    *nd the line with a bac)slash

    )s shown in /igure L, the use of a backslash at the end of the line makes it possibleto continue the string on a new line. +owever, the backslash is not included in theoutput, and there is no newline character in the output.

    ?ot restricted to strings

    )ctually, the backslash can be used at the end of a line to cause that line to becontinued on the next line whether inside a string or not. This is illustrated in thereview section.

    % form of concatenation

    &hen used in this way with a string, the backslash at the end of the line becomes aform of string concatenation. The portions of the strings on each of the input linesare concatenated to produce a single line containing both parts of the string in the

    output.

    will have more to say about string concatenation later in this lesson.

    #se the Kn escape sequence

    )s shown in /igure D, the inclusion of 2Kn2 inside the string produces the same resultas the inclusion of the numeric representation of the newline character, 2KE,>>print "Richard \nBaldwin"!icardBaldwin>>>

    Figure 8

    This is the common form of the newline escape se%uence typically used in 1, 188,and $ava.

  • 8/10/2019 Learn to Use Python

    37/176

    7ombine bac)slash and Kn

    The code in /igure shows how to combine the backslash at the end of the line witha newline character placed there to cause the output to closely resemble the input.

    >>>print "Richard \n\... Baldwin"!icardBaldwin>>>Figure %

    String 7oncatenation

    To concatenate two strings means to hook them together end#to#end, thus producinga new string that is the combination of the two.

    'iteral string concatenation

    You can cause literal strings to be concatenated just by writing one adjacent to theother as shown in /igure 5>.

    &&& print "Dick"#Baldwin#DickBaldwin&&& print #'(e# ")mit!"!oe"mith>>>

    Figure 10

    7ote that you can mix the different %uote types and it doesn!t matter if there iswhitespace in between.

    7reating whitespace

    +owever, if you want any space between the substrings in the output, you mustinclude that space inside the %uotes that delimit the individual strings as shown in/igure 55.

    >>> x "Richard ">>> ! " Baldwin">>> print x "#." !!icard #$ Baldwin>>>Figure 11

    #sing = for concatenation

  • 8/10/2019 Learn to Use Python

    38/176

    The plus operator 386 can be used to concatenate strings as illustrated in /igure 55.

    This fragment assigns string literal values to two variables, and then uses the plusoperator to concatenate the contents of those variables with another string literal.

    ;f course, it could also have been used to concatenate the contents of the two

    variables without the string literal in between.

    Whitespace is included in the quotes

    7ote that the string literals contain space characters. There is a space after the dinmy first name and before the Bin my last name. That is what meant earlier when said that if you want any space between the substrings in the output, you mustinclude that space inside the %uotes.

    &ore on Strings

    will have more to say about strings in a future lesson. Before that, however, we

    need to learn how to create and execute script files, and we also need to learn a littlemore about Python syntax.

    0eview

    5. :escribe the common meaning of the word stringin your own words, and givesome examples.

    %ns; The common interpretation of the word string in computer programmingjargon is that a string is a se%uence of characters that is treated as a unit. /orexample, a person!s first and last names are often treated as two different strings.

    > print 'Dick Baldwin'Dick Baldwin>>> print "$%& %ne("%o& ones>>> print """)ar! *&ith"""(ary S&it>>>

  • 8/10/2019 Learn to Use Python

    39/176

    Figure 12

    J. &hat is one of the advantages of using triple %uoted strings how an example.

    %ns; The use of triple %uoted strings, as shown in /igure 5I, makes it possible for

    you to continue a string on a new line, and to preserve the line break in the string.

    >>> print """Dick... Baldwin"""DickBaldwin>>>

    Figure 1*

    C. how two different representations of the newlinecharacter.

    %ns;KE,>> print 'Richard\012#.\nBaldwin'!icard#$Baldwin>>>Figure 14

    K. :escribe, in your own words, the purpose of an escape se%uence. how twoexamples.

    %ns; Escape se%uences are special se%uences of characters used to represent othercharacters that either

    1annot be entered directly into a string, or

    &ould cause a problem if entered directly into a string.

    Examples are shown in /igure 5C.

    >>> print\

    ... "*he (aid+ \",e \nw%n't g%\""Se said, ")ewon't *o">>>

    Figure 1

    L. how two different ways to include a double %uote character in a string.

  • 8/10/2019 Learn to Use Python

    40/176

    %ns; urround with single %uotes, or use an escape character as shown in /igure5K.

    &&& print #ic!ard "Dick" Baldwin#Richard Dick Baldwin&&& print "ic!ard \"Dick\" Baldwin"Richard Dick Baldwin>>>

    Figure 16

    D. how the escape se%uence for the tab character.

    )ns' The escape se%uence for the tab character is Ktas shown in /igure 5L.

    &&& print "\t(m\n\tDick, and\n\t-arr."#omDick, and$arry

    >>>

    Figure 1$

    Learn to Program using Python:Writing and Using Scripts

    Preface

    This document is part of a series of online tutorial lessons designed to teach you howto program using the Python scripting language.

    Something for everyone

    Beginners start at the beginning, and experienced programmers jump in further along.

    Learn to Program using Python: Lesson 1, Getting Started proides an oerall descriptionof this online programming course.

    Introduction

    http://www.developer.com/open/article.php/626311http://www.developer.com/open/article.php/626311http://www.developer.com/open/article.php/626311http://www.developer.com/open/article.php/626311
  • 8/10/2019 Learn to Use Python

    41/176

    ! hae been ta"ing it slo# and easy for the first fe# lessons. $y informal discussion has

    been designed to familiari%e you #ith the Python interactie programming enironment

    #hile teaching you some important programming concepts at the same time.

    It's time to learn about scripts

    &his lesson proides an introduction to the use of scripts, and of necessity #ill depart

    from the interactie mode used in preious lessons.

    Some system stuff

    'nfortunately, it #ill be necessary for me to get into somesystem stuffin this lesson.

    (on)t panic* ! still plan to #rite this lesson at a leel appropriate for beginningprogrammers.

    !t #ill be necessary for me to get into somesystemstuffthat really has nothing inparticular to do #ith Python programming. +ather, it #ill inole getting your computer

    set up for using scripts #ith Python.

    What Is A Script?

    'p to this point, ! hae concentrated on the interactie programming capability of

    Python. &his is a ery useful capability that allo#s you to type in a program and to haeit executed immediately in an interactie mode.

    But, interactive can be burdensome

    By no# you may hae reali%ed that you sometimes find yourself typing the same thing

    oer and oer. &hat is #here scripts are useful.

    Scripts are reusable

    Basically, a script is a text file containing the statements that comprise a Python

    program. nce you hae created the script, you can execute it oer and oer #ithout

    haing to retype it each time.

    Scripts are editable

    Perhaps, more importantly, you can ma"e different ersions of the script by modifying

    the statements from one file to the next using a text editor. &hen you can execute each of

    the indiidual ersions. !n this #ay, it is easy to create different programs #ith a

    minimum amount of typing.

    You will need a text editor

  • 8/10/2019 Learn to Use Python

    42/176

    -ust about any text editor #ill suffice for creating Python script files.

    ou can useMicrosoft NotePad, Microsoft WordPad, Microsoft Word, or just about any

    #ord processor if you #ant to.

    he !ro"rammer's #ile $ditor

    !)m fond of an editor named TheProgrammer's File Editor. ou can learn about it at the

    follo#ing '+L: http://###.lancs.ac.u"/people/cpaap/pfe/

    Arachnophilia and %oteab

    Some other editors that ! li"e areArachnophilia, #hich is aailable at

    http://###.arachnoid.com/arachnophilia/andNoteTab, #hich is aailable athttp://###.notetab.com/.

    &ust be a plain text editor

    0hicheer editor you choose, ma"e certain that it produces plain S2!! text in its output

    3no bold, no underline, no italics, etc.4.

    ombinin" scripts with interactive mode

    !t is also possible to combine script files #ith interactie mode to incorporate pre5#ritten

    scripts into interactie programs.

    (ettin" Started

    !n order to use script files, you must prepare you computer to use them. &his doesn)t

    amount to much in the #ay of effort, but it is critical.

    Where is !ython located?

    0hen you first installed your Python soft#are, a directory should hae been created

    some#here on your hard drie containing a file named python)exe.

    n a 0indo#s system, unless you forced the program to be installed some#here else, it

    #as probably installed some#here on your 25drie. ! forced the program to be installed

    on my (5drie.

    n my machine, the file named python)exeis in a directory named !ython, #hich inturn is contained in a directory named !ro"ram #iles on my (5drie.

    &y directory listin"

    http://www.lancs.ac.uk/people/cpaap/pfe/http://www.arachnoid.com/arachnophilia/http://www.notetab.com/http://www.notetab.com/http://www.lancs.ac.uk/people/cpaap/pfe/http://www.arachnoid.com/arachnophilia/http://www.notetab.com/
  • 8/10/2019 Learn to Use Python

    43/176

    &o help you get oriented, here is a list of files appearing in my !ythondirectory running

    under the 0in6& 7.8 0or"station operating system. &he file mentioned aboe is

    highlighted in boldface.

    !6S&LL.LG

    py.ico pyc.ico

    pycon.ico

    python)exe

    python#.exe

    '60!S9.99

    What about your files?

    !f you are running under 0indo#s, ! expect that your !ythondirectory #ill containpretty much the same set of files.

    ;o#eer, if you are using some other operating system, your list of files may be

    different, but hopefully there #ill still be a file named python)exe3or the e

  • 8/10/2019 Learn to Use Python

    44/176

    a=+=-a=+.a=-.c=a/0rint c

    Figure 1

    Where do I put the script file?

    Store this file in any directory on your hard drie. ou may #ant to create a ne#

    directory for the sole purpose of storing Python script files.

    A command prompt window

    &hen open a command prompt#indo# and ma"e the directory containing your ne#

    script file become the current directory.

    -ow do I open a command prompt window?

    0ith $S 0indo#s, you can open a command prompt #indo# by pulling up the Start

    menu, selectingPrograms, and then selecting ommand Prompt. t least this is ho# it is

    done on 0in6& 7.8 0or"station. 0in>? and 0in>@ should be similar.

    &he procedure #ill be different if you are using some other operating system.

    What is the current directory?

    !f you don)t "no# ho# to cause a particular directory to become your current directory,

    you #ill need to get someone #ho "no#s ho# to naigate the directory structure to sho#

    you. !t isn)t roc"et science, but it #ill be different for different operating systems, so you#ill need to "no# ho# to do it on your operating system.

    .unnin" your script file

    nce you hae accomplished all of the aboe, you should be able to enter the follo#ing

    command at the command prompt and you should see the result of executing your script

    appear on the screen.

    p.t!(n /unkp.

    =igure A sho#s #hat my screen loo" li"e #hen ! do this. 3gain, as a reminder, the

    figure number at the bottom is not part of the program output.4

    D%&Baldwin&''"chool&yro*>p.t!(n /unkp.+D%&Baldwin&''"chool&yro*>

  • 8/10/2019 Learn to Use Python

    45/176

    Figure 2

    I hi"hli"hted my command

    ! highlighted the command that ! entered in boldface 3in =igure A4 to separate it from thecommand prompt and the output produced by the program.

    Is this the correct output?

    !f you go bac" to the script file and do the arithmetic, you #ill see that the output alue of

    1 produced by the program is correct.

    on"ratulations are in order

    !f you got an output alue of 1, 55 congratulations 55 you hae just #ritten and executed

    your first Python script.

    What's %ext

    biously, there is a lot more that you #ill need to learn before you can #rite that C"illerscriptC that ta"es the #orld by storm, but at this point, you hae the tools to experiment

    #ith some simple scripts.

    !ractice, practice

    ! recommend that you loo" bac" into the earlier lessons and conert some of the

    interactie programs listed there into scripts, execute them, and confirm that the scriptsbehae as expected.

    In the future)))

    !n future lessons, ! #ill s#itch bac" and forth bet#een scripts and interactie mode,

    depending on #hich seems to be the most appropriate at the time.

    I li+e cut/and/paste pro"rammin"

    ;o#eer, ! am a strong adocate of cut5and5paste programming.

    2ut5and5paste programming #or"s #ell #ith scripts, and not so #ell #ith interactie

    mode.

    &herefore, any time there is ery much typing inoled, you can usually expect to see meusing scripts instead of interactie mode.

    .eview

  • 8/10/2019 Learn to Use Python

    46/176

    1. !n your o#n #ords, #hat is a scriptD

    Ans0 script is a text file containing the programming statements that comprise a

    Python program.

    A. script is a one5time affair, &rue or =alseD

    Ans0 #alse) Script files are reusable.

    . 2onert the interactie program sho#n in =igure into a script, execute it, and

    confirm that you get the correct result.

    >>> -/ 0 create and populate ->>> y1 0 create and populate y>>> -2y 0 add - to y and display the sum++>>>

    Figure *

    !n case you didn)t get any output, note that unli"e in interactie mode, in order to cause ascript to produce an output, you #ill need to use a statement something li"e the

    follo#ing:

    print +.

    7. 2onert the interactie program sho#n in =igure 7 into a script and execute it.

    >>> abc+3 0 assi*n +3 to several variables>>> a2b2c 0 add them to*ether3>>> abc43 0 assi*n 43 to same variables>>> a2b2c 0 add them to*ether/3>>>

    Figure 4

    ?. 2onert the interactie program sho#n in =igure ? into a script and execute it.

    >>> -1

    >>> y/>>> -2y++>>> -1.11111>>> y/./////>>> -2y+4.4444+>>>

    Figure

  • 8/10/2019 Learn to Use Python

    47/176

    E. 2onert the interactie program sho#n in =igure E into a script and execute it.

    >>> 12/++>>> 5244 0 add 44 to the continuation variable

    >>>

    Figure 6

    !f you #ere unable to get this to #or", don)t be dismayed. &he special ariable #hose

    name is the underscore character is aailable only in interactie mode. &herefore, youcan)t use that ariable in a script, and you #ill need to deelop a #or"around.

    F. 2onert the interactie program sho#n in =igure F into a script and execute it.

    >>> 0rint "Dick21+Baldwin"Dick

    Baldwin>>>

    Figure -

    Learn to Program Using Python:

    Program Construction

    Preface

    This document is part of a series of online tutorial lessons designed to teach you howto program using the Python scripting language.

    http://www.developer.com/open/article.php/628651http://www.developer.com/open/article.php/628651http://www.developer.com/open/article.php/628651http://www.developer.com/open/article.php/628651
  • 8/10/2019 Learn to Use Python

    48/176

    Something for everyone

    Beginners start at the beginning, and experienced programmers jump in furtheralong. Aearn to Program using Python' Aesson 5, Fetting tarted provides an overalldescription of this online programming course.

    Program 7onstruction

    1onceptually, programs are composed of statements, and statements are composedof expressions. n practice, you need to know how to construct statements from aphysical viewpoint.

    'ine structure

    ) Python program is divided into a number of logical lines. ) logical line isconstructed from one or morephysical lines.

    What is a physical line$

    ) physical line ends with the character3s6 used by your platform for terminatinglines.

    ;n 9nix, this is the linefeedcharacter. ;n :;0&indows, it is the carriage returncharacter followed by the linefeedcharacter. ;n *acintosh, it is the carriage returncharacter.

    &e refer to this in programming jargon as the newlinecharacter 3even though it isactually two characters on :;0&indows systems6.

    Please be more specific

    Basically, a physical line is what you get when you type some characters into yourtext editor and press the nterkey, the Returnkey, or whatever you call that key onyour keyboard. 3)ctually you don!t even need to type characters before pressing thenterkey, in which case you get blank lines.6

    This is the key that causes the cursor to go down to the next line and return to theleft side of the editing window.

    /or example, on my :ell laptop, pressed the *nterkey immediately following the##H in the two lines shown in /igure 5.

    3 will end te line ere 44>and end te next line ere 44>Figure 1

    This produced a newlinein each case. also pressed the nterkey a couple moretimes following that as well.

    % side trip into H/&'

  • 8/10/2019 Learn to Use Python

    49/176

    $ust in case you are interested in +T*A, the 7etscape 1omposer program that amusing to create this document inserts a B@H tag into the +T*A code each time press the nterkey 3but that has nothing to do with Python, or computerprogramming either for that matter6.

    What is a logical line$

    ) logical lineis constructed from one or morephysical lines.

    Aine joining rules 3described later6 can be used to construct a logical line from two ormore physical lines.

    Statements and logical lines

    ) statement cannot cross logical line boundaries except where the syntax allows forthe newlinecharacter, such as in compoundstatements. will show you an exampleof a compound statement later in this lesson.

    7omments

    &e learned about comments in an earlier lesson. To summari"e, a comment startswith a hash character 3M6 that is not part of a string literal 3we also learned aboutstring literals in an earlier lesson6. The comment ends at the end of the physicalline.

    *!plicit line 9oining

    You can join two or morephysical linesto produce a logical line, using the backslashcharacter as shown in /igure

  • 8/10/2019 Learn to Use Python

    50/176

    The backslash and the following end#of#line character are deleted 3or ignored by thecompiler6 and do not become part of the logical line.

    n /igure

  • 8/10/2019 Learn to Use Python

    51/176

    )n example of some spaces and blank lines is shown in /igure J.

    a = - s0aces and co&&ent

    = 5 ta and co&&ent

    c = 9a contin7e on next line/ a lank line ;ollows

    0rint c

    te o7t07t is 8

    Figure

    1ndentation

    n every programming environment that have worked with in the past, indentationis used strictly for cosmetic or readability purposes.

    ?ot 9ust for cosmetics in Python

    +owever, indentation is such an important topic in Python that have separated itinto a major section in this tutorial lesson.

    #sed to determine grouping of statements

    9nlike most other programming environments, physical indentation is used in Pythonto determine the grouping of statements.

    % blessing and a curse

    This can be both a blessing and a curse. The blessing is that it forces you to useproper indentation, which usually leads to more readable code.

    The curse is that if you don!t use proper indentation, your program probably won!tbehave properly.

    ?o safety nets

    There are no safety nets in Python 3such as the matching curly braces used in 1, 18

    8, and $ava6 to protect you from indentation errors.

    To make matters worse, such errors often turn up as logical errors 3meaning that theprogram simply doesn!t work correctly6 rather than compiler errors 3meaning thatthe compiler or interpreter will tell you about the error6.

    %n e!ample of correct indentation

  • 8/10/2019 Learn to Use Python

    52/176

    )lthough haven!t introduced you to the ifstatement yet, you probably have a fairlygood idea what it is used for. am going to use it to illustrate the proper indentationof a group of statements.

    'n istatement means that if some e-pression evaluates to true,

    do somethin* specific. 6therwise, don7t do it.

    :on!t be too concerned if the logic of this program escapes you at this point in time. will explain the use of the ifstatement in detail in a subse%uent lesson. Theimportant thing here is to understand the grouping of statements.

    7ompare % with B and ta)e appropriate action

    The sample program in /igure C compares the value of the variable %with the valueof the variable B 3i B & 36.

    = -

    B = 5

    i; B > /:print / egin gr%upprint Bprint / B end gr%up = 6 not 0art o; aove *ro700rint

    Figure 4

    /he program logic

    f the value of Bis greater than the value of %3which it is in this case6, the three3red6 statements are executed. ;therwise, that group of three statements isbypassed.

    37ote that made the statements red here to make them stand out. You would notmake them red when actually writing the program.6

    % compound statement

    The three statements shown in red are either all executed, or they are all bypassed.+ence, they behave as a group.

    ) group of statements like this is sometimes referred to as a compound statement3astatement made up of two or more individual statements6.

    3roup behavior

    &hen the three statements are executed as a group, the values I, J, and L areprinted on consecutive output lines by the three print statements in the group ofstatements, as shown in /igure K.

  • 8/10/2019 Learn to Use Python

    53/176

    D%&Baldwin&''"chool&yro*>python 8unk.py9:/

    D%&Baldwin&''"chool&yro*>

    Figure 6

    'ast statement is not part of the group

    Then the value K is printed by the last statement in the program, which is not part ofthe group.

    %nother sample program

    7ow, let!s make a change. The program shown in /igure L is identical to the one

    above except that switched the values of %and Bto cause the group of redstatements to be bypassed 3Bis no longer greater than %6.

    = 5B = -

    i; B > /:print / egin gr%upprint Bprint / B end gr%up = 6 not 0art o; aove *ro700rint

    Figure -

    /he output

    n this case, the output screen looks something like /igure D. ;nly one value 3K6 isprinted because the three print statements in the group were bypassed as a group.

    D%&Baldwin&''"chool&yro*>python 8unk.py/

    D%&Baldwin&''"chool&yro*>

    Figure 8

    What ma)es them into a group$

    The important point here is that the three red statements constitute a groupbecause of their common indentation level.

    *mphasis added

  • 8/10/2019 Learn to Use Python

    54/176

    37ote that used boldface and red in the above programs to emphasi"e certain partsof the program. The original script did not contain boldface and did not contain anyred color. Python scripts must be written in plain text, and control codes, such asbold or color, are not allowed.6

    %n opinion

    personally don!t like the idea of using indentation to create grouping. )lthough itsounds nice in theory, it can be very labor intensive in practice. ;nce you havewritten a script, one simple change can often re%uire you to go back and modify theindentation level of almost every statement in the script.

    guess the good news is that this will certainly encourage you to write your programas a series of short, concise independent modules rather than as a single longrambling program.

    Details" details

    7ow let!s talk about the details of indentation.

    'eading whitespace

    Aeading whitespace 3spaces and tabs6 at the beginning of a logical lineis used tocompute the indentation of the line. This, in turn, is used to determine the groupingof statements.

    What about tabs$

    *y advice is to avoid the use of tabs altogether. 9se spaces instead, and use thesame number of spaces for each statement in the group.

    +owever, if you must use tabs, there are a few things that you should know. +ere iswhat the Python @eference *anual has to say on the subject.

    ;irst, tabs are replaced (from left to ri*ht) by one to ei*ht spacessuch that the total number of characters up to and includin* thereplacement is a multiple of ei*ht (this is intended to be the samerule as used by

  • 8/10/2019 Learn to Use Python

    55/176

    9se either spaces, or tabs, but not both to cause the indentation level of allstatements in a group of statements to be indented to the same level.

    0eview

    5. Aogical lines are constructed from one or more QQQQQQQQQ 3fill in the blank6.

    %ns; Aogical lines are constructed from one or more physical lines.

  • 8/10/2019 Learn to Use Python

    56/176

    This document is part of a series of online tutorial lessons designed to teach youhow to program using the Python scripting language.

    Something for everyone

    Beginners start at the beginning, and experienced programmers jump in further

    along. Aesson 5 provides an overall description of this online programming course.

    1ntroduction

    What you have learned

    You have learned how to write some simple programs and execute theminteractively.

    You have learned how to capture simple programs in script files and to execute thosescript files.

    You have learned how to construct programs, including the indentation conceptsinvolved in Python.

    You have also learned some of the fundamental concepts involving strings.

    What you will learn

    This lesson will expand your knowledge of strings, and in addition will introduce youto some concepts that will be useful with other data types as well' indexingandslicing.

    What is inde!ing$

    )ccording to a definition that found on the web, "... an ordinal numberis anad!ective which describes the numerical position of an ob!ect e.g. first second

    third etc."

    % practical e!ample

    *any years ago when did a tour of duty as an enlisted man in the 9.. )ir /orce,they had a habit of lining us up and re%uiring us to "count off."

    &hat this meant was that the first person in the line called out the number one, the

    person behind him called out the number two, the person behind him called out thenumber three, etc. 3ince learning about computer programming, now wonder ifthe first person should have called out#ero.6

    %ssigning an ordinal inde!

    !m sure they didn!t reali"e that what they were doing was assigning an ordinal indexvalueto each person in the line 3and neither did at the time6.

    http://mathworld.wolfram.com/OrdinalNumber.htmlhttp://mathworld.wolfram.com/OrdinalNumber.html
  • 8/10/2019 Learn to Use Python

    57/176

    #sing an ordinal inde!

    Even though they didn!t know the technical details of ordinal indices, they didn!t haveany difficulty saying, "$umber six wash dishes number fourteen peel potatoesnumber twenty-two carry out the garbage etc."

    /his is inde!ing

    That is what indexing is all about.

    !n the context of this lesson, indexing is the

    process of assigning an ordinal index alue toeach data item contained in some sort of a

    container.

    n other words, we assign an ordinal number to each item, which describes the

    numerical position of the item in the container.

    =or example, if you #ere ery careful, you coulduse a felt tip pen to assign an ordinal index to

    each of the t#ele eggs contained in a carton

    containing a do%en eggs. 3Should you start #ith!eroor oneD4

    &hen you could extract the egg #hose index

    alue is > from the container and eat it forbrea"fast.

    +aving assigned the index, we can use that index to access the data itemcorresponding to that index, as in "$umber six wash dishes."

    37ote that this process is also referred to as a subscriptionin the Python @eference*anual.6

    1nde! values automatically assigned

    n this lesson, we will be using the index values that are automatically assigned tothe characters in a string for the purpose of accessing those characters, bothindividually, and in groups.

    What is slicing$

    +ere is what *agnus Aie +etlandhas to say on the topic of slicing 3and indexing aswell.6 )lthough this %uotation was taken from a discussion of lists, it applies e%uallywell to strings.

    6ne of the nice thin*s about lists is that you can access their

    http://www.idt.unit.no/~mlh/python/instant.htmlhttp://www.idt.unit.no/~mlh/python/instant.html
  • 8/10/2019 Learn to Use Python

    58/176

    elements separately or in *roups, throu*h inde-in* and slicin*.

    ndeingis done (as in many other lan*ua*es) by appendin* theinde- in brackets to the list. (ote that the first element has inde-3). 9!is is t!e answer t( t!e :uesti(n a7(ut t!e irst egg Baldwin;

    ...)licingis almost like inde-in*, e-cept that you indicate both thestart and stop inde- of the result, with a colon (%) separatin*them%..otice that the end is n(ninclusive. If one of the indices isdropped, it is assumed that you want everythin* in that direction.i.e. list@%A means every element from the be*innin* of list up toelement , noninclusive....list@%A would, on the other hand, mean every element from list,startin* at element (inclusive) up to, and includin*, the lastone.

    ;or really interestin* results, you can use ne*ative numbers too%list@A is the third element from the end of the list...

    Some material deleted for brevity

    added the boldface and the red comment for emphasis. also deleted some of thematerial from this %uotation for brevity, but will cover that material later inconjunction with my discussion of indexing and slicing strings.

    % Sample Program

    will illustrate indexing and slicing of strings using a sample program contained in ascript file named )tring01p..

    /he program listing

    ) complete listing of the program, and the output produced by the program, areprovided at the end of the lesson.

    Will discuss in fragments

    will discuss the program in fragments, illustrating particular aspects of indexing andslicing in each fragment. This is a scheme that will use fre%uently in this set of

    tutorial lessons.

    1nteresting 7ode :ragments

    ) single character can be extracted from a string by referring to the string andindicating the index of the character in s%uare brackets, as shown in the codefragment in /igure 5.

    aStr = "$hi( i( a (tring"

  • 8/10/2019 Learn to Use Python

    59/176

    0rint aStr2 0rint %0rint aStr- 0rint sFigure 1

    37ote that this is a fragment from a script file, not from an interactive Pythonprogram.6

    :irst create a string to wor) with

    The fragment in /igure 5 creates a string 3highlighted in boldface6 and assigns it to avariable named aStr. /rom this point on, the contents of the string can be accessedby referring to the variable.

    1nde! values always begin with Lero

    9nlike eggs and )ir /orce enlisted men, the first character in a string is alwayslocated at inde! E, as in a)tr

  • 8/10/2019 Learn to Use Python

    60/176

    ?ot li)e eggs

    f you access the egg at index value J in the container and eat it for breakfast, itcannot be accessed again 3because it will be gone6.

    +owever, if you access the character at index value J in the string and use it for

    some purpose, what you really use is a copy of the character. t is still there and canbe accessed again.

    3ome data containers do allow for the removal of data elements in much the samesense that we can remove an egg from its container. +owever, a string is not such acontainer.6

    % simple slice

    /or convenience, here is another copy of the fragment that created the string.

    aStr = "$hi( i( a (tring"

    The fragment in /igure < cuts a couple of slices out of that string and displays themon the screen.

    0rint aStr05 0rint %is0rint aStr10516 0rint strin*Figure 2

    Slice ?otation

    The slice notation uses two index values separated by a colon, as shown in boldface

    in /igure

  • 8/10/2019 Learn to Use Python

    61/176

    Omitting the first inde!

    f you omit the first index value, as shown in /igure I, it defaults to the value "ero.

    0rint aStr5 0rint %isFigure 3

    Therefore, the statement in /igure I extracts and prints the first word in the string,which is /his.

    Omitting the second inde!

    f you omit the second index, as shown in /igure J, it defaults to a value thatincludes the last character in the string.

    0rint aStr105 0rint strin*Figure

    Thus, the statement in /igure J extracts and prints the last word in the string, whichis string.

    Print the entire string

    /igure C shows two different ways to extract and print the entire string. won!tcomment on this, but will leave the analysis as an exercise for the student.

    0rint aStr54 / aStr450rint aStr5100Figure 4

    3+int' @emember that the plus sign when used with strings is the stringconcatenation operator.6

    Print an empty string

    There are several ways that you can specify the index values that will produce anempty string. ;ne of those ways is shown following the plus sign in /igure K.

    0rint "E&0ty: " / aStr16:122Figure 6

    n /igure K, both index values are outside the bounds of the index values of the

    characters in the string, which range from > through 5C inclusive.

    ?egative indices

    )lthough it can be a little confusing, negative index values can be used to count fromthe right, as shown in /igure L.

    0rint aStr74572 0rint tri

  • 8/10/2019 Learn to Use Python

    62/176

    Figure -

    This fragment extracts and prints the characters trifrom the word string, which isthe last word in the string.

    *liminating confusion

    ;nce you allow negative indices for slicing, thing can become very confusing. Thefollowing explanation of how indices work with slicing is attributed to Fuido van@ossum.

    n this example, *r. van @ossum is referring to a five#character string with a value of2Help%2.

    %e est way to re&e&er ow sliceswork is to tink o; te indices as0ointin* etween caracters, wit te

    le;t ed*e o; te ;irst caractern7&ered 2$ %en te ri*t ed*e o; telast caracter o; a strin* o; ncaracters as index n, ;or exa&0le:

    /444/444/444/444/444/? ) ? e ? l ? 0 ? ?/444/444/444/444/444/2 1 + - 5 @4@ 45 4- 4+ 41

    %e ;irst row o; n7&ers *ives te0osition o; te indices 2$$$@ in te

    strin*A te second row *ives tecorres0ondin* ne*ative indices$

    %e slice ;ro& i to consists o; allcaracters etween te ed*es laeled iand , res0ectively$

    For nonne*ative indices, te len*t o;a slice is te di;;erence o; teindices, i; ot are witin o7nds,e$*$, te len*t o; word1:- is +$

    +opefully, this explanation will help you to understand and to remember how indexvalues are used for the extraction of substrings from strings using slicing.

    3etting the length of a string

    )nd finally, a built#in function named len24can be used to determine the number ofcharacters actually contained in a string as shown in /igure D.

    0rint len9aStr

    http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000
  • 8/10/2019 Learn to Use Python

    63/176

    Figure 8

    /or the example string used in this lesson, /igure D gets and prints the length of thestring as 5K.

    f you count the characters in the string 3beginning with 56, you will conclude thatthere are 5K characters in the string.

    ?ote the difference between the number of characters and the ma!imum

    inde! value

    /or a string containing 5K characters, the valid index values range from > through 5Cinclusive.

    /he complete output

    This Python script file produces the output shown in /igure on my computer3boldface added for emphasis6.

    D%&Baldwin&''"chool&yro*>python strin*s3+.pys!isstring!isstring!is is a string!is is a string>mpt.tri16

    D%&Baldwin&''"chool&yro*>

    Figure %

    % String 1s 1mmutable

    There is one more point that needs to be made here. )lthough you can use indexingand slicing to access the characters in a string, you cannot use indexing and slicingto assign new character values to those characters.

    This is because a Python string is immutable. n other words, after it is created, itcannot be modified.

    7omplete Program 'isting

    ) complete listing of the program follows is shown in /igure 5>.

    File Strin*21$0y

  • 8/10/2019 Learn to Use Python

    64/176

    !ev +C5C22 o0yri*t +222, !$ #$ Baldwin 3ll7strates indexin* and slicin* strin*s4444444444444444444444444444444

    aStr = "%is is a strin*"0rint aStr2 0rint %0rint aStr- 0rint s0rint aStr2:5 0rint %is0rint aStr12:16 0rint strin*0rint aStr:5 0rint %is0rint aStr12: 0rint strin*

    0rint te entire strin*0rint aStr:@ / aStr@:0rint aStr:122

    0rint an e&0ty strin*0rint "E&0ty: " / aStr16:122

    co7nt ;ro& te ri*t0rint aStr4@:4+ 0rint tri

    *et te len*t o; te strin*0rint len9aStr

    Figure 10

    0eview

    5. &hat is an ordinal number

    %ns; )n ordinal number is an adjective, which describes the numerical position of anobject, e.g., first, second, third, etc.

  • 8/10/2019 Learn to Use Python

    65/176

    %ns; nclude both the start and stop index in s%uare brackets, separated by a colon,as in a)tr

  • 8/10/2019 Learn to Use Python

    66/176

  • 8/10/2019 Learn to Use Python

    67/176

    Python provides three kinds of se%uences' strings, lists, and tuples.

    discussed strings in a previous lesson. will discuss lists in this lesson, and willdiscuss tuples in a future lesson.

    What about the epressi(n?list$

    )ccording to the @eference *anual, if the primary is a se%uence, the "epressi(n?list"must evaluate to a plain integer.

    %n e!ample of an integer epressi(n?list

    n the string example above, the plain integer was Ein one case and @in the other.

    ?egative integers

    f the 3index6 value is negative, the length of the se%uence is added to it to obtainthe actual index used to access the se%uence.

    /or example, a)e:uence> aStr = "xy">>> 0rint aStr71>>>

    Figure 2

    &ore negative(integer rules

    The value resulting from adding the length of the se%uence to the specified indexvalue must be a non#negative integer less than the number of items in the se%uence.

    Then, the subscription selects the item whose index is that value 3counting from"ero6.

    3ood and bad negative integers

    This is illustrated in the interactive code fragment shown in /igure I, which showsboth valid and invalid negative subscription values. 3The subscription value of #Jviolates the above rule, thus producing an &ndexrror.6

    >>> aStrin* = "xy">>> 0rint aStrin*41>>> 0rint aStrin*4+y

  • 8/10/2019 Learn to Use Python

    68/176

    >>> 0rint aStrin*4-x>>> 0rint aStrin*45%raceack 9inner&ost last:File "", line 1, in

    nde>rr(r string inde (ut ( range

    >>>

    Figure 3

    What about a character type$

    There is no character type in Python. @ather, a string!s items are characters. )character is not a separate data type but a string of exactly one character.

    What is a &apping$

    ) mappingis a structure in which values are stored and retrieved according to a'ey. This is often called a dictionary, because it behaves similarly to a common

    dictionary.

    % real dictionary e!ample

    /or example, if want to know about the word Python, get out my &ebster!seventh 7ew 1ollegiate :ictionary, 3which is about forty years old6, and look upthe wordpython3in this case, python is the key6.

    The 3approximate6 value associated with the key is, "... monstrous serpent 'illed by(pollo ..."

    1s this a definition$

    n normal conversation, we fre%uently refer to the value obtained from a commonprinted dictionary as the definition of the word. +owever, definition usually meanssomething completely different in computer jargon.

    n computer jargon, we refer to it as the valueassociated with the word 3'ey6.Thus, a mapping, is a structure that associates valueswith 'eys.

    o, a common printed dictionary is an example of a mapping.

    ?o mention of the Python language

    ince my dictionary is much older than the Python programming language, wouldn!t expect to find anything about Python programming there.

    What about the epressi(n?list$

    )ccording to the @eference *anual, if the primary is a mapping, the epressi(n?listmust evaluate to an object whose value is one of the keys of the mapping 3such aspython in my common dictionary example6.

  • 8/10/2019 Learn to Use Python

    69/176

    What gets selected$

    Then the subscription selects the value in the mapping that corresponds to that key.

    n other words, the system looks up the word in the dictionary and returns the valuethat corresponds to that word.

    &ore to say about mappings

    will have more to say about mappingsin a future lesson.

    What is a Slicing$

    discussed slicingsat some length in the lesson on strings, using a different sourcefor my information. n this lesson, will paraphrase information extracted from thePython @eference *anual.

    The semantics for a simple slicingare as described in the following paragraphs.

    What about the primary$

    To begin with, the primary must evaluate to a se%uence object 3a string, a list, or atuple6. n other words, a dictionary structure cannot be sliced.

    % slicing specifies two numeric bounds

    The lower and upper bound expressions, if present, must evaluate to plain integers,such as in the statements from the lesson on strings shown in /igure J.

    0rint aStr050rint aStr10516Figure

    What about default values$

    Both the lower and upper bounds have default values. The default values are#eroand the se%uence)s length, respectively.

    /igure C shows some examples of using default values from the lesson on strings.

    0rint aStr50rint aStr105Figure 4

    What about negative bounds$

  • 8/10/2019 Learn to Use Python

    70/176

    f either bound is negative, the se%uence!s length is added to it. The slicing thenselects all items with index ksuch that i @= k @ /where iand /are the specified lowerand upper bounds.

    This may be an empty se%uence. t i