Augmented Assignment Operators Python Eats

It's not shorthand.

The symbol appeared in the C language in the 1970s, and - with the C idea of "smart assembler" correspond to a clearly different machine instruction and adressing mode:

Things like "", " and "", although at an abstract level produce the same effect, correspond at low level to a different way of working of the processor.

In particular those three expressions, assuming the variable resides in the memory address stored in a CPU register (let's name it - think of it as a "pointer to int") and the ALU of the processor takes a parameter and return a result in an "accumulator" (let's call it A - think to it as an int).

With these constraints (very common in all microprocessors from that period), the translation will most likely be

The first way of doing it is disoptimal, but it is more general when operating with variables instead of constant ( or ) or when translating more complex expressions (they all boil down in push low priority operation in a stack, call the high priority, pop and repeat until all the arguments had been eliminated).

The second is more typical of "state machine": we are no longer "evaluating an expression", but "operating a value": we still use the ALU, but avoid moving values around being the result allowed to replace the parameter. These kind of instruction cannot be used where more complicated expression are required: cannot be operated in place, since is required more times.

The third -even simpler- does not even consider the idea of "addition", but uses a more "primitive" (in computational sense) circuitry for a counter. The instruction is shorted, load faster and executes immediately, since the combinatorial network required to retrofit a register to make it a counter is smaller, and hence faster than the one of a full-adder.

With contemporary compilers (refer to C, by now), enabling compiler optimization, the correspondence can be swapped based on convenience, but there is still a conceptual difference in the semantics.

means

  • Find the place identified by x
  • Add 5 to it

But means:

  • Evaluate x+5
    • Find the place identified by x
    • Copy x into an accumulator
    • Add 5 to the accumulator
  • Store the result in x
    • Find the place identified by x
    • Copy the accumulator to it

Of course, optimization can

  • if "finding x" has no side effects, the two "finding" can be done once (and x become an address stored in a pointer register)
  • the two copies can be elided if the ADD is applied to instead to the accumulator

thus making the optimized code to coincide the one.

But this can be done only if "finding x" has no side effects, otherwise

and

are semantically different, since side effects (admitting is a function doing weird things around and returning an ) will be produced twice or once.

The equivalence between and is hence due to the particular case where and are applied to a direct l-value.

To move to Python, it inherited the syntax from C, but since there is no translation / optimization BEFORE the execution in interpreted languages, things are not necessarily so intimately related (since there is one less parsing step). However, an interpreter can refer to different execution routines for the three types of expression, taking advantage of different machine code depending on how the expression is formed and on the evaluation context.


For who likes more detail...

Every CPU has an ALU (arithmetic-logical unit) that is, in its very essence, a combinatorial network whose inputs and output are "plugged" to the registers and / or memory depending on the opcode of the instruction.

Binary operations are typically implemented as "modifier of an accumulator register with an input taken "somewhere", where somewhere can be - inside the instruction flow itself (typical for manifest contant: ADD A 5) - inside another registry (typical for expression computation with temporaries: e.g. ADD A B) - inside the memory, at an address given by a register (typical of data fetching e.g.: ADD A (H)) - H, in this case, work like a dereferencing pointer.

With this pseudocode, is

while is

That is, x+5 gives a temporary that is later assigned. operates directly on x.

The actual implementation depends on the real instruction set of the processor: If there is no opcode, the first code becomes the second: no way.

If there is such an opcode, and optimization are enabled, the second expression, after eliminating the reverse moves and adjusted the registers opcode, become the first.

Hands-On Python
A Tutorial Introduction for Beginners
Python 3.1 Version

Dr. Andrew N. Harrington 
Computer Science Department, Loyola University Chicago 
© Released under the Creative commons Attribution-Noncommercial-ShareAlike 3.0 United States License
http://creativecommons.org/licenses/by-nc-sa/3.0/us/

Contents

  Contents
Chapter 1.  Beginning With Python
 1.1.  Context
 1.2.  The Python Interpreter and Idle, Part I
 1.3.  Whirlwind Introduction To Types and Functions
 1.4.  Integer Arithmetic
 1.5.  Strings, Part I
 1.6.  Variables and Assignment
 1.7.  Print Function, Part I
 1.8.  Strings Part II
 1.9.  The Idle Editor and Execution
 1.10.  Input and Output
 1.11.  Defining Functions of your Own
 1.12.  Dictionaries
 1.13.  Loops and Sequences
 1.14.  Decimals, Floats, and Floating Point Arithmetic
 1.15.  Summary
Chapter 2.  Objects and Methods
 2.1.  Strings, Part III
 2.2.  More Classes and Methods
 2.3.  Mad Libs Revisited
 2.4.  Graphics
 2.5.  Files
 2.6.  Summary
Chapter 3.  More On Flow of Control
 3.1.  If Statements
 3.2.  Loops and Tuples
 3.3.  While Statements
 3.4.  Arbitrary Types Treated As Boolean
 3.5.  Further Topics to Consider
 3.6.  Summary
Chapter 4.  Dynamic Web Pages
 4.1.  Web page Basics
 4.2.  Composing Web Pages in Python
 4.3.  CGI - Dynamic Web Pages
 4.4.  Summary

Chapter 1
Beginning With Python

1.1. Context

You have probablry used computers to do all sorts of useful and interesting things. In each application, the computer responds in different ways to your input, from the keyboard, mouse or a file. Still the underlying operations are determined by the design of the program you are given. In this set of tutorials you will learn to write your own computer programs, so you can give the computer instructions to react in the way you want.

1.1.1. Low-Level and High-Level Computer Operations

First let us place Python programming in the context of the computer hardware. At the most fundamental level in the computer there are instructions built into the hardware. These are very simple instructions, peculiar to the hardware of your particular type of computer. The instructions are designed to be simple for the hardware to execute, not for humans to follow. The earliest programming was done with such instructions. If was difficult and error-prone. A major advance was the development of higher-level languages and translators for them. Higher-level languages allow computer programmers to write instructions in a format that is easier for humans to understand. For example

z = x+y

is an instruction in many high-level languages that means something like:

  1. Access the value stored at a location labeled x
  2. Calculate the sum of this value and the value stored at a location labeled y
  3. Store the result in a location labeled z.

No computer understands the high-level instruction directly; it is not in machine language. A special program must first translate instructions like this one into machine language. This one high-level instruction might be translated into a sequence of three machine language instructions corresponding to the three step description above:

0000010010000001  
0000000010000010  
0000010110000011 

Obviously high-level languages were a great advance in clarity!

If you follow a broad introduction to computing, you will learn more about the layers that connect low-level digital computer circuits to high-level languages.

1.1.2. Why Python

There are many high-level languages. The language you will be learning is Python. Python is one of the easiest languages to learn and use, while at the same time being very powerful: It is used by many of the most highly productive professional programmers. A few of the places that use Python extensively are Google, the New York Stock Exchange, Industrial Light and Magic, .... Also Python is a free language! If you have your own computer, you can download it from the Internet....

1.1.3. Obtaining Python for Your Computer

If you are not sure whether your computer already has Python, continue to Section 1.2.2, and give it a try. If it works, you are all set.

If you do need a copy of Python, go to the Downloads page linked to http://www.python.org. Be careful to choose the version for your operating system and hardware. Chosse a stable version, 3.1 or later. Do not choose a version 2.X, which is incompatible. (Version 2.6 is described in an older version of this tutorial.)

Windows

You just need to execute the installer, and interact enough to agree to all the default choices. Python works in Windows as well as on Apples and in the free operating system Linux.

OS X

Double-click on the installer. Find and run the MacPython.mpkg that is inside. Follow the defaults for installation.

Linux

Python is generally installed, though Idle is not always installed. Look for something like 'idle-python' (the name in the Ubuntu distribution).

1.1.4. Philosophy and Implementation of the Hands-On Python Tutorials

Although Python is a high-level language, it is not English or some other natural human language. The Python translator does not understand “add the numbers two and three”. Python is a formal language with its own specific rules and formats, which these tutorials will introduce gradually, at a pace intended for a beginner. These tutorials are also appropriate for beginners because they gradually introduce fundamental logical programming skills. Learning these skills will allow you to much more easily program in other languages besides Python. Some of the skills you will learn are

  • breaking down problems into manageable parts
  • building up creative solutions
  • making sure the solutions are clear for humans
  • making sure the solutions also work correctly on the computer.

Guiding Principals for the Hands-on Python Tutorials:

  • The best way to learn is by active participation. Information is principally introduced in small quantities, where your active participation, experiencing Python, is assumed. In many place you will only be able to see what Python does by doing it yourself (in a hands-on fashion). The tutorial will often not show. Among the most common and important words in the tutorial are “Try this:”
  • Other requests are for more creative responses. Sometimes there are Hints, which end up as hyperlinks in the web page version, and footnote references in the pdf version. Both formats should encourage you to think actively about your response first before looking up the hint.

    The tutorials also provide labeled exercises, for further practice, without immediate answers provided. The exercises are labeled at three levels
    *:
    Immediate reinforcement of basic ideas – preferably do on your first pass.
    **:
    Important and more substantial – be sure you can end up doing these.
    ***:
    Most creative
  • Information is introduced in an order that gives you what you need as soon as possible. The information is presented in context. Complexity and intricacy that is not immediately needed is delayed until later, when you are more experienced.
  • In many places there are complications that are important in the beginning, because there is a common error caused by a slight misuse of the current topic. If such a common error is likely to make no sense and slow you down, more information is given to allow you to head off or easily react to such an error.

Although this approach is an effective way to introduce material, it is not so good for reference. Referencing is addressed in several ways:

  • An extensive Table of Contents
  • Easy jumping to chosen text in a browser like Firefox
  • Cross references to sections that elaborate on an introductory section
  • Concise chapter summaries, grouping logically related items, even if that does not match the order of introduction.

Some people learn better visually and verbally from the very beginning. Some parts of the tutorial will also have links to corresponding flash video segments. Many people will find reading faster and more effective, but the video segments may be particularly useful where a computer interface can be not only explained but actually demonstrated. The links to such segments will be labeled. They will need a broadband link or a CD (not yet generated).

In the Firefox browser, the incremental find is excellent, and particularly useful with the single web page version of the tutorials. (It only fails to search footnotes.) It is particularly easy to jump through different sections in a form like 1.2.4.

1.2. The Python Interpreter and Idle, Part I

1.2.1. Your Python Folder and Python Examples

First you need to set up a location to store your work and the example programs from this tutorial. If you are on a Windows computer, follow just one of the three choices below to find an appropriate place to download the example archive examples.zip, and then follow the later instructions to unzip the archive.

Your Own Computer:
If you are at your own computer, you can put the folder for your Python programs most anywhere you like. For Chapter 4, it will be important that none of the directories leading down to your Python folder contain any blanks in them. In particular in Windows, “My Documents” is a bad location. In Windows you can create a directory in C: drive, like C:\myPython. You should have installed Python to continue.
Your Flash Drive:
If you do not have your own computer, or you want to have your materials easily travel back and forth between the lab and home, you will need a flash drive.

Plug your flash drive into the computer USB port.

On the computers in the Loyola lab DH 342, you can attach to the end of a cable that reaches close to the keyboard. In DH 339, there are USB ports on the monitor. Please Note: Flash drives are easy for me to forget and leave in the computer. I have lost a few this way. If you are as forgetful as I, you might consider a string from the flash drive to something you will not forget to take with you.

Open My Computer (on the desktop) to see where the flash drive is mounted, and open that drive.
Temporary:
If you (temporarily) do not have a flash drive and you are at a Loyola lab computer: Open My Computer from the desktop, and then select drive D:. Create a folder on drive D: with your name or initials to make it easy for you to save and remove things. Change to that folder. You should place the examples archive here. You will need to save your work somehow before you log off of the computer. You may want to email individual files to yourself, or rezip the examples folder and send just the one archive file to yourself each time until you remember a flash drive!

In Windows, after you have chosen a location for the archive, examples.zip, download it by right clicking on http://cs.luc.edu/anh/python/hands-on/3.0/examples.zip and selecting “Save As” or the equivalent on your browser and then navigate to save the archive to the chosen location on your computer. Note the the examples, like this version of the tutorial, are for Python 3.1. There were major changes to Python in version 3.0, making it incompatible with earlier versions.

If you are using Python version 2.5 or 2.6, you should continue with the older version of the tutorial. Go to http://cs.luc.edu/~anh/python/hands-on and find the links to the proper version of the tutorial and examples.

Once you have the archive, open a file browser window for that directory, right click on examples.zip, select Extract All. This will create the folder examples. End up with a file browser window showing the contents of the examples folder. This will be your Python folder in later discussion.

Caution 1: On Windows, files in a zip archive can be viewed while they are still in the zip archive. Modifying and adding files is not so transparent. Be sure that you unzip the archive and work from the regular directory that holds the resulting unzipped files.

Caution 2: Make sure that all the directories leading down to your Python examples directory do not include any spaces in them. This will be important in Chapter 4 for the local webserver. In particular, that means you should not place your folder under “My Documents”. A directory like C:\hands-on or C:\python would be fine.

You also have the option of downloading

The disadvantage of a local copy is that the tutorial may be updated online after you get your download. The change log file http://www.cs.luc.edu/~anh/python/hands-on/changelog.html will show when the latest update was made and a summary of any major changes.

1.2.2. Running A Sample Program

This section assumes Python, version at least 3.1, is already on your computer. Windows does not come with Python. (To load Python see Section 1.1.2) On a Mac or Linux computer enough of Python comes installed to be able to run the sample program.

If you are in a Windows lab with Python 3.1 installed, but not set up as the default version, see the footnote.

Before getting to the individual details of Python, you will run a simple text-based sample program. Find madlib.py in your Python folder (Section 1.2.1).

Options for running the program:

  • In Windows, you can display your folder contents, and double click on madlib.py to start the program.
  • In Linux or on a Mac you can open a terminal window, change into your python directory, and enter the command

python madlib.py

The latter approach only works in a Windows command window if your operating system execution path is set up to find Python.

In whatever manner you start the program, run it, responding to the prompts on the screen. Be sure to press the enter key at the end of each response requested from you.

Try the program a second time and make different responses.

1.2.3. A Sample Program, Explained

If you want to get right to the detailed explanations of writing your own Python, you can skip to the next section1.2.4. If you would like an overview of a working program, even if all the explanations do not make total sense yet, read on.

Here is the text of the madlib.py program, followed by line-by-line brief explanations. Do not worry if you not totally understand the explanations! Try to get the gist now and the details later. The numbers on the right are not part of the program file. They are added for reference in the comments below.

"""                                                      1 
String Substitution for a Mad Lib                        2 
Adapted from code by Kirby Urner                         3 
"""                                                      4 
                                                         5 
storyFormat = """                                        6 
Once upon a time, deep in an ancient jungle,             7 
there lived a {animal}.  This {animal}                   8 
liked to eat {food}, but the jungle had                  9 
very little {food} to offer.  One day, an               10 
explorer found the {animal} and discovered              11 
it liked {food}.  The explorer took the                 12 
{animal} back to {city}, where it could                 13 
eat as much {food} as it wanted.  However,              14 
the {animal} became homesick, so the                    15 
explorer brought it back to the jungle,                 16 
leaving a large supply of {food}.                       17 
                                                        18 
The End                                                 19 
"""                                                     20 
                                                        21  
def tellStory():                                        22 
    userPicks = dict()                                  23 
    addPick('animal', userPicks)                        24 
    addPick('food', userPicks)                          25 
    addPick('city', userPicks)                          26 
    story = storyFormat.format(**userPicks)             27 
    print(story)                                        28 
                                                        29 
def addPick(cue, dictionary):                           30 
    '''Prompt for a user response using the cue string, 31 
    and place the cue-response pair in the dictionary.  32 
    '''                                                 33 
    prompt = 'Enter an example for ' + cue + ': '       34 
    response = input(prompt)                            35 
    dictionary[cue] = response                          36 
                                                        37 
tellStory()                                             38 
input("Press Enter to end the program.")                39 

Line By Line Explanation

"""                                                      1 
String Substitution for a Mad Lib                        2 
Adapted from code by Kirby Urner                         3 
"""                                                      4 

1-4

There is multi-line text enclosed in triple quotes. Quoted text is called a string. A string at the very beginning of a file like this is documentation for the file.

5,21,29,37

Blank lines are included for human readability to separate logical parts. The computer ignores the blank lines.

storyFormat = """                                        6 
Once upon a time, deep in an ancient jungle,             7 
there lived a {animal}.  This {animal}                   8 
liked to eat {food}, but the jungle had                  9 
very little {food} to offer.  One day, an               10 
explorer

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *