Intro To Python, Sample 3 Pages
Intro To Python, Sample 3 Pages
Program Development 3
Obje ctive s
In this chapter, you’ll:
■ Decide whether to execute
actions with the statements
if, if…else and
if…elif…else.
■ Execute statements repeatedly
with while and for.
■ Shorten assignment
expressions with augmented
assignments.
■ Use the for statement and
the built-in range function to
repeat actions for a sequence
of values.
■ Perform sentinel-controlled
repetition with while.
■ Learn problem-solving skills:
understanding problem
requirements, dividing
problems into smaller pieces,
developing algorithms to solve
problems and implementing
those algorithms in code.
■ Develop algorithms through
the process of top-down,
stepwise refinement.
■ Create compound conditions
with the Boolean operators
and, or and not.
■ Stop looping with break.
3.1 Introduction
Before writing a program to solve a particular problem, you must understand the problem
and have a carefully planned approach to solving it. You must also understand Python’s
building blocks and use proven program-construction principles.
3.2 Algorithms
You can solve any computing problem by executing a series of actions in a specific order.
An algorithm is a procedure for solving a problem in terms of:
1. the actions to execute, and
2. the order in which these actions execute.
Correctly specifying the order in which the actions execute is essential. Consider the
“rise-and-shine algorithm” that an executive follows for getting out of bed and going to
work: (1) Get out of bed; (2) take off pajamas; (3) take a shower; (4) get dressed; (5) eat
breakfast; (6) carpool to work. This routine gets the executive to work well prepared to
make critical decisions. Suppose the executive performs these steps in a different order: (1)
Get out of bed; (2) take off pajamas; (3) get dressed; (4) take a shower; (5) eat breakfast;
(6) carpool to work. Now, our executive shows up for work soaking wet. Program control
specifies the order in which statements (actions) execute in a program. This chapter inves-
tigates program control using Python’s control statements.
Self Check
1 (Fill-In) A(n) is a procedure for solving a problem. It specifies the to
execute and the in which they execute.
Answer: algorithm, actions, order.
75 Control Statements and Program Development 3.3 Pseudocode 75
3.3 Pseudocode
Pseudocode is an informal English-like language for “thinking out” algorithms. You write
text that describes what your program should do. You then convert the pseudocode to
Python by replacing pseudocode statements with their Python equivalents.
Addition-Program Pseudocode
The following pseudocode algorithm prompts the user to enter two integers, inputs them
from the user at the keyboard, adds them, then stores and displays their sum:
Prompt the user to enter the first integer
Input the first integer
Self Check
1 (True/False) Pseudocode is a simple programming language.
Answer: False. Pseudocode is not a programming language. It’s an artificial and informal
language that helps you develop algorithms.
2 (IPython Session) Write Python statements that perform the tasks described by this
section’s pseudocode. Enter the integers 10 and 5.
Answer:
In [1]: number1 = int(input('Enter first integer: '))
Enter first integer: 10
Flowcharts
A flowchart is a graphical representation of an algorithm or a part of one. You draw flow-
charts using rectangles, diamonds, rounded rectangles and small circles that you connect by arrows called flowlines.
Like pseudocode, flowcharts are useful for developing and repre- senting algorithms. They clearly show how
forms of control operate. Consider the follow- ing flowchart segment, which shows sequential execution:
We use the rectangle (or action) symbol to indicate any action, such as a calculation or an
input/output operation. The flowlines show the order in which the actions execute. First,
the grade is added to the total, then 1 is added to the counter. We show the Python code
next to each action symbol for comparison purposes. This code is not part of the flowchart.
In a flowchart for a complete algorithm, the first symbol is a rounded rectangle con-
taining the word “Begin.” The last symbol is a rounded rectangle containing the word
“End.” In a flowchart for only a part of an algorithm, we omit the rounded rectangles,
instead using small circles called connector symbols. The most important symbol is the
decision (or diamond) symbol, which indicates that a decision is to be made, such as in an
if statement. We begin using decision symbols in the next section.
Selection Statements
Python provides three types of selection statements that execute code based on a condi-
tion—an expression that evaluates to either True or False:
1. Bohm, C., and G. Jacopini, “Flow Diagrams, Turing Machines, and Languages with Only Two For-
mation Rules,” Communications of the ACM, Vol. 9, No. 5, May 1966, pp. 336–371.
77 Control Statements and Program Development 3.4 Control Statements 77
Repetition Statements
Python provides two repetition statements—while and for:
• The while statement repeats an action (or a group of actions) as long as a condi-
tion remains True.
• The for statement repeats an action (or a group of actions) for every item in a
sequence of items.
Keywords
The words if, elif, else, while, for, True and False are keywords that Python reserves
to implement its features, such as control statements. Using a keyword as an identifier such
as a variable name is a syntax error. The following table lists Python’s keywords.
Python keywords
Self Check
1 (Fill-In) You can write all programs using three forms of control— ,
and .
Answer: sequential execution, selection statements, repetition statements.
2 (Fill-In) A(n) is a graphical representation of an algorithm.
Answer: flowchart.
3.5 if Statement
Suppose that a passing grade on an examination is 60. The pseudocode
If student’s grade is greater than or equal to 60
Display 'Passed'
determines whether the condition “student’s grade is greater than or equal to 60” is true
or false. If the condition is true, 'Passed' is displayed. Then, the next pseudocode statement
in order is “performed.” (Remember that pseudocode is not a real programming lan-
guage.) If the condition is false, nothing is displayed, and the next pseudocode statement
is “performed.” The pseudocode’s second line is indented. Python code requires indenta-
tion. Here it emphasizes that 'Passed' is displayed only if the condition is true.
Let’s assign 85 to the variable grade, then show and execute the Python if statement
for the pseudocode:
In [1]: grade = 85
The if statement closely resembles the pseudocode. The condition grade >= 60 is True,
so the indented print statement displays 'Passed'.
Suite Indentation
Indenting a suite is required; otherwise, an IndentationError syntax error occurs:
In [3]: if grade >= 60:
...: print('Passed') # statement is not indented properly
File "<ipython-input-3-f42783904220>", line 2
print('Passed') # statement is not indented properly
^
IndentationError: expected an indented block
An IndentationError also occurs if you have more than one statement in a suite and
those statements do not have the same indentation:
In [4]: if grade >= 60:
...: print('Passed') # indented 4 spaces
...: print('Good job!) # incorrectly indented only two spaces
File <ipython-input-4-8c0d75c127bf>, line 3
print('Good job!) # incorrectly indented only two spaces
^
IndentationError: unindent does not match any outer indentation level