Top Banner

of 55

Python 1 v2.pdf

Aug 07, 2018

Download

Documents

DeepakPrabhu
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/19/2019 Python 1 v2.pdf

    1/133

    Python 1

    Lesson 1: Gett ing Started

     A Bit of Python History

    Unix and CodeRunner 

    Programming in Python

     A First Program

    The Interactive Interpreter 

    Data in Python

    String Representations

    Numbers in Python

    Program 2: Printing Simple Python Expressio ns

     A Few Sample Expressio ns

    First Hurdle Cleared

    Quiz 1  Quiz 2  Pr o ject 1 

    Lesson 2: Ent ering and St oring Dat a

    Binding Values to Names

    Names in Python

    Namespaces and Object Space

    More Python Syntax Basics

    Line Continuations

    Multiple Statements o n One Line

    Indentation

    Comments

    Docstrings

    Using String Methods: Case Conversion

    Reading and Co nverting User Input

    The input() Function

    Type Conversions

    Calculating with Stored Values

    Getting It Done

    Quiz 1  Quiz 2  Project 1 

    Lesson 3: Making De cisions: The if Stat ement

    Conditions in Python

    Making Decisions: if Statements

    Choo sing Between Alternatives: the else Clause

    Multiple Choice Decisions

    Combining Conditions : 'and' and 'or'

    Testing for a Range of Values: Chaining Comparisons

    Wrapping It Up

    Quiz 1  Quiz 2  Project 1 

    Lesso n 4: Ite rat ion: For and While Loo ps

     A Basic For Loop

    Breaking Out of a Loop

    http://localhost/var/www/apps/conversion/tmp/scratch_2/homework/makingDecisions_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/makingDecisions_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/makingDecisions_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/enteringData_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/enteringData_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/enteringData_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/makingDecisions_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/makingDecisions_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/makingDecisions_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/enteringData_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/enteringData_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/enteringData_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/gettingStarted_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/gettingStarted_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/gettingStarted_quiz1.quiz.html

  • 8/19/2019 Python 1 v2.pdf

    2/133

    While Loo ps

    Terminating the Current Iteration

    Feel the Power 

    Quiz 1  Project 1 

    Lesso n 5: Seque nce Cont ainers: Lists and Tuple s

    Lists and Tuples

    Writing Lis ts and Tuples

     Accessing Sequence Values

    Modifying Lists

    Slices with a Stride: Skipping Sequences

    Other Functions and Methods to Use with Sequences

    Testing for Presence in a Sequence

    Manipulating Lists and Tuples

    It Slices, It Dices...

    Quiz 1  Quiz 2  Project 1 

    Lesson 6 : Set s and Dict s

    Creating Sets

    Working wi th Sets

    Working with Dicts

     Applying Dicts : Counting Words

     A More Complex Appl icatio n: Word Pair Frequencies

    Nice Work!

    Quiz 1  Quiz 2  Project 1 

    Lesso n 7: String Formatting

    The fo rmat() Method

    Function Arguments

    Format Field Names

    Format Specifications

    Padding and Alignment

    Sign

    Base Indicator 

    Digit Separator 

    Field Width

    Precision

    Field Type

    Variable-Width Fields

     A Simple Lis ting Program

    Check You Out!

    Quiz 1  Quiz 2  Project 1 

    Lesson 8 : More About Lo oping

    Fun with the range() function.

    Using the enumerate() function

     A More Complex While Loop Example

    While Loops and User Input Validation

    http://localhost/var/www/apps/conversion/tmp/scratch_2/homework/stringFormatting_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/stringFormatting_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/stringFormatting_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/setsAndDicts_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/setsAndDicts_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/setsAndDicts_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/sequenceContainers_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/sequenceContainers_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/sequenceContainers_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/iteration_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/interation_quiz1.quiz.html

  • 8/19/2019 Python 1 v2.pdf

    3/133

    Dicts and Loo ps

     A More Complex Example

    Loo p This

    Quiz 1  Quiz 2  Project 1 

    Lesson 9 : Reading and Writing File s

    Creating a New File

    Writing to a File

    Reading Files as Text

     Appending to a File

    Seeking to Arbitrary Pos itions

    More File Details

    Creating a File-Based To- Do Lis t

    Reading Binary Data

    Files for Miles

    Quiz 1  Quiz 2  Project 1 

    Lesso n 10: Pytho n's Built-In Funct ions

    Party Fun with Buil t-In Functions

    abs(x)

    all(iterable)

    any(iterable)

    bool(x)

    chr(i)

    dict(arguments)

    dir(arguments)

    globals()

    help(object)

    len(s)

    locals()

    max(iterable)

    min(iterable)

    ord(c)

    pow(x, y[, z])

    reversed(seq)

    round(x[, n])sorted(iterable)

    sum(iterable)

    zip(*iterables)

    Fun with Built-In Functions

    Quiz 1  Quiz 2  Project 1 

    Lesson 11: Def ining and Calling Your Own Functio ns

    Exploring Functions

    Write Your First Function

    Parameters and Ar uments

    http://localhost/var/www/apps/conversion/tmp/scratch_2/homework/pythonsBuiltInFunctions_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/pythonsBuiltInFunctions_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/pythonsBuiltInFunctions_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/readingAndWritingFiles_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/readingAndWritingFiles_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/readingAndWritingFiles_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/moreAboutLooping_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/moreAboutLooping_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/moreAboutLooping_quiz1.quiz.html

  • 8/19/2019 Python 1 v2.pdf

    4/133

     

    Returning Values

    Multiple Return Values

    Functions and Namespaces

    Parameters That Receive Multiple Arguments

    Putting It All Together 

     A Sol id Foundation

    Quiz 1  Quiz 2  Project 1 

    Lesson 12: The P ytho n St andard Library

    Increased Versatility

    Namespaces

    Python Modules

    Writing Modules to be Testable

    Splitting Up Your Programs

    Other Ways to Import a Module

    import ... as

    from ... impo rt ...

    The System Path

    Reduce, Reuse, Recycle!

    Quiz 1  Quiz 2  Project 1 

    Lesson 13: More About Functions

     Arbitrary Keywo rd Parameters

    Parameters, Sequence-Parameters, and Dict-Parameters

    Importing Functions and help()

    Function Execution by Dispatch

    What's Your Function?

    Quiz 1  Quiz 2  Project 1 

    Lesson 14: Classes and Object -Orient ed Programm ing

    The Nature of Objects

    Defining Your Own Object Classes

    Class and Instance Namespaces

    Defining Object Behavior 

    Defining Behavior as Methods

    Python Deep Magic: Hooking into Python's Clas s Mechanism

    Using __init__()

    More on Python' s Dunder Methods

    Being Selfish

     A Solid Foundation

    Quiz 1  Quiz 2  Project 1 

    Lesson 15: Except ion Handling

    Working through Exceptions

    How to Catch an Exception

    Verifying Numeric Input

    Handling Multiple Exception Types

    Handling Multiple Exceptions with One Handler 

    http://localhost/var/www/apps/conversion/tmp/scratch_2/homework/classesAndOOP_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/classesAndOOP_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/classesAndOOP_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/moreAboutFunctions_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/moreAboutFunctions_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/moreAboutFunctions_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/pythonStandardLibrary_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/pythonStandardLibrary_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/pythonStandardLibrary_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/definingAndCallingYourOwnFunctions_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/definingAndCallingYourOwnFunctions_quiz2.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/definingAndCallingYourOwnFunctions_quiz1.quiz.html

  • 8/19/2019 Python 1 v2.pdf

    5/133

    Raising Exceptions

    Specific and Generic Exceptions

    When to Use Exceptions

    Exceptional Work So Far!

    Quiz 1  Project 1 

    Lesso n 16: Building and Debugging Whole P rograms

    Putting it All Together 

    The Art of Computer Programm ingDesign Techniques

     Agile Programming

    Documenting and Testing Python Code

    'Keep It Simple, Stupid' (KISS)

    Refactoring

    Go Forth and Code in Python!

    Quiz 1  Project 1  Project 2  Project 3 

    Copyright © 1998-2014 O'Reilly Media, Inc.

    This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

    http://creativecommons.org/licenses/by-sa/3.0/legalcodehttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/buildingAndDebuggingWholePrograms_proj3.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/buildingAndDebuggingWholePrograms_proj2.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/buildingAndDebuggingWholePrograms_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/buildingAndDebuggingWholePrograms_quiz1.quiz.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/exceptionHandling_proj1.project.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_2/homework/exceptionHandling_quiz1.quiz.html

  • 8/19/2019 Python 1 v2.pdf

    6/133

    Getting Started

    Welcom e to the O'Reilly Schoo l of Technolo gy's (OST) Introduction to Python course! We're happy you' ve chosen to learnPython programming with us.

    Course Objectives

    When you complete this course, you will be able to:

    store and m anipulate user-input data using Python.

    implement bas ic Python decisions, iteration, sequence containers, sets, and dicts.

    read and write files us ing Python.

    define custom functions and call built-in Python functions .

    impo rt mo dules and names paces from the Python Standard Library.

    define classes and instantiate objects using Python' s Class mechanism.

    handle exceptions and do cument code.

    build and debug an entire program written in Python.

    In this course, you will learn the basics of programming with Python. Using the Co deRunner integrated learning environment,you'll learn about express ions , variables, conditionals , loops, lists, sets, dicts, functions, objects and exceptions.

    Besides a browser and internet connection, all so ftware is provided online by the O'Reilly Schoo l o f Technology.

    Learning with O'Reilly School of Technology Courses

     As with every O'Reilly Scho ol of Techno lo gy course, we'l l take a user-active approach to learning. This means that you(the user) will be active! You'll learn by doing, building live programs, testing them and experimenting with them—hands-on!

    To learn a new skill or technolo gy, you have to experiment. The more you experiment, the mo re you learn. Our systemis des igned to maximize experimentation and help you learn to learn a new skill.

    We'll program as much as pos sible to be sure that the principles sink in and s tay with you.

    Each time we discuss a new concept, you'll put it into code and see what YOU can do with it. On occasio n we'll evengive you code that does n't work, so you can see common m istakes and how to recover from them. Making mistakesis actually another goo d way to learn.

     Above all, we want to help you to learn to learn. We give you the too ls to take control o f your own learning experience.

    When you complete an OST course, you know the subject matter, and  you know how to expand your knowledge, soyou can handle changes like s oftware and o perating sys tem updates.

    Here are so me tips for using O'Reilly Schoo l of Technolo gy courses effectively:

    Type the code. Res ist the temptation to cut and paste the example co de we give yo u. Typing the codeactually gives you a feel for the programm ing task. Then play around with the examples to find out what elseyou can make them do , and to check your understanding. It's highly unlikely you' ll break anything byexperimentation. If you do break som ething, that's an indication to us that we need to impro ve our sys tem!

    Take your time . Learning takes time. Rushing can have negative effects o n your progress. Slow down andlet your brain absorb the new info rmation thoroughly. Taking your time helps to maintain a relaxed, pos itiveapproach. It also gives you the chance to try new things and learn more than you otherwise wo uld if youblew through all of the coursework too quickly.

    Experiment. Wander from the path often and explore the possibilities. We can't anticipate all of your questions and ideas, so it's up to yo u to experiment and create on your own. Your instructor will help if yougo completely off the rails.

    Accept guidance, but do n't depend on it . Try to so lve problems on yo ur own. Going frommisunderstanding to understanding is the best way to acquire a new s kill. Part of what you're learning isproblem so lving. Of course, you can always contact your instructor for hints when you need them.

    Use all available reso urces! In real-life problem- so lving, you aren't bound by false limitations; in OSTcourses , you are free to use any resources at your dispo sal to so lve problems you encounter: the Internet,reference books, and online help are all fair game.

  • 8/19/2019 Python 1 v2.pdf

    7/133

    Have f un! Relax, keep practicing, and don't be afraid to make mistakes! Your instructor will keep you at ituntil you've mas tered the skill. We want you to get that satisfied, "I'm so coo l! I did it!" feeling. And you'll haveso me projects to show off when you're done.

    Lesson Format

    We'll try out lots o f examples in each lesso n. We'll have you write code, look at code, and edit existing code. The codewill be presented in boxes that will indicate what needs to be do ne to the code inside.

    Whenever you see white boxes like the one below, you' ll type the contents into the editor windo w to try the exampleyourself. The CODE TO TYPE bar on top o f the white box contains directions for you to follo w:

    CODE TO TYPE:

    White boxes like this contain code for you to try out (type into a file to run).

    If you have already written some of the code, new code for you to add looks like this.

    If we want you to remove existing code, the code to remove will look like this.  We may also include instructive comments that you don't need to type. 

    We may run programs and do so me o ther activities in a terminal sess ion in the operating system or o ther command-

    line environment. These will be s hown like this:

    INTERACTIVE SESSION:

    The plain black text that we present in these INTERACTIVE boxes isprovided by the system (not for you to type). The commands we want you to type look like this.

    Code and info rmation presented in a gray OBSERVE box is for you to inspect  and absorb. This information is o ftencolo r-coded, and follo wed by text explaining the code in detail:

    OBSERVE:

    Gray "Observe" boxes like this contain information (usually code specifics) for you toobserve.

    The paragraph(s) that follo w may provide addition details on information that was highlighted in the Observe box.

    We'll also set especially pertinent information apart in "No te" boxes:

    Note Notes provide information that is us eful, but not abso lutely necessary for performing the tasks at hand.

    Tip Tips provide information that might help make the tools easier for you to use, such as sho rtcut keys.

    WARNING Warnings provide info rmation that can help prevent program crashes and data loss.

    The CodeRunner Screen

    This course is presented in CodeRunner, OST's self-contained environment. We'll discuss the details later, but here'sa quick overview of the various areas o f the screen:

  • 8/19/2019 Python 1 v2.pdf

    8/133

    These videos explain how to use CodeRunner:

    File Management Demo

    Code Editor Demo

    Coursework Demo

    A Bit of Python History

    First, here's a little background information to introduce you to Python. No cringing please—this will be the mosttextbookish part of the course. We like to provide a little history for our students with a mo re philosophical andacademic bent. Plus you'll have a better understanding o f your programm ing tasks if you have a better idea about what

    makes Python tick.

    The Python language was created by Guido van Ro ssum in the late 1980 s. It was intended to be sim ple to use andeasy to understand. The most interesting new feature of the language was its use of indentation to illustrate structure,sim ilar to the way we use indentation in o ur everyday pros e and written language.

    Python was built to have a small "co re," to keep it accessible, and a large library to make it versatile. Van Rossum wasinterested in networking. That interest prompted quick development of a useful set of network libraries for the language;many mo re libraries have been added s ince then.

    Today, Python is used jus t about everywhere. Major us ers include YouTube, Goo gle, Yahoo!, CERN, and NASA, andITA—the company that produces the route search engine used by Orbitz, CheapTickets, travel agents—as well asmany domestic and international airlines.

    Python is an interpreted  language, which means Python code is n't translated into the binary instructions thatcom puters actually run. Instead, bytecode is created, and the interpreter uses that bytecode to tell it what to do . Pythonis also a dynamic  language. This means that aspects o f your program which become fixed early on in so melanguages, remain available for yo u to change in Python, even while your program is running.

    In this co urse, we'll be us ing the latest version of Python (3.1). You may find that o ther people are using o lder versio ns.Fortunately, the differences between versions are mino r. We'll go over the changes you' ll need to be aware of in o rder to work with older versions as well.

    Unix and CodeRunner

    We use o ur CodeRunner Integrated Development Environment on the Unix operating system for this course. Unix and

    CodeRunner allow you to write Python programs o n our computers so yo u don't need to wo rry about having anyspecial software on your o wn com puter. We have an entire OST course devo ted to Unix if you'd like a deeper understanding o f that operating system. For this course, we'll jus t cover the concepts you need to know, when you

    http://www.youtube.com/watch?v=WmajY8bIXrAhttp://www.youtube.com/watch?v=SvbM6vPAG9khttp://www.youtube.com/watch?v=45sATp529Mw

  • 8/19/2019 Python 1 v2.pdf

    9/133

    need to kno w them.

    In the next section, we'll finally enter some Python code and run it!

    Programming in Python

    A First Program

    It is a tradition when learning a new language in computer programming to print the words "hello world" as afirst example. Python can print "hello world" in a single line o f code, so that does n't make for a great example

    here. Instead, we'll loo k at a slightly mo re complicated example that not only prints "hello " and "go odbye," butalso does a little calculation along the way.

    Usually you'll enter a Python program in your favorite text editor and then run it by typing a com mand in acommand shell  (that's the term for one o f thos e special programs whos e job in life is to display a prom pt andthen let you type in a command that executes when you press Enter). On a Unix o r Linux type o f system (thatincludes OS X), the shell is bash, or tcsh, or some o ther -sh, and the editor is vim o r Emacs or o ne of manyother pos sibilities. On Windows, the shell is the DOS window (what you get by running "cmd") and the edito r is No tepad or Wordpad or vim or, again, any of many other pos sibilities. (You can also run programs on

    Windows by double-clicking their icons , but then the usual input and o utput streams are not available.)

    In this co urse we're go ing to use a completely integrated environment because we want the course to beabout learning Python, not about learning a particular editor and operating system. Later in the course, thereis a brief lesso n on bas ic Unix commands and editors so that, when you're ready, you can transfer your knowledge o f Python to the real world.

    Let's get started on your first program! First, we'll create a folder to keep all of our Python stuff organized. Inthe left panel o f your Co deRunner window, right-click Home , and select New fo lder... as sho wn:

    Enter the folder name python1:

  • 8/19/2019 Python 1 v2.pdf

    10/133

    Note You wo n't see this many folders in your File Browser. OST editors work on a lot o f courses!

    Now you should be able to see your python1 folder lis ted in the File Browser  on the left side o f your screen:

    Now, in the editor windo w area below this lesso n text, enter the code belo w:

    CODE TO TYPE:

    print("Hello World")print("I have", 3 + 4, "bananas")print("Goodbye, World")

    In the editor menu bar, click the Save  icon: (we'll show that icon from no w on when we want you to save afile). Select your /pyt ho n1 folder and enter the file name hello_world.py:

  • 8/19/2019 Python 1 v2.pdf

    11/133

    To run the program, open a Unix shell. Click the New Te rminal icon at the top of the editor window and,when prompted, enter your OST username and password (the passwo rd won't appear as you type it):

    INTERACTIVE SESSION:

    cold1 login: usernamePassword: yourpassword 

    Once logged in, you' ll see a cold1:~$  prompt. Change to your /pyt ho n1 folder and then run the program asshown:

    INTERACTIVE SESSION:

    cold1:~$ cd python1cold1:~/python1$ python3 ./hello_world.pyHello WorldI have 7 bananasGoodbye, Worldcold1:~/python1$

    Congratulations ! You're o fficially a Python programmer! Of course this program is n't very complex, but theinterpreter has done the calculation you asked it to do . Pat yourself on the back! You're o ff to a strong s tart.Experiment with other calculations.

    How did this work? Let's loo k a little clos er:

    OBSERVE:

    cold1:~$ cd   python1cold1:~/python1$ python3 ./hello_world.py

    First we used the Unix changed directory (cd) comm and to change to the python1 folder where our programis located. Then we ran python3, the current versio n o f the Python interpreter, telling it to run the

  • 8/19/2019 Python 1 v2.pdf

    12/133

    hello_world.py program located in the current fo lder (./)

    Note When you want to exit from the interactive session, type exit  and press Enter , or press Ctrl+d.

    The Interactive Interpreter

    In Python, you can run the interpreter in interactive mode when you want to try things o ut and see resultsprinted right away. That ins tant feedback is really handy when you're learning a new language.

    CodeRunner gives you access to interactive Python sess ions —click the New Terminal icon, and in theTerminal windo w, type your OST login and passwo rd (again, it does n't appear while you' re typing it), and then

    type python3:

    INTERACTIVE SESSION:

    cold1 login: your OST loginPassword: your OST passwordcold1:~$ python3Python 3.1.4 (default, Oct 13 2011, 10:08:29)[GCC 4.4.5 20110214 (Red Hat 4.4.5-6)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>>

    The prompt >> > indicates that the interpreter is ready fo r your input.

    If you enter one o f the lines from the program you just ran, the output will appear. This interactive interpreter window allows you to enter both s tatements and express ions (we'll cover those in detail later). Statementsare executed pretty much as if they were part of a program; the express ions are evaluated and the resul tingvalue is printed (as lo ng as yo u're in interactive mode).

    Type the commands below in the interpreter window (Remember: when we say TYPE the code, do it. It's good 

    for you! ). The interpreter prints a result for each express ion. (You'll s ee a different prom pt after the fourth line.We'll talk about that in a minute):

    INTERACTIVE SESSION:

    >>> "hello" + " world"'hello world'>>> 'hello' + ' world''hello world'>>> """hello""" + ''' world''''hello world'>>> """hello... world"""'hello\nworld'>>>

    So, what happened here? The first three lines are all examples of string concatenation—a second s tring isappended to the first, giving a lo nger string as a result. Strings can have either single (') o r double (")quotation marks around them, and either one quotation mark or three at the beginning and end o f the string.Use exactly the same combination at both ends.

    The last express ion sho ws an impo rtant difference between the one-quo tation mark and the three-quotationmark forms. A string given in one-quo tation mark form must  begin and end on the sam e line. Three-quotationmark strings can spread across more than one line.

    The fourth example actually does extend across two lines, so the interpreter changed its prompt from >> > to.. . (an ellipsis ) after you entered the first line. The ellipsis lets you know that you've go t an incompletestatement or expression, and the interpreter is waiting for you to finish it. When you completed the string withthe second line o f input, the interpreter then printed the value o f the two- line expressio n, and returned thenormal >>>  prom pt. You can see that the line feed between hello  and world is represented by \n, which is

  • 8/19/2019 Python 1 v2.pdf

    13/133

    known in Python as a string escape sequence.

    Data in Python

    In Python there are various types o f data you can manipulate. The simples t are strings. There are also various numericdata types: integers, floats, and complex numbers. Let's see ho w to write thos e values in your programs.

    String Representations

    We've seen that Python has several ways o f representing strings. For regular strings, we use either of the

    one- quotation mark forms. Use three-quo tation mark strings if, for example, the value you need to representcontains newlines, or contains quotation marks itself. The interpreter represents certain characters usingescape sequences. You can put escape sequences into your s trings to insert certain literal or no n-printingcharacters. Here's a list of the most comm on sequences:

    Escape Sequence Is t ranslated into

    \" Double quote

    \' Single quote (apostrophe)

    \\ Backslash

    \r Carriage return

    \n Line feed (newline)

    \{newl ine} Ignores the newline, a llowing you to run a string across multiple program l ines

    \0nn Character whose value in o ctal is nn

    \xnn Character whose value in hexadecimal is nn

    You can build a really long s tring using triple-quotation mark strings and escaping the newlines, o r by placingseveral different strings one after the o ther in your so urce code. Usually you'll extend those types o f 

    statements acros s m ultiple lines us ing parentheses; the interpreter will assum e a statement or express ion isincomplete if it runs into unmatched parentheses. Continue the interpreter sessio n o r start a new one and trythese commands:

    INTERACTIVE SESSION:

    >>> """One\... Two\... Three"""'OneTwoThree'>>> ("One" "Two" "Three")'OneTwoThree'>>> 'OneTwoThree''OneTwoThree'

    The interpreter sho uld print the same value back after you enter each of the three strings. The first string youentered spans three lines, but only printed out one.

    Numbers in PythonIn Python, numbers are represented as yo u might expect. Integers are strings of digits. The digits can bepreceded by a minus s ign (-) for negative numbers. There is no limit on integer values in Python, although thelarger they get, the longer it takes yo u to do anything with them!

    NoteIn Python, you cannot  use commas to separate groups of digits like you so metimes do in textdocuments.

     A floating- po int number is made up o f an integer follo wed by a decimal po int and a fractional part. You mayalso use exponential notation if you like, by placing the letter E after the integer.

    Com plex numbers generally cons ist o f a real part and an imaginary part that's followed by a J ; the real part is

  • 8/19/2019 Python 1 v2.pdf

    14/133

    separated from the imaginary part by a plus o r minus sign. The imaginary number follo wed by the J  cancomprise a com plex number in Python as well. (For you mathematicians wondering why i wasn' t used, this isstandard engineering notation. The rest of us can just carry on.)

    Let's try som e o f this s tuff out. If you do n't have an interpreter sess ion open, click the New Te rminal icon andtype python3 again. Then, try these numbers:

    INTERACTIVE SESSION:

    >>> 1

    >>> -1000>>> 12.34>>> 1.234E2>>> 1+2j>>> 1j

    Huh. it seems the interpreter doesn't always print a value the way you enter it. Floating point numbers aren't

    always exact, though the interpreter gets as close as pos sible. Although the errors are relatively small, youwant to keep them from accumulating too much in long strings o f calculations . (More on that later.) If so me o f this isn't quite clear to you yet, don't worry. We're just getting started. We'll be talking about it all lots more andyou'll have many chances to try things o ut and ask questions.

    Program 2: Printing Simple Python Expressions

    You've s een that you can concatenate strings by adding them together. There are many mo re operations youcan perform on your numbers in Python:

    Symbol Operation

    + Addition

    - Subtraction

    * Multiplication

    / Division

    ** Exponentiation

    A Few Sample Expressions

    Create ano ther program file in the edito r window:

    CODE TO TYPE:

    print("""--------------------Some Calculations--------------------""")print(314159E-5)print(10**6, 1j**2)print(3 + 2 * 4, 1 / 3)print("-" * 20)print((3.14159 * 16) ** 2)

    print(3.14159 * 16 ** 2)print(20 * "-")print("--------------------\nEnd of Calculations\n--------------------")

     Save it in your /pyt ho n1 folder as calculations.py and run it in the Terminal tab:

  • 8/19/2019 Python 1 v2.pdf

    15/133

    INTERACTIVE SESSION:

    cold1:~/python1$ python3 ./calculations.py--------------------Some Calculations--------------------3.141591000000 (-1+0j)11 0.333333333333--------------------

    2526.6144583935998804.24704----------------------------------------End of Calculations--------------------cold1:~/python1$

    Take a m inute to ponder. Think deeply and make sure you understand all o f your results before go ing further.

    For example, you might wonder, why does 3 + 2 * 4 give 11, and not 20? Hmm... something to think about!Feel free to talk with your ins tructor if you are in any way befuddled.

    First Hurdle ClearedPhew! That was a who le lo t of introduction there. Thanks for sticking with me. Keep it up, you're doing great so far. See

    you at the next lesso n!

    Copyright © 1998-2014 O'Reilly Media, Inc.

    This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

    http://creativecommons.org/licenses/by-sa/3.0/legalcode

  • 8/19/2019 Python 1 v2.pdf

    16/133

    Entering and Storing Data

    Lesson Objectives

    When you complete this lesson, you will be able to:

    give data meaningful names.

    extract data from the us er.

    store data.

    Welcom e back. Let's get right to it, shall we? In Python, explicit  is better than implicit . The interpreter won' t try to co nvert the s tring"3.14159" into a number for you implicitly—if you try to add that string to the integer 1, you'll get an error message:

    We'll talk about that mo re later in the lesson; for no w, just let those terms marinate in your mind. In the last lesso n, you saw ho wto represent string and numeric data in Python programs, and use the print() function to send express ion values to the user.Now we'll lo ok at how to s tore data and how to extract data from the user. Because interactive user input arrives to us in s tringform, we'll also need to be able to convert strings into o ther data types.

    Binding Values to Names

    Most programming languages let you name your data. Giving meaningful names to data makes your code eas ier toread and helps you to recall its purpose. It also allows you to run the same code with different data values. And mostimpo rtantly, giving your data meaningful names means you can refer to the same piece o f data at different places in

    your program: you can store data and then use i t later.

    In Python, a value is given a name with the assignment statement . In its s imples t form, the assignment statement cons ists o f a name, an equals s ign, and a value. The value can be a single data item o r an express ion.

    Click to start a new interactive ses sio n, and type these Python statements:

    INTERACTIVE SESSION:

    cold1:~$ python3>>> r = 32>>> pi = 3.14159>>> area = pi * r ** 2

    >>> print(area)3216.98816>>> item = { 'link': "http://holdenweb.com", 'value': 99.99 }>>> targetURL = item['link']>>> print(targetURL)http://holdenweb.com>>> lst = range(5)>>> print(lst)range(0, 5)>>> r = r + 1>>> print(r)33

  • 8/19/2019 Python 1 v2.pdf

    17/133

    These assignment  statements al l have pretty much the same format: name = value . They don't representmathematical equations, they are instructions to the computer . The statements are telling the computer to associate thevalue on the right side o f the equals s ign with the name o n the left side o f it. Once a name is bound to a value, it stays

    that way unless you change it.

    When you read a statement like r = r + 1, be sure to read it like a programm er, not a math student! For us , it means totake the value currently associated  with the name r , add one to it, and then asso ciate this new  value with the name. So if the value o f r was 1112 before the statement was executed, it would be 1113 afterward.

    Names in Python

    Every programming language has rules about which names are acceptable. In Python, the interpreter requiresevery name to begin with a letter (upper- or lower-case) or the underscore character. The rest of the name canbe made up o f letters, digits, or underscores. So, i, _privat e , CamelCase , and very_long_name_127 areall valid names . But 12_name  isn' t valid, because it begins with a digit. my-name is also invalid, because itcontains a hyphen.

    Namespaces and Object Space

    Values in Python are sto red in memo ry allocated from a heap (also known as "object space"). The heap is anexpandable storage s pace. Namespaces ho ld names, which refer to values (objects in o bject space). Memo ryusage in Python is conveniently automatic. When you bind a name to a value with an assignm ent statement,

    that binding takes place in the "current namespace." In a complex Python program, namespaces are createdand destroyed continually.

    Each Python file you create is a module. Each module has its o wn namespace (often called the global namespace). An ass ignment statement at module level affects the mo dule's global namespace. When the

    interpreter needs the value asso ciated with a specific name, it looks for the name in a predefined list of 

    places. For module- level code, there are only two namespaces to co nsider: the module global names paceand the built-in namespace that holds Python' s es sential functions . You'll learn to write functions and classeslater when we create instances o f classes . Every time you call a function o r create a new class or ins tance, thePython interpreter creates a new namespace. That namespace becom es unavailable when the related o bjectis destroyed.

    Start the interactive interpreter window again and try these co mm ands (remember, the >> > is a prompt, notso mething you have to type):

  • 8/19/2019 Python 1 v2.pdf

    18/133

    INTERACTIVE SESSION:

    cold1:~$ python3>>> a = 23>>> dir()['__builtins__', '__doc__', '__name__', '__package__', 'a']>>> dir(a)['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__','__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__

    ge__', '__getattribute__','__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__','__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__','__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__','__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__','__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__','__sub__', '__subclasshook__','__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

    Note You may s ee different results.

    Cons ider these questions and ans wers as they relate to the code you just typed:

    Q. In which namespace was a value bound to a? A. The module global namespace o f the interactive s ession.

    Q. In which names pace did the interpreter locate the dir() function? A. The built- in namespace.

    Q. Which namespace does dir() report on when called with no argument? A. The module global namespace.

    More Python Syntax Basics

    Line Continuations

    Under normal circums tances, each line o f your Python program is a single s tatement. The exceptions arewhen a line is explicitly continued by the addition o f a backslash, or when a line ends before an opening

    paired delimiter (curly bracket, parenthesis, or square bracket) is closed. When you enter statements andexpressions in the interactive interpreter, you normally see a >> > prompt, indicating that the interpreter iswaiting for yo u to enter a new statement or expressio n. If you see a .. . prom pt instead, it means the interpreter does not regard the current statement o r expression as complete. There are different ways to lay o ut a Pythonass ignment. These next few assignments all bind the value 927 to the name "a." Type these commands in an

    interactive sessio n:

  • 8/19/2019 Python 1 v2.pdf

    19/133

    INTERACTIVE SESSION:

    cold1:~$ python3>>> z = 100>>> a = (3 + z) * 9>>> print(a)927>>> a = \... (3 + z) * 9>>> print(a)

    927>>> a = (... (3 + z)... * 9... )>>> print(a)927

    Multiple Statements on One Line

     Although multiple statem ents o n a single l ine can be separated by semico lons , we don't recommend it. Asyou'll dis cover down the road, leading spaces are significant! Python us es leading space to mark blocks o f 

    code, so if you s tart a command line with a space, the command generally will fail with an syntax error.

    Let's try a few mo re examples in the interactive interpreter windo w (if you closed it, click to start a newinteractive ses sio n):

    INTERACTIVE SESSION:

    cold1:~$ python3>>> a = 1>>> z = 2>>> print(a, z)1 2>>> a = 1; z = 2

    >>> print(a, z)1 2>>> a, z = 1, 2>>> print(a, z)1 2

    In our first example, we have a different single assignment statement. Next, those same two statementsappear, separated by a semico lon. Finally, there is an example o f what is called an unpacking assignment .This has a comma-separated list o f names o n the left and another list of values o n the right. Each value isbound to the corresponding name.

    Indentation

    In the programs you've written so far, all statements have started in the first column of the line. Statements canbe indented when they are the object of one o f Python's compound statements. A set of statements at thesame indentation level (including any code indented within a s tatement) form a block, also called a suite. We'll

    loo k more clos ely at suites when we discuss compo und statements in future lesso ns. For now, just be sureto s tart your lines without any leading spaces.

    Comments

    In a Python program text, the "#" character (pound sign, octothorp, hash mark, call it what you will) introduces

    a com ment. The com ment runs to the end o f the line—it is disregarded by the interpreter. Comments shouldonly o ccur where whitespace is legal (for readability). Com ments help o ther programmers to make sense o f your program, so include them o ften. As your skill level increases, your comments may be less detailed, butyour code s hould always be easy to read for bo th intent (the desired result of the code) and implementation(the way the code accom plishes the intent). Use comments as necessary to keep your code readable!

  • 8/19/2019 Python 1 v2.pdf

    20/133

    Docstrings

     Any Python expression is a valid s tatement (though statements are never  express ions ). A string on its own,as the first statement of various Python constructs (like module, function, class , and method), is interpreted bymany too ls as do cumentation. Using a three-quo te string allows you to add lots o f documentation to your programs. Use docs trings extensively to do cument your code. Later examples will show yo u so me practical

    docs tring content. For now, let's try a new program. Type this code in the editor window below:

    CODE TO TYPE:

    ## This is a program that prints its own docstring#"""print_docstring.py prints its own docstring(the string that's the first executable statement,which in this case extends to three lines)."""print(__doc__)

     Save the program in your /pyt ho n1 folder as print_docstring.py, and go to an interactive sessio n tochange to the /python1 folder and run i t:

    INTERACTIVE SESSION:

    cold1:~$ cd python1 cold1:~/python1$ python3 ./print_docstring.pyprint_docstring.py prints its own docstring(the string that's the first executable statement,which in this case extends to three lines).cold1:~/python1$

    Note __doc__ in t he Module Nam espace : In the code abo ve, the interpreter reso lves the name __doc__  by loo king in the mo dule namespace. The name is always present, but if the mo dulehas no docs tring, it is s et to the special value None .

    Now what happens if we remove the docstring—what happens when the print statement runs? Turn the stringinto an assignment statement by putting "x = " at the beginning of the first line after the com ments, as s hown:

    CODE TO TYPE:

    ## This is a program that prints its own docstring#x="""print_docstring.py prints its own docstring(the string that's the first executable statement,which in this case extends to three lines)."""print(__doc__)

    Save and run it. Can you think of any o ther interesting variations on this program? Go ahead and try a few of 

    your own experiments!

    Using String Methods: Case Conversion

    In the example below, replace each comment with a Python expression that returns the value described.

    Do not use any literal strings—write expressions using methods of s only!  For example: s.capitalize() .

    To see a lis t of the methods of a string, use dir("") in the interactive interpreter.

    Type in this code:

  • 8/19/2019 Python 1 v2.pdf

    21/133

    CODE TO TYPE:

    ## case_convert.py#s = "this Is a Simple string"slower = # s converted to lower case

  • 8/19/2019 Python 1 v2.pdf

    22/133

    INTERACTIVE SESSION:

    cold1:~$ python3>>> n = int(input("Enter a number: "))Enter a number: 33>>> x = float(input("Another number: "))Another number: 45.67>>> n, x(33, 45.67)>>> y = float(input("Final number: "))

    Final number: abc.defTraceback (most recent call last):  File "", line 1, in   ValueError: could not convert string to float: abc.def>>> 

    Feel free to try other inputs. Observe, too , that the floating-po int number system used on com puters cannotexpress 45.67 exactly, though it gets pretty clos e. This us ually only happens with floating-po int numbers, notintegers. If you haven't programmed before, just remember these " rounding errors" make arithmetic slightlyinexact, so be sure they don't make a difference to yo ur results. They can sometimes add up surprisingly

    quickly. In the last of the three cases above, the user is entering text that canno t be converted into a number.So Python calls the action to a halt with an exception traceback  that tells yo u what happened. (Pretty coo l,huh?)

    Because the observations were made in an interactive interpreter after the traceback, you s ee ano ther >> >prompt. If an unhandled exception occurs when running a program, the program run is terminated. But thisisn't always your des ired result. Fortunately, there are ways you can handle these exceptions and avoid

    program termination. For no w, let's jus t type carefully when we need to provide numeric input!

    Calculating with Stored Values

    Okay! Let's put all this together in a sho rt sample program that asks for the height, width, and depth o f a roo m, andcalculates the surface area o f the walls. It'll give yo u an idea of ho w real code is written.

    Type this code in the editor window belo w:

    CODE TO TYPE:

    ## wall_area.py#h = float(input("Room height: "))w = float(input("Room width : "))d = float(input("Room depth : "))area = 2 * (h * (w + d))print("Area of walls:", area)

     Save it in your /pyt ho n1 folder as wall_area.py, and run it in an interactive sess ion a few times , using differentinputs:

    INTERACTIVE SESSION:

    cold1:~/python1$ python3 ./wall_area.pyRoom height: 12Room width : 14Room depth : 32Area of walls: 1104.0cold1:~/python1$

    What happens if you give the program a no n-numeric input? (Never fear. We'll show you ho w to deal with thos ecircumstances later.)

  • 8/19/2019 Python 1 v2.pdf

    23/133

    Getting It Done

    We're covering a lo t of material in these early lessons , and we still have a long way to go . You're doing really well sofar—stick with it—see you in the next lesson!

    Copyright © 1998-2014 O'Reilly Media, Inc.

    This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

    http://creativecommons.org/licenses/by-sa/3.0/legalcode

  • 8/19/2019 Python 1 v2.pdf

    24/133

    Making Decisions: The if Statement

    Lesson Objectives

    When you complete this lesson, you will be able to:

    take different actions depending o n whether a specific condition is true.

    compare and evaluate two values using the comparison o perator.

    determine whether one string appears ins ide ano ther, using the in  test.

    test for several different conditions.

    use the elif  keyword instead of else ... if ..

    use the or  operator between the conditions.

    So far, we've covered basic types of statements in Python—the assignment statement and the statement that calls a function.The function we've used most o ften is print(), which has the handy side effect of printing out the value of o ne or mo reexpressions.

    One o f the mo st commo n needs in programming is to make a decisio n and act on it—for example, doing o ne thing if acustomer answers Yes to a question, and another if they answer No. The if  statement gives us this power, allowing us to takedifferent actions depending on whether a specific condition is true.

    Conditions in Python

    In order to be able to make a decisio n, you need to evaluate so me condition. The conditions we compare mo stfrequently in Python are o f two values, using the compariso n operator. You can com pare for various kinds o f equality

    or inequality:

    Operat o r T rue when

    a == b a and b have the same value

    a != b a and b do no t have the same value

    a < b a's value is less than b's

    a b a's value is greater than b's

    a >= b a's value is greater than or equal to b 's

    Com paring numbers is pretty intuitive, but keep in mind that you can't use these operators to compare com plexnumbers. The operands are two-dim ensio nal, so they can't be laid out in a straight line; simple com parisons like thataren't valid. Instead, you must compare the abso lute values o f complex numbers, using the abs() function.

    Com paring strings is fairly straightforward as lo ng as you can alphabetize a lis t of items. The characters in s tringshave a defined o rder, so metimes called the collation sequence. Let's s uppos e we want to compare strings a and b.The interpreter looks at the first character of each s tring. If the first character of a occurs earlier in the collation sequencethan the first character of b, then a is less than b. If the first character in a is greater than the first character in b, then a isgreater than b. If this initial attempt to co mpare the strings is inconclusive, then the next characters in the sequence o f the strings are compared until a determination is made.

    If the end of one of the strings is reached and additional characters still remain in the other, then the longer of the twostrings is greater. If both strings have exactly the same characters in them, they are cons idered equal. You m ay see the

    term " lexical compariso n" used to describe this method o f comparing strings. Start a new terminal sess ion and verifythe follo wing results:

  • 8/19/2019 Python 1 v2.pdf

    25/133

    INTERACTIVE SESSION:

    cold1:~$ python3>>> a = 23.0>>> b = 22>>> a == bFalse>>> a != bTrue>>> a < b

    False>>> a >> a > bTrue>>> a >= bTrue>>> p1 = "Python">>> p2 = "Perl">>> p1 == p2False>>> p1 != p2True>>> p1 < p2

    False>>> p1 >> p1 > p2True>>> p1 >= p2True>>> "this+" > "this"True>>> "that" == "that"True>>> "That" == "that"False>>> "That".upper() == "thAT".upper()True>>>

    The last tests show that string compariso ns are case-sens itive. If you want to avoid case- sens itivity, use the upper()or lower()  method to co nvert both strings to the same case.

    In addition, you can determine whether one s tring appears ins ide ano ther, using the in  test:

    INTERACTIVE SESSION:

    cold1:~$ python3>>> x = "nan"

    >>> s = "Banana">>> x in sTrue

    The result o f the expressio n x in s is True when the substring x appears so mewhere inside the string s. You can alsotest to find out whether a string is a member of a lis t or a tuple (a tuple is a sequence or o rdered list, of finite length); xin lt  is true if x is an element of lt , whether lt  is a lis t or a tuple.

     Also, strings have several methods fo r you to use to determine whether the string has s pecific characteris tics. Themo st impo rtant ones are shown in this table:

    Met hod Example T rue when ...

    s.startswith(x) String s starts with the substring x

  • 8/19/2019 Python 1 v2.pdf

    26/133

    s.endswith(x) String s ends wi th the substring x

    s.isalnum() All characters in s are alphanumeric and there is at least one character 

    s.isalpha() All characters in s are alphabetic and there is at least one character 

    s.isdigi t() Al l characters in s are digi ts and there is at least one character  

    s.islower() All cased characters in s are lowercase and there is at least one cased character 

    s.isupper() All cased characters in s are uppercase and there is at least one cased character 

     All o f these conditio ns can be tested individually or, as we' ll see later, in combination. You can use the if  statement tochoo se whether or no t to execute one o r mo re statements by testing a condition and executing the statement if  thecondition is true. You can also choose which sets o f statements to execute.

    Making Decisions: if Statements

    Express ions that the Python interpreter will evaluate as True or False (also called conditions) can be used to modify theactions o f your program, using a basic if  statement.

    The if  statement begins with the keyword if , follo wed by an express ion, and ends with a colo n. This line is alwaysfollowed by an indented suite—one o r mo re statements with an indentation level greater than that of the if  line. If thecondition is true, then the indented suite is executed. All the statements in the suite must be indented to exactly thesame level. In the Python world, we use four additional spaces for each new indentation level.

    Okay, let's program!

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Detect any mention of Python in the user's input."""

    uin = input("Please enter a sentence: ")if "python" in uin.lower():  print("You mentioned Python.")

    Note

    By default, the CodeRunner editor and your web browser likely display tab characters as taking up eightspaces. It is proper Python programming practice to indent four spaces. As s uch, we recommend that

    you indent code using the space bar rather than the Tab key. Alternatively, if you are familiar with a Linuxtext edito r, you are welcome to use emacs or vim, which are available on the OST server.

    Save it in your /pyt ho n1 folder as find_python.py and run it:

    INTERACTIVE SESSION:

    cold1:~$ cd python1cold1:~/python1$ ./find_python.pyPlease enter a sentence: My python is a happy snake.You mentioned Python.cold1:~/python1$ ./find_python.py

    Please enter a sentence: There's a pylon in the road.cold1:~/python1$

    Run the program s everal times to verify that when the string "python" is present in your input, the program prints "You

    mentioned Python." and when "python" is NOT present, it does not. Make sure you test in all circumstances.

    NoteBecause we added #!/usr/local/bin/pytho n3 at the beginning o f the program, we didn' t need to cal lpython3 specifically in the interactive ses sio n. We'll use this from now on in our programs, but it mightnot work on other systems.

  • 8/19/2019 Python 1 v2.pdf

    27/133

    Choosing Between Alternatives: the else Clause

    The basic if  statement allows you to choos e whether to execute an indented suite made up of one or mo restatements. If you want to execute one set of actions if the condition is true and execute another set if it is false, add an

    else  clause to the if  s tatement. The else  clause follo ws the first indented suite, and is follo wed by the indented suiteto execute if the if  condition is false. When the condition is true, the first suite is executed; when it is false, the secondsuite is executed. Modify find_python.py as sho wn:

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Detect any mention of Python in the user's input."""

    uin = input("Please enter a sentence: ")if "python" in uin.lower():  print("You mentioned Python.")else:  print("Didn't see Python there.")

     Save and run it. Test your pro gram several times , using bo th types o f input. When your program includes alternativebehaviors, it's impo rtant to test all the pos sible paths.

    Multiple Choice Decisions

    Sometimes a decision isn't as s imple as choo sing between A or B. You may need to test for several differentconditions, then take an action on the first condition that's true. In this case, using if ... else repeatedly gives rise to asmall problem. Chained if ... else s tatements move co de to the right. else  adds a level o f indentation, so if we have along chain of tests, the code m oves o ver towards the right margin, which can make your co de difficult to read. That'snothing we can't handle, though! Take a lo ok:

    OBSERVE:

    if (condition 1):  suite 1else:  if (condition 2):  suite 2

      else:  if (condition 3):  suite 3  else:  ...

    To overcom e this, Python has the elif  keyword, which you can use ins tead of else ... if . Because a single elif incorporates the functions of bo th the else  and the if  statements, elif  does not introduce an additional level of indentation:

    OBSERVE:

    if (condition 1):  suite 1elif (condition 2):  suite 2elif (condition 3):  suite 3else:  ...

    Both of our examples do the same thing, but the second one is easier to read, and presents the chain of choices muchmore clearly. The else  clause at the end is o ptional; if it's included, then the suite under it will be executed if  none of the conditions are true. Without an else  clause, the program won't do anything at all if none o f the conditions are true(it will just continue on the line after suite 3).

    Now suppose we want to analyze a us er's input to detect different programm ing languages, and respo nd if we don't

    find any of our languages mentioned. Modify your program so that it uses elif  to select among the alternatives. Edit

  • 8/19/2019 Python 1 v2.pdf

    28/133

  • 8/19/2019 Python 1 v2.pdf

    29/133

    CODE TO TYPE:

    #!/usr/local/bin/python3target = 63guess = 0 while guess != target:

    guess = int(input("Guess an integer: "))  if guess > target:  print ("Too high...")  elif guess < target:

      print ("Too low...")  else:  print ("Just right!")

     Save it in your /pyt ho n1 folder as guesser.py and run it, entering a few guesses. For every guess you m ake, theprogram reports whether your guess is too high or too low. With every guess , you clo se in o n the target number.

    Below is the output fo r a typical run of the program:

    INTERACTIVE SESSION:

    cold1:~/python1$ ./guesser.pyGuess an integer: 22Too low...Guess an integer: 88Too high...Guess an integer: 50Too low...Guess an integer: 67Too high...Guess an integer: 58Too low...Guess an integer: 63Just right!

    Wrapping It UpYou're looking good so far. But there's plenty mo re to learn still!

    In the next lesson, we'll look at how we can write more powerful programs us ing loops. See you there!

    Copyright © 1998-2014 O'Reilly Media, Inc.

    This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

    http://creativecommons.org/licenses/by-sa/3.0/legalcode

  • 8/19/2019 Python 1 v2.pdf

    30/133

    Iteration: For and While Loops

    Lesson Objectives

    When you complete this lesson, you will be able to:

    use a f o r  s tatement to lo op over the characters in a s tring you enter, and an if  statement to determine whether eachcharacter is a vowel.

    execute a break during a loop to terminate the loo p immediately.

    Glad to s ee you here again! We've covered a couple o f basic "object" types in Python—strings and numbers. We've also

    encountered one o f Python's sequence types—strings. Other Python sequence types may contain mo re than just characters.But before we try to understand Python' s co ntainer objects, let's take a look at lo ops .

    Modern com puters execute millio ns or even billio ns o f instructions per second. If we had to write out every instruction, it wouldtake a lifetime to write less than a second's worth o f code. Fortunately, we have loo ps at our disposal. Loo ps tell the computer to execute the same sequence o f actions over and o ver. Through the use o f loo ps, we can tell the com puter to repeat the sameoperations on different pieces o f data, without typing the instructions again each time.

     At the end of the las t less on we wo rked with a pro gram that contained a while  loo p. Using a while  loo p, we can apply the samelogic repeatedly—in this case, until a specific condition is true. Similarly, f o r  loo ps allow you to repeat the same actions on

    each of a number o f things. We'll take a closer lo ok at f o r  loo ps first.

    A Basic For Loop

    Suppose you wanted to count the number of vowels in a string. How would you approach this task? Traditionally, you

    would set a counter to zero, then loo p over the characters in the string, adding one to the counter when a vowelcharacter was fo und. After all the characters in the string were processed, the counter would co ntain the total number o f vowels in the string.

    Let's try an example that uses a f o r  s tatement to lo op over the characters in a s tring you enter, and an if  s tatement todetermine whether each character is a vowel. Type this code in the editor window:

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Counts the vowels in a user input string."""

    s = input("Enter any string: ")vcount = 0for c in s:  if c in "aeiouAIEOU":  vcount += 1  print("C is ", c, "; Vowel count:", vcount)

     Save it in your /pyt ho n1 folder as vowel_counter.py  and run it in the Terminal tab. The "Enter any string:" promptappears. The program co unts the number of vowels in any string you enter and returns a total.

    The f or  statement is follo wed by an indented suite (in this case, a single if  s tatement). When the f o r  s tatementexecutes, the name s is bound to a s tring. For each character in the string, the interpreter executes the indented suitewith the name c, bound to the current character. So, suppo se yo u entered "the." The first time through the lo op, c wouldbe "t." The second time, it would be "h," and the third time, it would be "e." Each time around, the if  statement checks tosee whether c contains a vowel. If it does, we add 1 to the vcount  counter; otherwise no thing happens because thereis no else  clause for the if . After all characters have been pro cessed, vcount  contains a count of the vowels withinthe input string.

    We had the program print every time it went through the loop so you could see ho w it works. Now, let's change our program to print only when it finishes reading the input string. To do that, we simply unindent the print statement so that

    it falls o utside of the loop. We'll also remove the code that prints the value of "c":

  • 8/19/2019 Python 1 v2.pdf

    31/133

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Counts the vowels in a user input string."""

    s = input("Enter any string: ")vcount = 0for c in s:  if c in "aeiouAIEOU":  vcount += 1print("C is ", c, "; Vowel count:", vcount)

     Save and run it again to see the difference.

    Breaking Out of a Loop

    The f or  loo p is useful fo r processing each element in a sequence. We'll loo k at mo re complex sequences in the nextlesson, but for now we'll just use s trings.

    Suppose you wanted to know where the first space appears in a string. One way to find out would be to loop through

    the string, counting characters until you found a space. But once you found it, how would you stop counting? Youcould s et a flag to tell your computer to s top counting after you found the space and com pleted the loop, but then whybother completing the loo p? It would be mo re efficient to stop loo king at characters o nce you found the first space. Todo that, we use the break s tatement. If you execute a break during a loop, the loo p terminates imm ediately.

    Let's write a program that prints out the position where the first space appears in a s tring. Enter this code:

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Program to locate the first space in the input string."""

    s = input("Please enter a string: ")pos = 0for c in s:  if c == " ":  break  pos += 1

    print("First space occurred at position", pos)

     Save it in your /pyt ho n1 folder as space_finder.py and run it:

    INTERACTIVE SESSION:

    cold1:~$ cd python1cold1:~/python1$ ./space_finder.pyPlease enter a string: Space, the final frontier.First space occurred at position 6

    The count (po s) starts at 0 because that's the first pos ition o f a string or any o ther Python sequence. Each timethrough the lo op, we test to see if the current character (c) is a space (" "). If it is, we hit the break, exit the loo p, andprint the value from po s; otherwise we add 1 to po s and the loo p continues. Be sure you get things in the right order!Incrementing the count before testing and terminating the loop would cause what's known as an "o ff by 1 error."

    But what does the program do if there's no space in the input? I'm glad you as ked! It prints out a result as though a

    space follo wed the input string, because the loo p terminates after it has inspected each character in the string. Check itout in your program by running it with an input containing no spaces.

    We need separate logic to verify that there really is a space in the string. Python loo ps come with such extra logic builtin, in the shape of the optional else  clause. This clause is placed at the sam e indentation level as the f o r  or whileloop that it matches, and (just as with the if  statement) is follo wed by an indented suite of o ne or more s tatements.This suite is only  executed if the loop terminates no rmally. If the loop ends because a break statement is executed,then the interpreter just skips o ver the else  suite. In the case o f the space detection program , we execute the breakwhen we detect a space, so an else  clause on the f o r  loop would o nly run if there were no spaces in the input.

  • 8/19/2019 Python 1 v2.pdf

    32/133

    We need to mo dify our code a bit more. In the first version, the print  was located at the end o f the loop, where italways runs no matter what the outcome o f the testing. Now we want it to be part of the suite guarded  by the if statement, so it only runs when a space is found. Modify your s pace_finder.py file as shown:

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Program to locate the first space in the input string."""

    s = input("Please enter a string: ")

    pos = 0for c in s:  if c == " ":  print("First space occurred at position", pos)  break  pos += 1else:  print("No spaces in that string")print("First space occurred at position", pos)

     Save and run it with a string that contains a space and then with a string that does n't. The program runs just fine either 

    way.

     As yo ur programs become mo re complex, you wil l find that there are so metimes di fferent ways to expres s the same

    logic. In thos e cases, you sho uld "do the simplest thing that works." For example, in the body o f the loop, we could have put the statement that increments the counter in the suite of an else  clause. We chose not to use an elsebecause if the expression c == " "  tests as true, the break statement will guarantee that po s isn't incremented (byimmediately exiting from the loo p) before the assignm ent statement is executed.

    While Loops

    The f or  loo p is useful when you want to apply the same lo gic to each member of a sequence. But som etimes (like inthe guessing game at the end of the last lesso n) you do n't have a finite sequence; you want actions to be repeateduntil so me condition is true.

    Suppose we want to split a string into words. Defining words by the spaces between them, we can locate the firstspace with a f o r  loop. Now we can modify the string each time we find a word (by re-binding the name o f the string to a

    new string with the word removed) until there are no m ore words left. That's the idea behind the next program. Create anew file as sho wn:

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Program to split a sentence into words."""

    s = input("Please enter a sentence: ")while True:  pos = 0  for c in s:  if c == " ":  print(s[:pos])

      s = s[pos+1:]  break  pos += 1  else:  print(s)  break

     Save it in your /pyt ho n1 folder as sentence_splitter.py and run it. The while T rue clause in this program sets upa loop that will keep running until logic in the if/else  suites causes a break. When you see while T rue in a program,either the programm er has included a break statement to terminate the loop, or the program is des igned for continuous operation—or  the programmer has made a terrible mistake and the program will never stop running! In thiscase, it's the former: the break to terminate the while  loo p is inside the f o r  loop's else  clause. Run the program andenter a sentence. You sho uld see each wo rd in the sentence on a separate line.

  • 8/19/2019 Python 1 v2.pdf

    33/133

    Note In s[:pos] and s = s[pos+1:], we use a feature that we haven' t covered yet. Stay tuned!

    Of course this program isn't perfect—very few programs are! Try entering a sentence where the words are separated bymultiple spaces. The program prints empty lines, corresponding to the "empty words" between the spaces. We can fixthat, though. One way would be to remo ve leading spaces before going into the f o r  loo p each time. Let's mo dify our sentence_splitter.py to allow multiple spaces between words. Edit the program as sho wn:

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Program to split a sentence into words."""

    s = input("Please enter a sentence: ")while True:  while s.startswith(" "):  s = s[1:]  pos = 0  for c in s:  if c == " ":  print(s[:pos])  s = s[pos+1:]  break  pos += 1

      else:  print(s)  break

    Save and run it.

    When you run your updated program, you can enter as m any spaces as you like between the words and still get oneword per line in the output. Can you figure out how you might use or  to ignore extra tabs between wo rds? What part o f the program would you need to change to treat tabs as completely equivalent to spaces? (Hint: you wo uld have toaccept sentences with just tabs between the words.)

    Terminating the Current Iteration

    The break statement can be used to terminate either a f o r  or a while  loop. There is ano ther statement you can use toterminates o nly the current iteration of a lo op, moving o n to the next iteration immediately.

    In the final example for this less on, we'll process lines o f input from the user. The user will indicate the end of their input by entering a blank line (sim ply pressing the Enter  key), but we want them to be able to add comments to their input by entering lines beginning with the #  character. These lines sho uldn't be processed; they are just there to info rmthe reader. (Python als o accepts comments—the #  character tells the interpreter to igno re everything els e up to the endof the line). We aren't especially concerned with the process ing that's done on each line, so in this example we'll justuse the len() function to print.

     A com ment should be indicated by the first printable character. Create a new file as shown:

    CODE TO TYPE:

    #!/usr/local/bin/python3"""Demonstrating the continue statement."""

    while True:  s = input("Enter a line (or Enter to quit): ")  if not s:  break  if s.startswith("#"):  continue  print("Length", len(s))

    Save it in your /pyt ho n1 folder as length_counter.py and run it. Enter several lines, including at least onecomment line that begins with "#." Co mment lines are processed differently from regular lines because o f thecontinue  statement, which immediately causes the program to lo op and ask for ano ther input. There are other ways

  • 8/19/2019 Python 1 v2.pdf

    34/133

    you co uld have achieved the same result.

    Feel the Power

    Once you understand how loo ping logic works, you' re well on the way to comprehending the real power of computers.Loo ping allows you to tell the computer to repeat the same set of instructions again and again and again...

    We must confess , there are easier ways to perfo rm the tasks that you programmed in this lesso n, but we want you tounderstand what's going on behind the scenes first. Start or switch to an interactive ses sio n and enter the followingexpressions:

    INTERACTIVE SESSION:

    >>> "spaces are our friends".find(" ")6>>> "What\tis a word?".split()['What', 'is', 'a', 'word?']>>>

    The find()  string method locates a given character inside the string (it finds the first occurrence of the string passed asits argument). The split() s tring method, when called without arguments, splits the string up into its cons tituent words,which are assumed to be separated by one o r mo re white space characters. The strings ins ide the square brackets

    constitute a list . We'll be lo oking at those (and their cous ins, the tuples) in the next lesso n.

    Well done. Goo d for you for s ticking with it! Now you have a grasp o f a lot of the basics, you'll be able to take on mo re

    complex programming challenges. See you at the next less on!

    Copyright © 1998-2014 O'Reilly Media, Inc.

    This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

    http://creativecommons.org/licenses/by-sa/3.0/legalcode

  • 8/19/2019 Python 1 v2.pdf

    35/133

    Sequence Containers: Lists and Tuples

    Lesson Objectives

    When you complete this lesson, you will be able to:

    write Lis ts and Tuples.

    access the individual elements in a s equence with indexing .

    index and slice elements.

    modify lists.

    use a third com ponent o f the slice s pecification: the stride.

    determine whether a sequence contains a specific value, using the in  keyword.

    Welcom e back, my favorite student! So far, we've covered basic o bject types in Python, such as strings and numbers. Nowwe're ready to loo k at Python's "container" objects, s tarting with lists and tuples. Both lists and tuples are sequence types.Because strings are sequence types as well, much of what we learn here can be applied to strings as well.

    Sequence types have a specific order , so it's easy to spot a s tring's first and last characters. Similarly, lists and tuples presentelements in a particular order. Each element  o f a sequence is numbered. The numbering always s tarts at zero. You refer to an

    individual element by following the sequence name with a number in s quare brackets [ ].

    Lists and Tuples

    Python uses bo th lists and  tuples. In general, tuples are used when the pos ition o f an element indicates s omethingabout its capability, and lists are used to ho ld elements that will be treated in the sam e manner. Python does n't enforce

    these constraints, though; the only hard and fast rule for us ing lists and tuples is don't use tuples if you want to changethe sequence. Tuples are primarily fo r use when you need a no n-modifiable sequence.

    Writing Lists and Tuples

    Sometimes you'll want to write the contents o f a list right inside o f your code. To do that, write a comma-separated list

    of the element values, surrounded by square brackets [ ].

    Tuples are usually written as a comma-separated lis t of values surrounded by parentheses ( ) rather than brackets [ ],but in many cases the parentheses () are optional. (Okay, I will refrain from including illustrations of brackets [ ] andparentheses ( ) now. You get the picture, right?) The interactive interpreter always puts parentheses around a tuplewhen asked to display its representation, and we recom mend yo u do the same, in o rder to facilitate readability.

    Let's lo ok at som e sequences in action. Start an interactive terminal s ess ion and type:

  • 8/19/2019 Python 1 v2.pdf

    36/133

    INTERACTIVE SESSION:

    cold1:~$ python3>>> lst1 = [1, 3, 5]>>> lst2 = [2, 4, 6]>>> tup1 = (9, 7, 5)>>> tup2 = (8, 6, 4)>>> dir(lst1)['__add__', '__class__', '__contains__', ... , 'append', 'count', 'extend','index', 'insert', 'pop', 'remove', 'reverse', 'sort']

    >>> dir(tup1)['__add__', '__class__', '__contains__', ... , 'count', 'index']>>> lst1+lst2[1, 3, 5, 2, 4, 6]>>> tup1+tup2(9, 7, 5, 8, 6, 4)>>> lst1+tup1Traceback (most recent call last):  File "", line 1, in  TypeError: can only concatenate list (not "tuple") to list>>> clist = [lst1, lst2, tup1, tup2]>>> print(clist)[[1, 3, 5], [2, 4, 6], (9, 7, 5), (8, 6, 4)]

    The results of the calls to the dir() function show that a list has methods that a tuple doesn't have. We abbreviated theoutput by remo ving many of the special names beginning with a double undersco re. We'll learn more about thos emethods later, but for now we'll focus on the regular methods.

    You can put whatever you like in a list. Usually you'll enter simple values like s trings and num bers. The clist  lis t in theexample above contains two o ther lists and two tuples.

    Accessing Sequence Values

    Once you have created a sequence, you can access its individual elements us ing indexing . To index a single elementfrom a sequence, you follow it with a numeric value in s quare brackets (remember—the first element is numberedzero !). You can also take slices from the sequence, creating a new and us ually smaller sequence. To slice a s equence,

    you write two numeric values , separated by a colo n (:), inside the square brackets. If you o mit the first value, the newsequence starts with the first element of the sliced sequence. If you o mit the last value, the new sequence ends with its

    last element. Continue the interactive terminal ses sio n as s hown:

    INTERACTIVE SESSION:

    >>> clist = [1, (2, 3, 4), "a", "Bright", "c"]>>> clist [1](2, 3, 4)>>> clist[1][1]3>>> clist[3][1:3]'ri'>>> stuff = clist[2:4]>>> stuff['a', 'Bright']>>> stuff2 = clist[2:5]>>> stuff2['a', 'Bright', 'c']>>> stuff[0]'a'>>> "Strings are sequences too"[:7]'Strings'

    Indexing and slicing are fundamental operations in Python, so make sure that you understand why each expressio nevaluates the way it does . Be aware that when you slice a s equence, the second index isn't the index of the last

  • 8/19/2019 Python 1 v2.pdf

    37/133

    element in the slice. This is actually very useful. It would be co nfusing if clist[2:4] didn't give you a list 2 elementslong, so element 4 isn't included in that slice. So, to get the fourth element in our slice, we referenced the nonexistentelement 5. Because s trings are also sequences, we can chop s trings up without too much difficulty.

    Modifying Lists

     Although s trings and tuples are also sequences, they are immutable. Once created, they can't be changed (althoughyou can still index and s lice them to extract individual elements o r sub-sequences). Lists, however, can be changed. Inthe same way that you can bind a new value to a name with an assignment, you can also bind a new value to anelement of a lis t. Let's check out one way you can m odify a list. Start or continue the interactive terminal sessio n as

    shown:

    INTERACTIVE SESSION:

    >>> stuff = [1, (2, 3, 4), "a", "Bright", "c"]>>> stuff[1] = "Not a tuple">>> stuff[1, 'Not a tuple', 'a', 'Bright', 'c']>>> stuff[0] = 0>>> stuff[3] = 'b'>>> stuff[0, 'Not a tuple', 'a', 'b', 'c']>>> stuff[2:4]

    ['a', 'b']>>> stuff[2:4] = [1, 2, 3]>>> stuff[0, 'Not a tuple', 1, 2, 3, 'c']>>>

    So far, we've just been just replacing single elements of the list. It's also pos sible to replace a slice. When you do that,make sure that you also ass ign another sequence. Any sequence will do—a lis t, tuple, or s tring. If you ass ign a s tringto a slice, each character in the string becomes a new element of the list. Try experimenting with these poss ibilities.

    Because you can replace any slice of a list, you can delete the slice by assigning an empty sequence to it. But there are

    less labor-intensive ways to replace a slice of a list. Python' s de l s tatement was designed especially fo r deletingthings. You can use it o n a s ingle element or a slice. If you kno w that a list contains a certain value, but you do n't know

    the value's index, you can use the list's remove() method to delete it from the list. If the same value o ccurs mo re thanonce, only the first occurrence is deleted. Let's give it a try. Type the comm ands belo w as sho wn:

    INTERACTIVE SESSION:

    >>> dlist = ['a', 'b', 'c', '1', '2', 1, 2, 3]>>> dlist[6]2>>> del dlist[6]>>> dlist['a', 'b', 'c', '1', '2', 1, 3]>>> dlist[:3]['a', 'b', 'c']

    >>> del dlist[:3]>>> dlist['1', '2', 1, 3]>>> dlist.remove(1)>>> dlist['1', '2', 3]

  • 8/19/2019 Python 1 v2.pdf

    38/133

    Note

    In the las t example, element 2 (the integer 1) was removed, not element 0 (the string '1'). In Python,

    numbers and s trings are dis tinctive, and it doesn' t convert from one to the o ther unless you s pecificallytell it to do s o.

     Also, remember that deletio n only wo rks fo r lis ts. Deleting an element of a sequence wo uld be the sameas m odifying the sequence, and you can't modify tuples and strings.

     As we saw in an earlier example, we can add elements to a lis t. Ano ther way to include more elements is to use thelist's append() method. You call the method and give it a new element to be appended to the list. It's also pos sible to

    insert elements at a specific pos ition, and again there are two ways to do this. The simplest way is to us e the list'sinsert() method, which you call with a pos ition (index value) and a value to be inserted. Or you could also ass ign thenew value to an empty slice—any slice with the same value for the lower and upper indexes is bo und to be em pty.Let's experiment with adding new elements to a lis t. Type the commands belo w as s hown:

    INTERACTIVE SESSION:

    >>> elist = [] # The empty list>>> elist.append('a')>>> elist['a']>>> elist.append('b')>>> elist['a', 'b']>>> elist.append((1, 2, 3))>>> elist['a', 'b', (1, 2, 3)]>>> len(elist)3>>> elist[1:1][]>>> elist[1:1] = ["new second element"]>>> elist['a', 'new second element', 'b', (1, 2, 3)]>>> elist.insert(3, "4th")>>> elist['a', 'new second element', 'b', '4th', (1, 2, 3)]>>> len(elist)

    5

    One o f the limitations we run into with slice ass ignment is that the replacement must be a sequence, so we usuallyappend or insert it. If you have a sequence of elements that you want to insert, keep in mind that slice assignmentrequires much less code than mo st other techniques.

    NoteIf you call a lis t's append() method with a sequence argument (like you did with elist .append((1, 2, 3))in the example above), that entire sequence becomes the last element of the lis t.

    Slices with a Stride: Skipping Sequences

     A sl ice specifies a subsequence o f a sequence. No w suppo se yo u don't want to include every element, but ins teadyou want to use every second or third element. The easiest way to do this would be to use a third compo nent of theslice specification: the stride. The stride specifies how many elements to s kip in the slice before extracting the nextelement. The stride is s eparated from the first two components with a colo n; so your slice specification is like

    [first:last:stride].

    When you specify only two s lice compo nents, by default the stride is 1; it takes every element in the slice. A stride of 2takes every second element, and so on. Stride values can be negative as well as pos itive. Slicing always wo rks bysetting the index to the first sl icing compo nent and then increasing the index by the stride value, until the index reachesor go es past the second slicing com ponent. When the stride is negative, the first slicing component mus t be higher than the second. Type the commands below as sho wn:

  • 8/19/2019 Python 1 v2.pdf

    39/133

    INTERACTIVE SESSION:

    >>> alf = "abcdefghijklmnopqrstuvwxyz">>> alf[2:13]'cdefghijklm'>>> alf[2:13:2]'cegikm'>>> alf[2:13:-2]''>>> alf[13:2:-2]

    'nljhfd'>>> alf[13:2]''>>> alf[::-1]'zyxwvutsrqponmlkjihgfedcba'

    One way to get the reverse o f a sequence is to s lice the whole thing by om itting the first and second s lice compo nentsand then use a s tride of -1. So, if you want to replace a list with its reverse, rather than use the list's reverse() methodlst.reverse(), you can write lst = ls t[::-1]. Python sequences are nothing if not versatile!

    Other Functions and Methods to Use with Sequences

    Sometimes you'll have a string that you want to break up into a list o f words. The split() method helps you to do justthat. If you call the string without any arguments, it will split the string. If you call it with one argument (for example, aspace " "), it will use that argument as a separator, returning a lis t of the strings that appear between its o ccurrences.

    If you give a s econd argument, it sho uld be an integer. This informs the interpreter of the maximum number of times to

    recognize the sep