The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | Apr 2017 |
| Last Sign in: | 103 Weeks Ago, 3 Days Ago |
| Questions Answered: | 4870 |
| Tutorials Posted: | 4863 |
MBA IT, Mater in Science and Technology
Devry
Jul-1996 - Jul-2000
Professor
Devry University
Mar-2010 - Oct-2016
Online Module_Python.qxd 7/30/09 8:10 PM Page 1 Programming in Python
Online module to accompany Invitation to Computer Science, 5th Edition ISBN-10:
0324788592; ISBN-13: 9780324788594 (Course Technology, a part of Cengage
Learning, 2010). 1. 2.
3. 4.
5. 6. 7. 8. Introduction to Python
1.1 A Simple Python Program
1.2 Creating and Running a Python Program
Virtual Data Storage
Statement Types
3.1 Input/Output Statements
3.2 The Assignment Statement
3.3 Control Statements
Another Example
Managing Complexity
5.1 Divide and Conquer
5.2 Using and Writing Functions
Object-Oriented Programming
6.1 What Is It?
6.2 Python and OOP
6.3 One More Example
6.4 What Have We Gained?
Graphical Programming
7.1 Graphics Hardware
7.2 Graphics Software
Conclusion EXERCISES
ANSWERS TO PRACTICE PROBLEMS 1
©2010 Course Technology, a part of Cengage Learning. Online Module_Python.qxd 1 7/30/09 8:10 PM Page 2 Introduction to Python
Hundreds of high-level programming languages have been developed; a
fraction of these have become viable, commercially successful languages.
There are a half-dozen or so languages that can illustrate some of the concepts
of a high-level programming language, but this module uses Python for this
purpose.
Our intent here is not to make you an expert Python programmer—any
more than our purpose in Chapter 4 was to make you an expert circuit
designer. Indeed, there is much about the language that we will not even
discuss. You will, however, get a sense of what programming in a high-level
language is like, and perhaps see why some people think it is one of the most
fascinating of human endeavors. 1.1 A Simple Python Program
Figure 1 shows a simple but complete Python program. Even if you know
nothing about the Python language, it is not hard to get the general drift of
what the program is doing.
FIGURE 1
A Simple Python Program #Computes and outputs travel time
#for a given speed and distance
#Written by J. Q. Programmer, 6/15/10
speed = input(“Enter your speed in mph: ”)
speed = int(speed)
distance = input(“Enter your distance in miles: ”)
distance = float(distance)
time = distance/speed
print(“At”, speed, “mph, it will take”)
print(time, “hours to travel”, distance, “miles.”)
input(“\n\nPress the Enter key to exit”) 2 Programming in Python
©2010 Course Technology, a part of Cengage Learning. Online Module_Python.qxd 7/30/09 8:10 PM Page 3 Someone running this program (the user) could have the following
dialogue with the program, where boldface indicates what the user types:
Enter your speed in mph: 58
Enter your distance in miles: 657.5
At 58 mph, it will take
11.3362068966 hours to travel 657.5 miles.
To aid our discussion of how the program works, Figure 2 shows the same program with a number in front of each line. The numbers are there for reference
purposes only; they are not part of the program. Lines 1–3 in the program of
Figure 2 are Python comments. Anything appearing on a line after the pound
symbol (#) is ignored by the compiler, just as anything following the double
dash (––) is treated as a comment in the assembly language programs of
Chapter 6. Although the computer ignores comments, they are important to
include in a program because they give information to the human readers of
the code. Every high-level language has some facility for including comments,
because understanding code that someone else has written (or understanding
your own code after some period of time has passed) is very difficult without
the notes and explanations that comments provide. Comments are one way to
document a computer program to make it more understandable. The comments
in lines 1–3 of Figure 2 describe what the program does plus tell who wrote
the program and when. These three comment lines together make up the
program’s prologue comment (the introductory comment that comes first).
A prologue comment is always a good idea; it’s almost like the headline in a
newspaper, giving the big picture up front.
Blank lines in Python programs are ignored and are used, like comments,
to make the program more readable by human beings. In our example
program, we’ve used blank lines (lines 4, 9, 11, 14) to separate sections of the
program, visually indicating groups of statements that are related. Except for
blank lines, Python by default considers each line of the program to be an
individual program instruction, also called a program statement, so you end a
statement by just pressing the Enter key and going to the next line to write
the next statement.
FIGURE 2
The Program of Figure 1 (line
numbers added for reference) 1. #Computes and outputs travel time
2. #for a given speed and distance
3. #Written by J. Q. Programmer, 6/15/10
4.
5. speed = input(“Enter your speed in mph: ”)
6. speed = int(speed)
7. distance = input(“Enter your distance in miles: ”)
8. distance = float(distance)
9.
10. time = distance/speed
11.
12. print(“At”, speed, “mph, it will take”)
13. print(time, “hours to travel”, distance, “miles.”)
14.
15. input(“\n\nPress the Enter key to exit”) 1 Introduction to Python ©2010 Course Technology, a part of Cengage Learning. 3 Online Module_Python.qxd 7/30/09 8:10 PM Page 4 The three quantities involved in this program are the speed of travel and
the distance traveled (these are input by the user) and the time to complete
that travel (this is computed and output by the program). The program code
itself uses descriptive names—speed, distance, and time—for these quantities,
to help document their purpose in the program. Lines 5–8 prompt the user to
enter values for speed and distance, and store those values in speed and
distance. Later, we’ll see more details on how this works. Line 10 computes the
time required to travel this distance at this speed. Finally, lines 12 and 13 print
the two lines of output to the user’s screen. The values of speed, time, and distance are inserted in appropriate places among the strings of text shown in
double quotes. The final program statement, line 15, has the effect of holding
the output on the user’s screen until the user presses the Enter key; otherwise,
the output might just flash by and be gone when the program ends.
Python, along with every other programming language, has specific rules
of syntax—the correct form for each component of the language. Any violation of the syntax rules generates an error message from the compiler because
the compiler does not recognize or know how to translate the offending code.
Python’s rules of syntax are much simpler than those of many other programming languages, which is one reason that Python programs are often shorter
and, many would claim, easier to write than programs in C++, Java, Ada, or C#,
for example. Nonetheless, a typing error such as
printt(“Hello World”)
will produce an error message, as will
Print(“Hello World”)
because Python is a case-sensitive language, which means that uppercase letters are distinguished from lowercase letters, and the instruction is print, not
Print. 1.2 Creating and Running a Python Program
Creating and running a Python program is basically a two-step process. The
first step is to type the program into a text editor. When you are finished, you How About
That Snake?
The Python programming language was created in the early
1990s by the Dutch computer scientist and applied mathematician Guido van Rossum as a successor to a language
called ABC. It was not actually named for a snake. It was
named for the BBC comedy show Monty Python’s Flying
Circus. Make of that what you will!
Since its original release, Python has gone through a
number of revisions. Guido van Rossum remains the project 4 leader and final arbiter of new enhancements to the
language, although—because it is an open-source
language—anyone can tinker with it and propose new
features or additions, and many have contributed to its
development.
Python is prized for its low-stress (minimalist and
intuitive) syntax, which leads to quick development time.
While the basics of the language are simple, an extensive
library of supporting code makes it a flexible and powerful
language. Programming in Python
©2010 Course Technology, a part of Cengage Learning. Online Module_Python.qxd 7/30/09 8:10 PM Page 5 save the file, giving it a name with the extension .py. So the file for Figure 1
could be named
TravelPlanner.py
The second step is to execute the program. Details of how to run the program
depend on your system; you may be able to double-click on the TravelPlanner.py file, or you may have to type the command “TravelPlanner.py” at the
operating system prompt. Whenever you run a Python program, the Python
compiler (it’s actually called an interpreter)1 translates the Python code first
into low-level code called bytecode, which is not yet object code, then
finishes the translation into machine-specific object code and executes it.
(Referring to Figure 9.1 in the Invitation to Computer Science textbook, there
are no explicit linker or loader steps. The program goes quite seamlessly from
high-level code to execution.) A Python program will therefore run on any
computer that has Python on it.
Another approach is to do all of your work in an Integrated Development Environment, or IDE. The IDE lets the programmer perform a number of
tasks within the shell of a single application program. A modern programming
IDE provides a text editor, a file manager, a way to run the program, and tools
for debugging, all within this one piece of software. The IDE usually has a
graphical user interface (GUI) with menu choices for the different tasks. This
can significantly speed up program development. Python comes with its own
Integrated Development Environment called IDLE, so you can do all your
Python program development with this one tool.
This Python exercise is just a beginning. In the rest of this module, we’ll
examine the features of the language that will enable you to write your own
Python programs to carry out more sophisticated tasks. PYTHON INTERPRETER
A free Python interpreter is available to download at www.python.org/download.
Python comes with its own IDE called IDLE. You can do all your Python program
development within this one tool. There are versions for Windows, Linux, and Mac
OS X. The code in this module is based on Python version 3.0, which was released
in December 2008, and is quite different from previous versions.
The graphics software used in Section 7 of this module is courtesy of Dr. John
Zelle of Wartburg College, Iowa, as modified for Python 3.0 by Dr. Andrew Harrington of Loyola University, Chicago. This is open-source software released under the
terms of the GPL (General Public License; see www.gnu.org/licenses/gpl.html) and
may be downloaded for free from http://mcsp.wartburg.edu/zelle/python. Put the
file (graphicsPy3.py) in the Python Lib folder after you have installed Python, but
be sure to rename it as graphics.py. 1The difference between a compiled language and an interpreted language is that a compiler
translates source code into object code once. The compiled code is then used over and over,
unless the source code is changed, requiring a recompile. An interpreter translates source code
into object code each time the program is executed, and no object code is saved for later use. 1 Introduction to Python ©2010 Course Technology, a part of Cengage Learning. 5 Online Module_Python.qxd 2 7/30/09 8:10 PM Page 6 Virtual Data Storage
One of the improvements we seek in a high-level language is freedom from
having to manage data movement within memory. Assembly language does
not require us to give the actual memory address of the storage location to be
used for each item, as in machine language. However, we still have to move
values, one by one, back and forth between memory and the arithmetic logic
unit (ALU) as simple modifications are made, such as setting the value of A to
the sum of the values of B and C. We want the computer to let us use data
values by name in any appropriate computation without thinking about where
they are stored or what is currently in some register in the ALU. In fact, we do
not even want to know that there is such a thing as an ALU, where data are
moved to be operated on. Instead, we want the virtual machine to manage the
details when we request that a computation be performed. A high-level
language allows this, and it also allows the names for data items to be more
meaningful than in assembly language.
Names in a programming language are called identifiers. Each language has
its own specific rules for what a legal identifier can look like. In Python an identifier can be any combination of letters, digits, and the underscore symbol (_),
as long as it does not begin with a digit. An additional restriction is that an
identifier cannot be one of the few words, such as “while”, that have a special
meaning in Python and that you would not be likely to use anyway. The three
integers B, C, and A in our assembly language program can therefore have more
descriptive names, such as subTotal, tax, and finalTotal. The use of descriptive
identifiers is one of the greatest aids to human understanding of a program.
Identifiers can be almost arbitrarily long, so be sure to use a meaningful identifier such as finalTotal instead of something like A; the improved readability is
well worth the extra typing time. Remember that Python is case sensitive; thus,
FinalTotal, Finaltotal, and finalTotal are three different identifiers. CAPITALIZATION OF IDENTIFIERS
There are two standard capitalization patterns for identifiers, particularly “multiple
word” identifiers:
camel case: First word begins with a lowercase letter, additional words
begin with uppercase letters (finalTotal)
Pascal case: All words begin with an uppercase letter (FinalTotal)
The code in this chapter uses the following convention for creating identifiers
(examples included):
Simple variables – camel case: speed, time, finalTotal
Named constants - all uppercase: PI, FREEZING_POINT
Function names – camel case: myFunction, getInput
Class names – Pascal case: MyClass
Object names – camel case: myObject
The underscore character is not used except for named constants. Occasionally,
however, we’ll use single capital letters for identifiers in quick code fragments. 6 Programming in Python
©2010 Course Technology, a part of Cengage Learning. Online Module_Python.qxd 7/30/09 8:10 PM Page 7 Data that a program uses can come in two varieties. Most quantities used in a
program have values that change as the program executes, or values that are
not known ahead of time but must be obtained from the computer user
(or from a data file previously prepared by the user) as the program runs.
These quantities are called variables. Some programs may use quantities that
are fixed throughout the duration of the program, and their values are known
ahead of time. These quantities are called constants. The names for both
variables and constants must follow the Python identifier syntax rules given
previously.
Identifiers for variables and constants serve the same purpose in program
statements as pronouns do in ordinary English statements. The English
statement “He will be home today” has specific meaning only when we plug in
the value for which “He” stands. Similarly, a program statement such as
time = distance/speed
becomes an actual computation only when numeric values have been stored in
the memory locations referenced by the distance and speed identifiers.
We now know how to name variables, but how do we actually create them
in a Python program? The syntax is very simple; variables are created and
given values all in one statement of the form
identifier = value
For example,
myNumber = 15
associates the identifier myNumber with some (unknown to us and we don’t
care) memory location and stores the integer value 15 in that location. This
statement is equivalent to the assembly language statement
myNumber: .DATA 15
Python recognizes different types of data that can be stored in variables,
namely string data or numeric data. A string is just a sequence of characters;
the statement
print(“Hello World”)
prints the exact sequence of characters within the quote marks. Such a string
is sometimes called a literal string because it is printed out exactly as is. The
first statement below stores that same string in a variable, and the second
statement then prints out the contents of that variable:
message = “Hello World”
print(message)
The effect is the same in either case—the user sees
Hello World
on the screen.
2 Virtual Data Storage ©2010 Course Technology, a part of Cengage Learning. 7 Online Module_Python.qxd 7/30/09 8:10 PM Page 8 FIGURE 3
Some of the Python Data Types int
float
string an integer quantity
a real number (a decimal quantity)
a sequence of characters There are also several different types of numeric data, the most common
being type int and type float. Whole numbers with no decimal points, such as
–28 and 5231, are of type int; numbers with decimal points, such as 25.8 or
–52.976, are of type float. Figure 3 lists these common Python data types.
We know that all data are represented internally in binary form. In Chapter 4 we noted that any one sequence of binary digits can be interpreted as a
whole number, a negative number, a real number (one containing a decimal
point, such as –17.5 or 28.342), etc. In Python, a variable doesn’t have a fixed
data type associated with it. Instead, it takes on the data type of whatever
value it currently contains. After execution of
myNumber = 15
the binary string in memory location myNumber will be interpreted as an integer. If the statement
myNumber = 65.81
is executed later in the same program, Python will then interpret the binary
string in myNumber as a decimal value. Still later, myNumber could take on
the string data type with the statement
myNumber = “This is my number”
although at this point the identifier would be somewhat misleading! And this
points out a difficulty with the ability of an identifier to take its data type
from the value assigned to it at the moment. If the reader of the program has
to remember, “let’s see, in this section of code the variable xyz means
something-or-other, but down in that section of code it means something-orother-else,” then there is room for confusion. Good programming practice says
that an identifier should represent only one thing in a given program.
Let’s consider program constants. An example of a constant is the integer
value 2. The integer 2 is a constant that we don’t have to name by an identifier,
nor do we have to build the value 2 in memory manually by the equivalent of a
.DATA pseudo-op. We can just use the symbol “2” in any program statement.
When “2” is first encountered in a program statement, the binary representation
of the integer 2 is automatically generated and stored in a memory location. In
a program that does computations about circles, an approximation to , say
3.1416, could be used just as easily by simply sticking this number wherever in
the program we need it. But if we are really using this number as an approximation to , it is more informative to use the identifier PI. The statement
PI = 3.1416
stores the desired decimal value in a memory location with the identifier PI.
The convention among Python programmers is that an identifier of all caps,
8 Programming in Python
©2010 Course Technology, a part of Cengage Learning. Online Module_Python.qxd 7/30/09 8:10 PM Page 9 like PI, represents a constant value in the program. Therefore the value of PI
should not be changed by a later program statement. However, Python won’t
prevent you from later making a change in the value of PI, so it’s up to you as
the programmer to treat this value of PI as unchangeable. In Python, then, a
named constant is really just a variable.
In addition to variables of a primitive data type that hold only one unit of
information, we can create a whole collection, called a list, of logically related
variables at one time. This allows storage to be set aside as needed to contain
each of the values in this collection. For example, suppose we want to create
a roster of students in the class. We can do this using a Python list that contains string data.2 The following two statements create a Python list and print
its contents.
roster = ["Martin", "Susan", "Chaika", "Ted"]
print(roster)
The output is
['Martin', 'Susan', 'Chaika', 'Ted']
While roster refers to the list as a whole, individual list elements can be
accessed by giving their position or index in the list. List indices begin at 0, so
print(roster[1])
produces output of
Susan
Figure 4 illustrates this list.
Here is an example of the power of a high-level language. In assembly
language, we can name only individual memory locations—that is, individual
items of data—but in Python we can also assign a name to an entire collection
of related data items. A list thus allows us to talk about an entire table of
values, or the individual elements making up that table. If we are writing
Python programs to implement the data cleanup algorithms of Chapter 3, we
can use a list of integers to store the 10 data items.
A Python list can perform many different actions. For example, the list
can be put into sorted order:
roster.sort()
print(roster) FIGURE 4 Martin A 4-Element List roster Susan Chaika Ted roster[1]
2A Python list serves the same purpose as what is usually called an “array” in other languages. 2 Virtual Data Storage ©2010 Course Technology, a part of Cengage Learning. 9 Online Module_Python.qxd 7/30/09 8:10 PM Page 10 produces output of
['Chaika', 'Martin', 'Susan', 'Ted'] PRACTICE PROBLEMS
1. Which of the following are legitimate Python identifiers?
martinBradley C3P_OH Amy3 3Right Print 2. What is the output from the following fragment of Python code?
myVariable = 65
myVariable = 65.0
myVariable = “Sixty Five”
print(myVariable)
3. Using the roster list of Figure 4, how do you reference the last item
in the list? 3 Statement Types
Now that we understand how to create variables to hold data, we will examine
additional kinds of programming instructions (statements) that Python provides.
These statements enable us to manipulate the data items and do something
useful with them. The instructions in Python, or indeed in any high-level
language, are designed as components for algorithmic problem solving, rather
than as one-to-one translations of the underlying machine language instruction
set of the computer. Thus, they allow the programmer to work at a higher level of
abstraction. In this section we examine three types of high-level programming
language statements. They are consistent with the pseudocode operations
described in Chapter 2 (see Figure 2.9).
Input/output statements make up one type of statement. An input
statement collects a specific value from the user for a variable within the
program. In our TravelPlanner program, we need input statements to get the
values of the speed and distance that are to be used in the computation. An
output statement writes a message or the value of a program variable to the
user’s screen. Once the TravelPlanner program computes the time required to
travel the given distance at the given speed, the output statement displays
that value on the screen, along with other information about what that value
means.
Another type of statement is the assignment statement, which assigns a
value to a program variable. This is similar to what an input statement does,
except that the value is not collected directly from the user, but is computed
by the program. In pseudocode we called this a “computation operation.”
Control statements, the third type of statement, affect the order in which
instructions are executed. A program executes one instruction or program 10 Programming in Python
©2010 Course Technology, a part of Cengage Learning. Online Module_Python.qxd 7/30/09 8:10 PM Page 11 statement at a time. Without directions to the contrary, instructions are
executed sequentially, from first to last in the program. (In Chapter 2 we called
this a straight-line algorithm.) Imagine beside each program statement a light
bulb that lights up while that statement is being executed; you would see a
ripple of lights from the top to the bottom of the program. Sometimes,
however, we want to interrupt this sequential progression and jump around in
the program (which is accomplished by the instructions JUMP, JUMPGT, and so
on, in assembly language). The progression of lights, which may no longer be
sequential, illustrates the flow of control in the program—that is, the
path through the program that is traced by following the currently executing
statement. Control statements direct this flow of control. 3.1 Input/Output Statements
Remember that the job of an input statement is to collect from the user
specific values for variables in the program. In pseudocode, to get the value
for speed in the TravelPlanner program, we would say somethi...