Notes From Python Programming (By John Zelle) : 1.6 The Magic of Python
Notes From Python Programming (By John Zelle) : 1.6 The Magic of Python
The CPU performs simple arithmetic and logical operations. Information that
the CPU acts on (data and programs) is stored in main memory (RAM). More
permanent information is stored on secondary memory devices.
A mathematical model is called chaotic if very small changes in the input lead
to large changes in the results, making them seem random or unpredictable.
The models of many real-world phenomena exhibit chaotic behavior, which
places some limits on the power of computing.
Chapter 2
Objectives
To know the steps in an orderly software development process.
To understand programs following the input, process, output, (IPO) pattern
an be able to modify them in simple ways.
To understand the rules for forming valid Python identifiers and expressions.
To be able to understand and write Python statements to output information
to the screen, assign values to variable, get information entered from the
keyboard, and perform a counted loop.
The process of creating a new program is often broken down into stages according
to the information that is produced in each phase. You should do:
Analyze the problem Figure out exactly what the problem to be solved is. Try to
understand as much as possible about it. Until you really know what the problem is,
you cannot begin to solve it.
Determine Specifications Describe exactly what your program will do. At this point,
you should not worry about how will work, but rather about deciding exactly what it
will accomplish. For simple programs this involves carefully describing what the
inputs and outputs of the program will be and how they relate to each other.
Create a design Formulate the overall structure of the program. This is where the
how of the program gets worked out. The main task is to design the algorithms as
Python programs.
Test/Debug the program Try out your program and see if it works as expected. If
there are any errors (often called bugs), then you should go back and fix them. The
process of fixing errors is called debugging a program.
Maintain the program Continue developing the program in response to the needs
of your users.
2.2 Example Program: Temperature Converter
IPO: Input, process, output.
Pseudocode: Pseudocode is just precise English that describes what a program
does. It is meant to communicate algorithms without all the extra mental overhead
of getting the details in any particular programming language.
This is called concatenation. As you can see, the effect is to create a new string that
is the result of “gluing” the strings together.
The last statement illustrates how string literal expressions are often used in print
statements as a convenient way of labeling output.
Notice that successive print statements normally display on separate lines of the
screen. A bare print (no parameters) produces a blank line of output.
One common use of the end parameterin print statements is to allow multiple
prints to build up a single line of output. For example:
Notices how the output from the first print statements in Python is the assignment
statement.
<variable> = <expr>
A variable can be assigned many times. It always retains the value of the most
recent assignment. Here is an interactive Python session that demonstrates the
point:
The last assignment statement shows how the current value of a variable can be
used to update its value. The chaos.py program from chapter 1 did something
similar, though a bit more complex. Remember, the values of variables can
change; that’s why we call them variables.
Figure 2.1 shows how we might picture the effect of x = x + 1 using this
model. This is exactly the way assignment works in some computer languages.
It’s also very a very simple way to review the effect of assignment, and you’ll find
pictures similar to this throughout the book.
Python assignment statements are actually slightly different from the “variable as
a box” model.
In Python, values may end up anywhere in memory, and variables are used to
refer to them. Assigning a variable is like putting one of those little yellow sticky
notes on the value and saying, “this is x.” Figure 2.2 gives a more accurate picture
of the effect of assignment in Python. An arrow is used to show which variable
refers to. Notice that the old value doesn’t get erased by the new one; the variable
simply switches to refer to the new value. The effect is like moving the sticky note
from one object to another. This is the way assignment actually works in Python,
so you’ll see some of the sticky-note style pictures sprinkled throughout the book
as well.
The purpose of an input statement is to get some information from the user of a
program and store it into a variable.
For textual input, the statement will look like this:
<variable> = input(<prompt>)
Here <prompt> is a string expression that is used to prompt the user for input;
the prompt is almost always a string literal (i.e., some text inside of quotation
marks).
When Python encounters a call to input, it prints the prompt on the screen.
Python then pauses and waits for the user to type some text and press the
<Enter> key. Whatever the user types is then stored as a string. Consider this
simple interaction:
When the user input is a number, we need a slightly more complicated form of
input statement:
<variable> = eval(input(<prompt>))
As you might guess, eval is short for “evaluate.” In this form, the text typed by the
user is evaluated as an expression to produce the value that is stored into the
variable. So, for example, the string “32” becomes the number 32.
The important thing to remember is that you need to eval the input when you
want a number instead of some raw text (a string).
Here sum would get the sum of x and y and diff would get the difference.
One way to make the swap work is to introduce an additional variable that
temporally remembers the original value of x.
Temp = x
x=y
y = temp
Let’s walk through this sequence to see how it works.
As you can see from the final values of x and y, the swap was successful in this
case.
In Python, the simultaneous assignment statement offers an elegant alternative.
Here is a simple Python equivalent:
x, y = y, x
Because the assignment is simultaneous, it avoids wiping out one of the original
values.
Simultaneous assignment can also be used to get multiple numbers from the
user in a single input. Consider this program for averaging exam scores:
In some ways this may be better, as the separate prompts are more informative
for the user. Sometimes getting multiple values in a single input provides a more
intuitive user interface, so it’s a nice technique to have in your toolkit.
2.6 Definite Loops
The body of the loop can be any sequence of Python statements. The extent of
the body is indicated by its indentation under the loop heading (the for <var> in
<sequence>: part).
The variable after the keyword for is called loop index. It takes each successive
value in the sequence, and the statements in the body are executed once for
each value. Often the sequence portion consists of a list of values. List are a very
important concept in Python. For now, it’s enough to know that you can create a
simple list by placing a sequence of expressions in square brackets. Some
interactive examples help to illustrate the point:
range is a built-in Python function for generating a sequence of numbers “on the
fly”. You can think of a range as a sort of implicit description of a sequence of
numbers. To get a handle on what range actually does, we can ask Python to
turn a range into a plain-old list using another built-in function, list:
Do you see what is happening here? The expression range (10) produces the
sequence of numbers 0 through 9. The loop using the range (10) is equivalent to
one using a list of those numbers:
In general, range (<expr>) will produce a sequence of numbers that starts with 0
and goes up to, but does not include, the value of <expr>.
When you want to do something in your program a certain number of times, use
a for loop with a suitable range.
The value of the expression determines how many times the loop executes.
Programmers often use i or j as the loop index variable for counted loops.
Statement like the for loop are called control structures because they control the
execution of other parts of the program.
Some programmers find it helpful to think of control structures of pictures called
flowcharts. A flowchart is a diagram that uses boxes to represent different parts
of a program and arrows between the boxes to show the sequence of events
when the program is running. Figure 2.3 depicts the semantics of the for loop as
a flowchart.
2.8 Chapter summary
This chapter has covered a lot of ground laying out both the process that is used
to develop programs and the details of Python that are necessary to implement
simple programs. Here is a quick summary of some of the key points:
Many simple programs follow the input, process, output (IPO) pattern.
Programs are composed of statements that are built form identifiers and
expressions.
Identifiers are names; they begin with an underscore or letter which can be
followed by a combination of letter, digit, or underscore characters. Identifiers
in Python are case sensitive.
Expressions are the fragments of a program that produce data. An expression
can be composed of the following components:
Literals: A literal is a representation of a specific value. For example, 3 is a
literal representing the number three.
Variables: A variable is an identifier that stores a value.
Operators: Operators are used to combine expressions into more complex
expressions. For example, in x + 3 * y the operators + and * are used.
The Python operators for numbers include the usual arithmetic operations of
addition (+), subtraction (-), multiplication (*), division (/), and exponentiation
(**).
The Python output statement print displays the values of a series of
expressions to the screen.
In Python, assignment of a value to a variable is done using the equal sign
(=). Using assignment, programs can get input from the keyboard. Python
also allows simultaneous assignment, which is useful for getting multiple input
values with a single prompt.
Definite loops are loops that execute a known number of times. The Python
for statement is a definite loop that iterates through a sequence of values. A
Python list is often used in a for loop to provide a sequence of values for the
loop.
One important use of a for statement is in implementing a counted loop, which
is a loop designed specifically for the purpose of repeating some portion of
the program a specific number of times. A counted loop in Python is created
by using the built-in range function to produce a suitably sized list of numbers.
2.9 Exercises
Review Questions
True/False
1. F
2. T
3. F
4. T
5. F
6. T
7. T
8. F
9. T
10. F
Multiple choice
1. C
2. A
3. D
4. C
5. B
6. B
7. B
8. D
9. A
10. D
Discussion
1. List and describe in tour own words the six steps in the software development
process.
R:
1. Problem analysis: study the problem to be solved.
2. Program specification: describe exactly what the program is going to do.
3. Design: design the program using pseudocode.
4. Implementation: Translate the program into a programming language.
5. Testing / Debugging: solve the program errors.
6. Maintenance: Keeping the program up to date according with the necessities.
5. Why is it a good idea to first write out algorithm in pseudocode rather than
jumping immediately to Python code?
R: You can see in a clear way how you are going to design your program.
Chapter 3
Computing with numbers
Objectives
To understand the concept of data types.
To be familiar with the basic numeric data types in Python.
To understand the fundamental principles of how numbers are
represented on a computer.
To be able to use the Python math library.
To understand the accumulator program pattern.
To be able to read and write programs that process numerical data.
Table 3.2 shows some of the other functions that are available in the math library.
3.5 Type Conversions and Rounding
int()
float()
round()