Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Notes From Python Programming (By John Zelle) : 1.6 The Magic of Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

NOTES FROM PYTHON PROGRAMMING (BY JOHN ZELLE)

1.6 The magic of Python


- In programming languages, a complete command is called statement.
- A function is invoked (or called) by typing its name followed by parentheses.
Programs are usually created by typing definitions into a separate file called a
module or script. This file is saved on a disk so that it can be used over and over
again.
A programming environment is specifically designed to help programmers write
programs and includes features such as automatic indenting, color highlight, and
interactive development. The standard Python distribution includes a programming
environment called IDLE that you may use for working on the programs in the book.
- The .py extension indicates that this is a Python module.
A module needs to be imported into a session only once. After the module has been
loaded, we can run the program again by asking Python to execute the main
command. We do this by using a special dot notation. Typing chaos.main() tells
Pyhton to invoke the main function in the chaos module.

1.7 Inside a Python Program


# Comments - These lines are called comments. They are intended for human
readers of the program and are ignored by Python.
print(“comment”) – This line causes Python to print a message introducing the
program when it runs.
Variable – A variable is used to give a name to a value so that we can refer to it at
other points in the program.
1.9 Chapter Summary
 A computer is a universal information-processing machine. It can carry out
any process that can be described in sufficient detail. A description of the
sequence of steps for solving a particular problem is called algorithm.
Algorithms can be turned into software (programs) that determines what the
hardware (physical machine) can does accomplish. The process of creating
software is called programming.

 Computer science is the study of what can be computed.

 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.

 Programs are written using a formal notation known as a programming


language.

 A Python program is a sequence of commands (called statements) for the


Python interpreter to execute.

 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

Writing Simple Programs

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.

2.1 The Software Development Process

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.

2.3 Elements of programs

Note: keywords are also called reserved words.


2.3.2 Expressions
Programs manipulate data.
The fragments of program code that produce or calculate new data values are called
expressions. The simplest kind of expression is a literal. A literal is used to indicate
a specific value.
Our programs also manipulated textual data in some simple ways. Computer
scientists refer to a textual data as strings. You can think of a string as just a
sequence of printable characters. A string literal is indicated in Python by enclosing
the characters in quotation marks (““).
The process of turning an expression into an underlying data type is called
evaluation. When you type an expression into a Python shell, the shell evaluates the
expression and prints out a textual representation of the result.
Python also provides operators for strings. For example, you can “add” strings.
>>> “Bat” + “man”
‘Batman’

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.

2.4 Output statements


By default, a single blank space character is placed between the displayed value.
As an example, this sequence of print statements:

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.

2.5.1 Simple Assignment

The basic assignment statement has this form:

<variable> = <expr>

Here “variable” is an identifier and “expr” is an expression. The semantics of the


assignment is that the expression on the right side is evaluated to produce a
value, which is then associated with the variable named on the left side.
Here are some of the assignments we’ve already seen:

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.

2.5.2 Assigning input

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).

2.5.3 Simultaneous Assignment

There is an alternative form of the assignment statement that allows us to


calculate several values all at the same time. It looks like this:

<var>, <var>, …, <var> = <expr>, <expr>, …, <expr>

This is called simultaneous assignment. Semantically this tells Python to evaluate


all the expressions on the right-hand side and then assign these values to the
corresponding variables named on the left-hand side. Here’s an example:

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

You already know that programmers use loops to execute a sequence of


statements multiple times in succession. The simplest kind of loop is called a
definite loop. This is a loop that will execute a definite number of times.

A Python for loop has this general form:

For <var> in <sequence>:


<body>

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:

 Writing programs requires a systematic approach to problem solving and


involves the following steps:
1. Problem Analysis: Studying the problem to be solved.
2. Program Specification: Deciding exactly what the program will do.
3. Design: Writing an algorithm in pseudocode.
4. Implementation: Translating the design into a programming language.
5. Testing/Debugging: Finding and fixing errors in the program.
6. Maintenance: Keeping the program up to date with evolving needs.

 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.

3.1 Numerical Data Types


The information that is stored and manipulated by computer programs is
generically referred to as data.
The data type of an object determines what values it can have and what operators
can be performed on it. Whole numbers are represented using the integer data
type (int for short). Values of type int can be positive or negative whole numbers.
Numbers that can have fractional parts are represented as floating point (or float)
values.
Python provides a special function called type that tells us the data type (or class)
of any value. Here is an interaction with the Python interpreter showing the
difference between int and float literals:

If you don’t need fractional value, use an int.


3.2 Using the math library
Besides the operations listed in Table 3.1 Python provides many other useful
mathematical functions in a special math library.

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()

3.6 Chapter summary


 Additional mathematical functions are defined in the math library. To use
these functions, a program must first import the math library.
 Numerical results are often calculated by computing the sum or product of a
sequence of values. The loop accumulator programming pattern is useful for
this sort of calculation.
 Python automatically converts numbers from one data type to another in
certain situations.
 Programs may also explicitly convert one data type into another using the
functions float(), int(), and round().

You might also like