Python Textbook 1701285714
Python Textbook 1701285714
Python Textbook
1. Chapter 1: Introduction 1
2. Chapter 2: Python Basics 14
3. Chapter 3: Numeric Data 26
4. Chapter 4: Strings 38
5. Chapter 5: Printing 47
6. Chapter 6: Selection 57
7. Chapter 7: Repetition 74
8. Chapter 8: User-defined Functions 91
9. Chapter 9: Lists and Dictionaries 99
10. Chapter 10: Data Files 113
11. Chapter 11: Making Computer Games 125
12. Chapter 12: Turtle Graphics 139
13. Chapter 13: Graphical User Interfaces using 149
Tkinter
14. Chapter 14: Web Applications using Server-Side 162
Scripting
1. Chapter 1: Introduction
Chapter 1
INTRODUCTION
Topics Covered:
• Benefits of coding
• Computer basics
• Algorithms
• Flowcharts
• Programming
Chapter 1: Introduction | 1
“Everybody should learn to program a computer, because it teaches
you how to think.”
– Steve Jobs, Apple founder
Benefits of Coding
Why should I learn to code? If you are not planning to be a
software developer, this is a reasonable question. If you are a
business student or a psychology major it may be difficult to see
how coding fits into your career plans. The goal of this book is to
help you understand how learning to code is a skill that will help you
in any career. Through learning to code you will no longer only be
a computer user; you will become a coding Jedi with the ability to
command the computer to obey your will.
Benefits of learning to code include:
2 | Chapter 1: Introduction
industry consistently rank problem solving as the most desired
skill for new hires. Coding helps you to become a better
problem solver by teaching you to break down problems into a
logical and structured format. In addition, it’s often necessary
to find creative problem solutions that are different than
anything that’s been done before. This analytical process will
come in handy whenever you need those skills to tackle a
challenging problem at work or in your daily life.
2. You may need to code in your job: It doesn’t matter if you are a
scientist in a research lab or a financial planner working in an
office; there may come a time when you need to write code.
You may need to solve a small task that your current software
cannot perform. Sometimes the need to code shows up in a
surprising context. Creating database queries and spreadsheet
macros are essentially instances of coding. With your
newfound programming skills, you will be able to write a
program to solve that task and impress your boss.
3. You can develop a basic understanding of how software
works: In virtually every career, you will be working with
technology and software on a daily basis. Once you have
written programs yourself, you will gain an appreciation and
understanding of how software works. You will gain insights
into what features can be better exploited and be able to
identify deficiencies or limitations in the programs that you are
using.
4. You can learn to be persistent: Albert Einstein famously stated,
“It’s not that I’m so smart, I just stay with problems longer.”
Coding helps you learn to be persistent when facing difficult
problems. You may get stuck and hit roadblocks on your
journey, but the satisfaction of sticking with it and finding a
solution is worth the effort. It takes persistence to be
successful in almost any endeavor, and coding helps you learn
persistence.
5. You can communicate about technology effectively: Learning
the basics of programming will be helpful in job situations
Chapter 1: Introduction | 3
where a non-techie will need to talk to someone in the
computing field. There are so many terms and phrases that you
will pick up while learning to program. You won’t have to speak
the techie language perfectly, but you will know enough to pick
up on important conversations among computing
professionals, especially if you are working with software
developers.
4 | Chapter 1: Introduction
The software is the computer programs. This consists of both the
operating system (Windows, Macintosh, Linux, etc.) and the
applications (word processor, spreadsheet, games, web browser,
etc.).
As illustrated in the previous figure, most computers today use
the von Neumann architecture. This means that programs and data
are loaded into RAM before a program runs. When you double-click
on a program icon to run a program, you may notice a slight delay
before your program appears. That is your computer loading the
program and any necessary data from the external storage into the
internal memory unit.
When we create software, most of the time our programs will
follow the data processing cycle. This consists of three stages: (1)
input, (2) processing, and (3) output. This cycle is illustrated below.
Chapter 1: Introduction | 5
the monthly electricity bill. You decide to write an algorithm that
will solve this problem.
With a little digging on the Internet, you discover that in order to
find the cost of electricity, you will need to know three things: (1)
the wattage of your light bulb, (2) how many hours did you leave it
on, and (3) the price that your electric company charges. You also
discover that to compute this cost, you simply multiply the wattage
by the hours, then divide that by 1,000 times the price of electricity.
You divide by 1000 since electric companies charge by center per
kilowatt-hours, and we are asking the user to enter the time in
hours. Therefore, your algorithm ends up looking like this:
Algorithm for computing cost of electricity:
◦ Output cost
6 | Chapter 1: Introduction
algorithm
3. Definiteness – the algorithm must specify every step and the
order the steps must be taken in the process
4. Effectiveness – every step must be feasible. You couldn’t have
a step, for example, that said “list every prime number”
5. Finiteness – the algorithm must eventually stop
Flowchart
A flowchart is a visual representation of a problem solution.
Different shapes in a flowchart have different meanings. Arrows,
or arcs, connect the shapes and provide the flow of control for
your problem solution. The following table illustrates the meaning
of some of the more commonly used flowchart shapes.
Ellipse Start/End
Parallelogram Inputs/Outputs
Formulas/
Rectangle
Actions
Diamond Decisions
Chapter 1: Introduction | 7
Going back to the problem of computing the electricity, let’s take
a look at those steps expressed using a flowchart. There are many
tools for creating a flowchart. We recommend using the free web
http://draw.io to build your flowcharts.
8 | Chapter 1: Introduction
Chapter 1: Introduction | 9
Figure 1.3: Flowchart to compute the cost of electricity.
10 | Chapter 1: Introduction
might be used to tell the computer to add the values in memory
locations 123 and 147, rather than the binary form:
00101010 01111011 10010011
Of course, the computer didn’t, and still doesn’t, understand
assembly language directly. Instead, special programs, called
assemblers, were (and are) used to translate assembly language to
its binary equivalent.
Although assembly language programming is still an option with
computer systems, it’s used only sparingly, primarily for performing
very low-level tasks where direct communication with the
computer’s hardware is required. Most programming is instead
done using more sophisticated languages. This is because assembly
language is still quite difficult to work with, requiring even the
simplest tasks to be broken down into sequences of several, or even
several hundred, instructions. Also, virtually every computer system
has its own unique assembly language. To run an existing assembly
language program on a new computer system requires translation
of the program into the new system’s assembly language – often a
formidable task.
The Development of High-Level Languages
High-level programming languages were first introduced in the
1950s. Whereas each instruction in an assembly language
represents a single machine language instruction, a single high-
level language instruction will usually translate into several machine
language instructions. This implies, of course, that high-level
languages are far more expressive than assembly languages. It also
implies that the translation process required to convert programs
written in these languages into a form that the computer can
process is far more complex.
There are two strategies for translating high-level languages. The
first, software called a compiler translates programs fully into
machine language. Once translated, the compiled program can be
run at any time without any additional translation required. In
contrast, other languages are interpretive. When a program written
in an interpretive language is run, an interpreter program reads one
Chapter 1: Introduction | 11
instruction at a time, and determines how to carry out the required
action.
To better understand the difference between compiling and
interpreting, imagine that you have an article written in a foreign
language. You could hire someone to translate the article to English
and give you a written copy of this translation. This is what a
compiler does. Alternatively, you could hire someone to read the
article aloud, translating it to English as they read. This is what an
interpreter does. Notice the important difference between these
two approaches. When the article is “compiled” for you, you can
refer back to the translated version at any time; the “interpreted”
version, however, is not retained, and you’d need to seek out your
interpreter again if you want to review the article’s contents.
There are literally hundreds of different high-level programming
languages. When first learning to program, one of the first
challenges is the selection of an appropriate language. The TIOBE
(The Importance Of Being Earnest) index is a measure of the
popularity of programming languages. This list gets updated
monthly, but here is a recent glimpse of the top ten high-level,
general-purpose languages:
1. C
2. Java
3. Python
4. C++
5. C#
6. Visual Basic
7. JavaScript
8. PHP
9. Go
10. R
12 | Chapter 1: Introduction
Python for free in just a matter of minutes. Before you know it, you
will be writing your first programs.
a. Arrow
b. Diamond
c. Ellipse
d. Parallelogram
e. Rectangle
Programming Projects:
1.1. Answer the following questions about algorithms:
Chapter 1: Introduction | 13
2. Chapter 2: Python Basics
PYTHON BASICS
Topics Covered:
• Python overview
• Download Python
• Creating our first program
• Saving and running a program
Python Overview
In this book we use Python as the introductory programming
language. One of the primary reasons we chose Python is because
it is considered an easy to learn language. The designer of the
When you open Idle for the first time, a window similar to the
one above will appear. The Python version number (In this case,
3.8.0, since the author was too lazy to update his computer to
version 3.9.2) is shown in the window title and the first line inside
the window. The Idle environment has two modes. Initially, the
environment is in interactive mode, which allows you to evaluate
expressions and individual instructions. When you want to develop
a larger program, however, you will want to switch to script mode.
The string “>>>” is the screen prompt which tells you that the
environment is waiting for you to type a Python expression or
instruction. The interactive mode can be used to play around and
just experiment with different commands. Try typing the four
expressions shown below following the prompt. You will notice that
When you type 3+2 and press the Enter key, the result of 5 is
returned. Of course, this comes as no surprise. In the interactive
mode, the expression you enter is executed immediately. You will
notice that all of the program output is displayed by Idle as blue.
Obviously, 4*5 resulted in 20. Why did 2**5 return 32? If it isn’t
obvious, see if you can research (i.e., Google) the answer.
Whenever you want to display something in Python, you use a
special function called print. All of the built-in Python functions
appear as purple in Idle. Also note how the word “hello” appeared in
double quotes. This means it is a string, or sequence of characters.
Idle displays strings using green. The last example had a string,
followed by *, followed by a whole number. How did Python evaluate
that expression?
Now, let’s get back to tackling the electricity problem from the
chapter one. In your new script window, type the following
program, replace the X’s with your name and the current date. We
will break each instruction down, line by line, afterwards.
Note: It is important that you actually type in this program to
get used to this environment of creating, editing, troubleshooting,
saving, and running programs.
The lines at the top of this programming that begin with the pound
sign (#) are called comments. When the interpreter goes to translate
and run your code, it will ignore comments. These lines are added to
document your program. That is, the comments will describe your
program and various aspects of it. As a minimum, you should include
the 4-line comment block illustrated in this example.
As mentioned earlier, the print function is used to display
information to the screen. Each print statement will send an output
to a new line. With the print function, you include what you want
displayed inside parentheses. Anything inside the parentheses of
a function is called a parameter. With no parameter, the print
function simply outputs a blank line.
The input function is used to get information from the user via
the keyboard. The program will pause until the user types
information followed by the Enter key. Data will be read in as a
string and stored as a variable, which is simply a named memory
location. The parameter for the input function is a prompt that is
displayed as a hint to the user indicating what should be entered at
the keyboard.
You should notice in the program the same input statements
for wattage, hours, and price that we saw in the algorithm and
flowchart in chapter one. Since the input function returns the user’s
input as a string, we need to use the float function to convert that
string to a floating-point number. Data types will be discussed in
more detail in the upcoming chapters.
The program shows us that it will cost $4.25 to leave that lamp on
for a month straight. Of course, we have a lot more decimal places
than we need, but we will worry about formatting our output later.
We have a working program that solves our problem!
It is possible that your program did not run successfully. If you
mistype one or more instructions, you may have created a syntax
error, which is when one of your instructions breaks the rules of
the language. For example, suppose you forget the closing right
parenthesis at the end of the first print instruction. As shown below,
Idle will display a pop-up screen with an error message. The
position of that error will be highlighted in red in your program
code.
Now that you’ve successfully created, saved, and run your first
Python program, it’s time to start digging deeper. In the chapter
three, we will discuss the most common numeric data types used in
Python programs, as well as the operations and functions associated
with each.
Programming Projects:
2.1. Many athletes are concerned with reaching their
ideal training heart rate during their workouts.
Topics Covered:
• Data types
• Numeric operators
• Precedence rules
• Assignment
• Error types
“I think that great programming is not all that dissimilar to great art.
Data Types
Ultimately, everything that is stored within a computer’s memory
is a number. The computer’s processing unit has to decide, based on
context, what the numbers in the memory represent. If the CPU is
asked to execute the instruction at memory location 385, the CPU
assumes that the number stored in that memory location should
be treated as a machine language instruction. If that instruction at
location 385 indicates that the contents of memory location 1376
should be added to the contents of memory location 2795, then the
CPU will treat the values in those memory locations as numbers.
A major distinction between different programming languages is
the set of resources provided by that language for interpreting the
values stored in the computer’s memory. The different mechanisms
provided by the language are generally referred to as the language’s
data types.
The simplest data type supported by virtually all programming
languages is the numeric data type. Just like we recognize two kinds
of numbers, whole numbers and fractions, computers normally
distinguish between int, or whole number values, and float, or
fractional values. Technically, a float value is actually like a decimal
representation of a fraction. And just like some fractional values, like
1/3, don’t have an exact decimal representation, many float values
are actually approximations for the fractional value that is being
represented.
In practice, we will use an int when storing a whole number such
as a person’s age (i.e., 19) or golf score (i.e., 97). Float is short for
floating point number and can stores things like a grade point
average (i.e., 3.48) or a bank account balance (i.e., 578.25).
As a programmer, you have to decide on the data type as you
Numeric Operators
As you begin to solve problems, you will use numeric operators to
create formulas. The next table shows some of Python’s most
common numeric operators.
Precedence Rules
Suppose a student decided to use Python in the interactive mode
to find her average of three exam scores: 70, 80, and 90. When she
typed in the expression, the result is shown below:
1. Parenthesis
2. Exponent
3. Multiplication and division (left to right)
4. Addition and subtraction (left to right)
Variable Assignment
To give a value to a variable you use an assignment statement.
The assignment operator is the equal sign (=). The instruction age
= 19 will assign the value 19 to the variable age. Technically, age is a
reference that identifies the memory location where your program
stored the number 19. You might picture your computer’s memory
as a bunch of cells:
Error Types
You noticed in that last example that a message popped up. Errors
show up in red when you work in Idle, so we try to avoid that
color. In this example, we tried to print the contents of a variable
named temp, but we never created or defined that variable. Python
will not permit you to access a variable if you haven’t defined it.
Every language has its own syntax, which are the rules of
language. This includes the language structure, whitespace,
reserved words, etc. If one of your instructions breaks one of these
language rules, it is called a syntax error. Unfortunately, many
beginning programmers (as well as some experienced
programmers) mistakenly believe that, once they have removed all
syntax errors, their programmers are good to go. The table below
shows three types of common programming errors. A runtime error,
such as dividing by zero or taking the square root of a negative
number, occur during program execution. With a logical error, your
program runs but the intended results or outputs are not correct.
INTERACTIVE – Debugging
Often times, we describe an error in a computer program as a bug.
The process of removing those errors is therefore called debugging.
To give you a little practice debugging, consider the program below.
It is trying to compute and display the hypotenuse of a right triangle
In the sample run below, the user input 68 as the number of cents
the customer should be given. If you look at 68//25, the integer
division returns 2 as the number of quarters. The expression 68%25
Programming Projects:
3.1. If P dollars (called the principal) is invested at r% interested
compounded annually, then the future value of the investment
after n years is given by the formula:
Topics Covered:
• Strings
• Common String Methods
• Casting
Strings
To computer programmers, a string is simply a sequence of
characters. A specific example of one is called a string literal, and
is surrounded by quotes. Examples include “Donald Duck”,
“35630-1418”, “Florence, Alabama”, and “”. That last example, called
an empty string, has no characters. You may have also noticed the
second example had numeric digits in it. A string may contain any of
38 | Chapter 4: Strings
the printable characters you see on your keyboard, as well as some
characters that don’t show up there.
We use string variables all of the time to store data that is not
numeric. The computer stores this data in memory using an
encoding called ASCII (American Standard Code for Information
Interchange). You might visualize a string as a table, with each slot
storing a single character. Take a look at the following 11-character
string literal “Roar Lions!”:
0 1 2 3 4 5 6 7 8 9 10
R o a r L i o n s !
Chapter 4: Strings | 39
Taking a look at this example, you should notice that Idle output the
resulting strings with single quotes. You can use single or double
quotes for strings. When displaying the 5th character – the
character in position 4 – a space is printed. You can use [m:n] to
create a substring, or slice, of a string. It returns the string that
starts at position m and ends at position n-1.
The following example shows four examples of the slice. The
first displays a string beginning at position 3 and goes up to but
does not include position 5. The second example displays
characters 7 through 10. The third example does not include an
ending number after the colon. This will display all characters at
position 3 and beyond. The final example is missing the beginning
subscript before the colon. All characters before position 5 are
displayed.
You can use the Python len() function to determine the length of a
string. The following shows you a couple examples using len():
40 | Chapter 4: Strings
Figure 4.4: The Python len function.
Chapter 4: Strings | 41
Figure 4.5: Python string methods.
The find message searches the string for a pattern and returns the
position where it matches. The pattern “quiz” was found at position
7. The pattern “Love” was not found so a -1 was returned. Notice that
the matching is case-sensitive.
When applied to numbers, the plus (+) operator is used to add the
two operands. You can also use this same plus operator with two
strings. It will perform string concatenation, which simply means
the strings are joined together. When a language defines an
operator to perform different functions depending on its operands,
this is called operator overloading. It’s intuitive and easy to use, as
illustrated below:
42 | Chapter 4: Strings
Figure 4.6: Combining strings with the plus (+) operator.
In the examples above, you can see how you can apply the plus
operator multiple times and it will concatenate the strings from
left to right. The example demonstrates how you could use plus
operator to combine strings and then store the result to a variable.
As previously mentioned, the input function allows the user to
enter information from the keyboard. The result is a string that
is usually assigned to a variable. Most of the time, you will want
to provide a prompt as a parameter to the function so that the
user knows that your program is waiting for some input. Here is an
example that shows a few examples:
Chapter 4: Strings | 43
Figure 4.8: Program interaction.
Casting
In the previous example, all of the input values were used as
strings. When we need the user to enter a number that will be used
in an arithmetic expression, we need to use type casting, which is
converting from one type to another. Here are a couple of examples
from the interactive window that demonstrate type casting:
44 | Chapter 4: Strings
string slicing function. Experiment with different inputs and try to
predict the output before you run the program.
Chapter 4: Strings | 45
Figure 4.11: Program interaction.
As you can see from the code, a type cast was needed to convert
the meal cost and tip percentage from a float to a string. A type
cast was not needed for the wait person since it is already the
intended string type.
46 | Chapter 4: Strings
5. Chapter 5: Printing
PRINTING
Topics Covered:
Chapter 5: Printing | 47
You can see from these examples that the print statement allows
any number of parameters, or items between the parentheses. In
the first example, there was only one parameter, “dog”. The second
example had no parameters so it just printed a blank line. The final
two examples each had three parameters. Notice how a space was
displayed between each item; this sets Python apart from many
other commonly-used programming languages.
If you wanted something other than a space between each item,
you can define the separator with the sep attribute of the print
statement. Here are some examples of programmer-defined
separators:
48 | Chapter 5: Printing
You can see in each example, the items that were normally
separated by a space are now separated by the string that
followed sep=. The third example shows how you can use the empty
string to print items without any separation. The final two examples
begin with a backslash (\) and create what is called an escape
sequence. The character that follows the backslash defines a special
character. The “\t” produced a tab and the “\n” created a newline.
We have previously seen that each print statement will generate
output on a new line. Occasionally, you would like to display
something, but you do not want to move the following output to the
next line. In this case, you can define how the line should end be
setting the end attribute to a string that should terminate the print.
Here is an example:
In this code example, the first three print statements are directing
each output to be terminated with a space instead of the default
Chapter 5: Printing | 49
new line. Without these three end=” “ clauses, the four print
statements would create four lines of output. Instead, the output
looks like this:
Rounding Numbers
We introduced the round function in chapter 3. It can be used to
round a floating point to the nearest integer. It can also be used
to round a floating point number to a specified number of decimal
places. It is important to note that when you use round in a print
statement with a variable, the value of that variable does not actually
change. This example will illustrate the point:
The output when that code segment is executed looks like this:
There are cases in which you would like to store the rounded result
of an expression. Perhaps you are rounding a currency expression
to the nearest hundredth so you can keep track of dollars and
cents. In the following example, we compute the simple interest
for an amount of $465.83 deposited in an account earning 4.25%
interest for 2.5 years. We will display that interest as calculated, plus
rounded using 2 decimal places. Here is the Python code along with
the output displayed by the program:
50 | Chapter 5: Printing
You can either round a previously calculated result, or you can
include the round function in the computation, as shown below:
roundedInterest = round(interest,2) # store to a new variable
interest = round(principal*rate*time,2) # round formula
Format Specifiers
Sometimes, rounding alone doesn’t provide enough control over
the output’s appearance. Let’s take a look at the simple interest
example again, but this time use data that produces an interest
value that naturally ends with only one decimal place. Here is the
Python code and the sample run:
Chapter 5: Printing | 51
specifier to force two decimal places to be printed. Here is the new
and improved version, along with the program’s output:
In the example above, the format specifier “%.2f” was placed before
the variable interest with a percent symbol, %, separating the two.
This expression forces the output to display two digits after the
decimal point. Python provides quite a bit of functionality with
format specifiers, as illustrated below:
The “%xxd” specifier is used to define the total width of the output
field. By default, the result is aligned to the right, or right justified,
with spaces attached to the left of the value. The dash (-) can be
used to change the alignment to the left so spaces are instead added
to the right when integers d, e, and f are displayed:
52 | Chapter 5: Printing
Python also allows you to combine rounding and field-width
specification into a single formatting specification. This is especially
useful when you are trying to align numbers into columns. In the
Python code below, we will display each of four numbers using two
decimal places and a total of seven characters:
In this output, notice that the value 893.00 takes up six characters
so one space was added on the left. Also, observe that the decimal
points all align vertically, as well as the digits in the tenths and
hundredths place.
Chapter 5: Printing | 53
We have seen how the letter d is used for integers and f is used for
floating point numbers. You can use the letter s when formatting
string variables or expressions. The alignment for strings is similar
to that of integers. In the next example, we will display the first
name, last name, and career rushing yards for three former football
players. In each case, both the first and last names will be displayed
in 10-character fields, aligned on the left. The rushing yards will
be displayed in eight-character fields; special formatting is used to
specify that commas should be used to separate the numeric values
in three-digit groups.
54 | Chapter 5: Printing
from this version of the text. You can view them online here:
https://una.pressbooks.pub/python-textbook/?p=28
Chapter 5: Printing | 55
You can use f-strings to specify the spacing and precision of
variables or expressions that you want to display. Below we print
the value of the floating point variable named number, first
with 1 decimal place, then with 5 decimal places:
56 | Chapter 5: Printing
6. Chapter 6: Selection
SELECTION
Topics Covered:
Chapter 6: Selection | 57
decision‑making capability is provided by the if statement, which
has the following format:
if Condition:
Action
In this prototype, Condition stands for any expression that can
be evaluated to either True or False. Most often, the Condition is
a simple comparison. In Python, you can use the following
comparison operators:
Operator Meaning Example
== is equal to A == B
< is less than A<B
> is greater than A>B
!= is not equal to A != B
<= is less than or equal to A <= B
>= is greater than or equal to A >= B
These operators should be self‑explanatory. You need to be
careful, though, when comparing fractional values, since equality
rarely holds between two fractional variables or expressions. This is
because fractional values are approximated in the computer. When
a series of arithmetic operations is performed using approximated
values, it is almost inevitable that these values will undergo a
significant amount of round-off in the final decimal places. Here
are a couple of examples of conditions, or Boolean expressions,
evaluated in the Python Interactive window:
58 | Chapter 6: Selection
The Action component of the if statement is the instruction, or
series of instructions, to be carried out if the condition is True. If
more than one instruction is to be carried out, the whole series
of instructions should be indented at the same level. This tells the
computer to treat the entire group of instructions, commonly
referred to as a block, as a single unit. Python’s Idle environment
assists you by automatically indenting when you type a colon at the
end of a line.
To illustrate, the following are examples of legal if statements in
Python:
if hoursWorked <= 40:
grossPay = rate * hours
if prevID != currID:
idCount = idCount + 1
prevID = currID
In the first example, the variable hoursWorked is compared to 40;
if it is less than or equal to 40, the value of grossPay is computed by
multiplying rate by hours.
In the second example, the variables currID and prevID are
compared. It’s assumed that these are both numeric variables. If the
values don’t match exactly, then two actions are carried out. First, 1
Chapter 6: Selection | 59
is added to the variable idCount; presumably, the program is going
to count how many distinct identification numbers are processed.
Second, the value of the variable currID is being copied into the
variable prevID.
It is worth emphasizing here just how important
the indentation of blocks is with Python. Most languages use either
keywords, such as begin/end, or curly brackets { }, to indicate
blocks of code. The white space (space, tab, new line) in these
languages is ignored. For a block to work in Python, the indenting
for each instruction has to be created using the same keystrokes.
For example, you cannot use the TAB key on the first line of the
block and then consecutive spaces on the second line, even if they
appear to visually align vertically.
The standard comparison operators (<, <=, >, >=, ==, and !=) can be
used to compare strings, as well as for comparing numeric values.
You should be aware, though, that string comparison is case
sensitive. The ASCII values of characters are used when
comparisons are made between two strings. Here are some
examples:
In the first example, “fish” is less than “turkey” because the ASCII
60 | Chapter 6: Selection
value of “f” (102) is less than that of “t” (116). A “d” has a value (100)
greater than that of “c” (99), so “dog” is not less than “cat”. When
strings begin with the same character, the comparison moves on
to succeeding characters until characters in the two strings differ.
The string “twinkie” is less than “twister” since the fourth character
“n” had an ASCII value (110) less than that of “s” (115). Finally, upper
case letters have smaller ASCII values than lower case letters. The
string “cat” is not less than “Cat” because the “c” has a value of
99 and the “C” has a value of 67. Since 99 is not less than 67, the
expression “cat”<“Cat” returns False.
Chapter 6: Selection | 61
While this may seem like a minor difference, it does improve the
overall readability of the program.
62 | Chapter 6: Selection
associated with the most recent if. Perhaps the simplest way to
understand its use is to think of it like this:
If some condition is true,
here’s what I want you to do.
But if that condition is false,
I want you to do this, instead.
As with the simple if statement, multiple actions are specified
by indenting those instructions to the same level. For example,
if a company’s payroll required regular and overtime pay to be
calculated separately, it might be done like this:
if hoursWorked <= 40:
regularPay = hoursWorked * hourlyRate
overtimePay = 0
else:
regularPay = 40 * hourlyRate
overtimePay = 1.5 * hourlyRate * (hoursWorked – 40)
As you model the decision-making process using a flowchart,
whenever a condition occurs, you should include that condition
inside of a diamond. Two arrows will exit the diamond, one
designating the path if the condition is True; the other path when
the condition is False. Below are flowcharts modeling
an if statement and an if-else statement.
Chapter 6: Selection | 63
Flowchart Modeling an if statement.
64 | Chapter 6: Selection
Flowchart Modeling an if-else statement.
Suppose the local bagel shop asked you to write a simple program to
compute the charge for each customer’s purchase. Bagels normally
cost 75 cents each, but if you buy a half-dozen or more, then the
charge is 60 cents per bagel. Of course, once we learn the quantity,
a decision needs to be made. Our newly acquired if-else statement
would be perfect here:
Chapter 6: Selection | 65
# Program to compute charge for bagel sale
# Written by XXX XXXXX
# CS101 – Introduction to Computer Programming
# Date: XX/XX/XXXX
quantity = int(input(“How many bagels do you want? “))
if quantity<6:
charge = .75 * quantity
else:
charge = .60 * quantity
print(“Total charge is”, charge)
66 | Chapter 6: Selection
While less common, it’s sometimes necessary to mix “and” and
“or” conditions in a single expression. Python has default rules for
interpreting these expressions, but it’s probably best to instead use
parentheses to explicitly dictate the order in which the individual
expressions should be combined.
Although not required, you can add parentheses, which many
people find to be more readable:
if (testAvg < 60) or (absences >= 10) :
or even:
if ((testAvg < 60) or (absences >= 10)) :
Finally, in some contexts, it’s desirable to perform some action
if some condition or conditions are NOT met. Typically, the
word not is placed outside of a parenthesized expression. For
example, you could check to see if a salesperson is not eligible for a
bonus like this:
if not (numCustomers >= 20 and totalSales >= 10000):
…
An easier way to ask this same question, though, might be to ask:
if numCustomers < 20 or totalSales < 10000:
…
Nested if Statements
Whenever one or both of the actions associated with an if –
else instruction contains another if statement, the resulting form
is referred to as a nested if. The nested form arises naturally in
contexts where a choice must be made between several different
options. To illustrate, consider the following scenario.
To receive a grade of A, a student’s average must be at least 90. A
B will be assigned if the average is at least 80, but less than 90, while
a C is assigned for a grade of at least 70, but less than 80. For an
average of 60 or higher, but less than 70, the letter grade is D, while
an average below 60 leads to a grade of F.
Using only if statements, this grade assignment problem could be
programmed like this:
if average >= 90:
Chapter 6: Selection | 67
grade = ‘A’
if average >= 80 and average < 90:
grade = ‘B’
if average >= 70 and average < 80:
grade = ‘C’
if average >= 60 and average < 70:
grade = ‘D’
if average < 60:
grade = ‘F’
While this sequence will certainly do the trick, it requires several
redundant comparisons, and also contains a number of potential
trouble spots, where either numbers or comparison operators could
easily be messed up.
An alternate form, which significantly reduces the number of
comparisons required, is the following:
grade = ‘A’
if average < 90:
grade = ‘B’
if average < 80:
grade = ‘C’
if average < 70:
grade = ‘D’
if average < 60:
grade = ‘F’
While this form is clearly shorter, it’s far more difficult to
understand, because it relies on a trick. Every student is initially
assigned an A, and then their grades are reassigned as each new test
shows their average to be lower. Often, programmers forget that
other people need to be able to understand their programs, too, and
will rely on tricks that, while the trick they came up with might be
obvious to them, it might not be obvious to others.
68 | Chapter 6: Selection
A cleaner version of the grade checker, which takes advantage of
the elif statement to assign a grade to each student exactly once,
would be:
The comments on the right clarify why this form works. When
an if statement follows an else, it can rely on the fact that the
condition associated with the preceding if is already known to
be False. This characteristic is shown in most well written
nested if blocks – the secondary if statements are placed so they
follow an else, thereby ensuring that the earlier if condition is
already known to be False.
Whatever you do, don’t place the if within the if portion, as
illustrated below:
While this form will, in fact, work properly, it’s a rare person who
could figure it out on the first try!
Chapter 6: Selection | 69
The program below asks the user to enter a number. It will then
display whether the input number is positive, negative, or zero. The
only problem, though, is that the code contains three errors. Can
you fix it?
70 | Chapter 6: Selection
Flowchart Modeling the Bank Withdrawal Problem.
Chapter 6: Selection | 71
b = 12
c=8
What is the value of the following condition (True or False)?
a != b
6.2. Given the following Python instructions:
a = 12
b = 12
c=8
What is the value of the following condition (True or False)?
a < b and b > c
6.3. Given the following Python instructions:
a = 12
b = 12
c=8
What is the value of the following condition (True or False)?
a < b and b > c
6.4. Show the output if the following Python instructions were
executed:
a=4
b=5
c = 13
if a+b < 10:
print(c)
else:
print(a)
6.5. Show the output if the following Python instructions were
executed:
miles = 10
if miles<20:
price = 5 + .30*miles
else:
price = 2 + (20-miles)*.10
print(price)
Programming Projects:
72 | Chapter 6: Selection
6.1. Write a program that will ask for the name and age of two
people. The program should then display a message saying either
“X is older than Y”, “X is younger Y”, or “X is the same age as Y”
(assuming the first person has name X and the second person has
name Y).
6.2. Leo’s Print Shoppe charges 8 cents per copy for the first 50
copies and 5 cents per copy for the copies beyond the first 50. Write
a Python program that asks for the customer’s name and how many
copies they need. Your program should output the customer’s name
and the total cost (using a dollar sign and 2 decimal places).
Chapter 6: Selection | 73
7. Chapter 7: Repetition
REPETITION
Topics Covered:
• Repetition
• While loop
• For loop
• Range()
• Finding maximum
Repetition
Suppose a student was trying to compute the average of three
exam scores. It would be relatively easy to construct a Python
program to do this:
exam1 = float(input(“Enter exam #1 score: “))
exam2 = float(input(“Enter exam #2 score: “))
74 | Chapter 7: Repetition
exam3 = float(input(“Enter exam #3 score: “))
average = (exam1 + exam2 + exam3) / 3.0
print(“The average is”, “%.1f”%average)
Okay, but what if there were five exam scores instead of three?
Well, that’s obvious. Just create two more variables, add two inputs,
and then divide the sum by 5.0 instead of 3.0:
exam1 = float(input(“Enter exam #1 score: “))
exam2 = float(input(“Enter exam #2 score: “))
exam3 = float(input(“Enter exam #3 score: “))
exam4 = float(input(“Enter exam #4 score: “))
exam5 = float(input(“Enter exam #5 score: “))
average = (exam1 + exam2 + exam3 + exam4 + exam5) / 5.0
print(“The average is”, “%.1f”%average)
Well, what if there were 100 exam scores? Of course, you could
add another 95 variables and 95 input statements, but there must
be an easier way. If we create a total variable and add each exam
score to it once it’s been input, we don’t need to remember the
exam scores. What we would like to do is repeat the same two
instructions (input number, add it to the total) 100 times.
Perhaps the one feature of computers that has contributed the
most to their success is their ability to repeat instructions until
some type of event has taken place. There are several different
instructions that can be used to implement repetitions within a
Python program. These loop instructions, along with the selection
instructions discussed in chapter 6, are examples of control
structures, since they alter the sequential flow of the program.
Chapter 7: Repetition | 75
type of comparison. In operation, the instruction tells the computer
to repeatedly:
a) Test the Condition to see if it is True
b) If the Condition is True, carry out the Action
The key feature that distinguishes this from an if statement is
that fact that this sequence can be carried out over and over, as
necessary, until the value of the Condition becomes False.
Like the if, the Action component of a while instruction may
consist of more than just a single instruction. In this case, it is
necessary to indent at the same level all of the instructions that
make up the Action.
To illustrate the behavior of the while instruction, consider these
examples:
sum = 0
number = 10
while number > 0:
sum = sum + number
number = number – 1
This instruction sequence will add the values 10, 9, 8, and so
on, down to 1, to the variable sum. In other words, the instruction
sequence is a long way to say:
sum = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1
In this example, the indenting of the block is needed to capture
the two instructions that make up the Action. To see why this
matters, take a look at the alternative:
sum = 0
number = 10
while number > 0:
sum = sum + number
number = number – 1
In this case, even though both instructions were intended to be
within the loop, the only instruction actually in the loop is sum
= sum + number. Since the value of the variable number never
changes from its initial setting of 10, this loop will never terminate.
This type of (erroneous) program segment is called an infinite loop.
76 | Chapter 7: Repetition
As a third example of the while instruction, consider this
sequence:
sum = 0
number = 0
while number > 10:
sum = sum + number
number = number + 1
In this case, the apparent intent of the programmer was to count
from 0 up to 10. However, because the Condition is incorrectly
stated, the value of the Condition is initially False. When this
occurs, Python will bypass the instructions that make up the loop
entirely. The while instruction is commonly referred to as a pre-test
loop structure; it tests the Condition at the very start of the loop,
before it carries out the specified Action.
We have seen how useful the Python Interactive mode is for
testing lines of code and experimenting. With multiple-line
instructions like if statements or while loops, you can still use the
Interactive mode. After typing the colon and ENTER after your
control structure’s Condition, the cursor moves to the next line
without displaying the >>> prompt. You can type as many
instructions as you’d like into your block. Just hit ENTER twice
after the final instruction in your block. Here is a simple while loop
example tested in the Interactive window:
Chapter 7: Repetition | 77
Before the loop, the variable num is initialized to 2. Since 2 is less
than 20, the Condition is True and Action will be executed. In this
case, the Action is two instructions, display num and its square,
then increment num by 3. This process continues until num
eventually reaches a value of 23, which is greater than 20, and
causes the Condition to be False.
Let’s look at a full example of the while loop in action. The
problem we want to solve: How long it will take to have half of a
loan paid off? Before we jump into the code, let’s take a look at
a flowchart that models a solution to this problem. Flowcharting
a while loop looks very similar to that of an if statement.
The Condition is represented by a diamond and arrows
labeled True and False must exit this diamond.
In our solution, we will first ask the user to input the amount
of the loan, the annual interest rate, and the
monthly payment amount. We will initialize a balance variable to
the loan amount and set a month variable to 1. Our Condition will
check to see if the remaining balance is still greater than half of
the original loan. For the Action of this while loop, the program will
compute the interest, determine the new balance, and then output
78 | Chapter 7: Repetition
the month, interest, payment and balance. To compute the
interest, the balance is multiplied by the annual interest rate. It is
divided by 12 to convert it to a monthly rate and then divided by 100
to convert it from a percentage to a decimal number. The final step
is to add 1 to the month before looping back to the Condition.
Chapter 7: Repetition | 79
Below is the output of a sample run of the program. Suppose you
bought a “new” car and took out a loan for $14,000. The annual
interest rate was 6.25% and you decided you would make monthly
payments of $500. You can see from the program run that you’ll be
halfway to paying off that loan in just 16 months!
80 | Chapter 7: Repetition
The for Loop
Another common and very powerful repetition structure in
Python is the for loop. The for loop will iterate, or repeat, once for
each item in a sequence. Each time through the loop, you can access
the current item in the sequence using a variable. For example, if the
sequence was 1, 2, 3, 4, 5, then the for loop variable will take on 1 the
first iteration of the loop, 2 in the second iteration of the loop, and
so on. The syntax of the Python for loop looks like this:
for Variable in Sequence:
Action
The Sequence in this statement can take on many forms. We will
see later that the Sequence may contain items in a list or even lines
Chapter 7: Repetition | 81
from a file. The most common use, though, is the range function.
The reference range(m,n) – generates a Sequence m, m+1, m+2, …,
n-1. Let’s take a look at a couple of examples from the Interactive
mode:
82 | Chapter 7: Repetition
Now would be a good time to see how we could use the for loop
to solve a problem: Write a program that will display the world
population through 2025. Assume that the population was 7 billion
in 2011 and that it grows at a rate of 1.1% each year. The program
should display the year and population for each year on a line
together. Here is a look at one solution to this problem:
population = 7000000000
print(“Year Population”)
for year in range(2011,2026):
print(year, f”{round(population):15,d}”)
population = 1.011*population
Shown below is the output when the program was executed.
Notice that this program did not involve any keyboard input from
the user.
Chapter 7: Repetition | 83
There are a couple of things from the code above that probably need
some explanation. First, since we wanted to iterate the year variable
through 2025, the ending value in the range needed to be the next
integer, 2026. To display the population, we first rounded it to the
nearest integer. We then used an f-string to output using 15 total
characters and commas between each 3-digit period.
Another way you could have written the formula for the
population would be to say population = population +
.011*population. In other words, the following year’s population will
be the current population plus 1.1% times the current population.
84 | Chapter 7: Repetition
If you were thinking that you could have solved this problem
using a while loop instead of a for loop, you are absolutely correct.
Shown next is the comparable Python program using a while loop.
It produces the exact same output as the program with the for loop.
You should notice, though, that the while loop version is actually
two lines longer than the for loop version since it was necessary
to initialize the variable year to 2011 before the loop and increment
year during the Action of the loop.
population = 7000000000
year = 2011
print(“Year Population”)
while year < 2026:
print(year, f”{round(population):15,d}”)
population = 1.011*population
year = year + 1
In the previous for loop examples, the value of the control variable
increased by one for each iteration. An alternate form of
the range function can be used that allows a third parameter,
usually referred to as the step. This will make much more sense after
looking at a couple of examples using the Interactive mode:
Chapter 7: Repetition | 85
In the first example, number began at 13 and stepped by increments
of 2. When it reached 21, the loop terminated. In the second
example, thing began at 0 and incremented by steps of 5 until
86 | Chapter 7: Repetition
reaching the ending range value 30. In the final example, item began
at -5, incremented by steps of 3 and stopped when it reached 7.
Finding Maximum
A frequent problem to solve in computing involves finding a
maximum (or minimum) value of a list of numbers. The algorithm to
accomplish this is pretty straightforward:
1. Input a value
If you know in advance how many values you will have, a for loop
is a good choice. Suppose we would like to ask the user how many
values will be entered first. Then, the user will enter each value. You
should note that these values could be exam scores, stock prices,
fish weights, temperatures, etc. Our algorithm will work for any
application. Here is a Python program that will implement a solution
based on the algorithm above. The output for a sample run of the
program is also provided.
Chapter 7: Repetition | 87
A couple of observations from this program:
88 | Chapter 7: Repetition
while thing < 10:
print(thing)
7.3. How many lines will get output when the following Python
code is executed?
thing = 2
while thing > 10:
print(thing)
thing = thing + 1
7.4. How many lines will get output when the following Python
code is executed?
for num in range(3,8):
print(num)
7.5. How many lines will get output when the following Python
code is executed?
for num in range(5,17,3):
print(num)
Programming Projects:
7.1. Write a program that creates a table to display Fahrenheit-
to-Celsius conversions. Use the following formula to do the
conversions:
You should ask the user for start, end, and step values for Fahrenheit
temperatures. The program should print column headings and the
values printed should be displayed using 2 decimal places.
The sample interaction should look like this:
Chapter 7: Repetition | 89
90 | Chapter 7: Repetition
8. Chapter 8: User-defined
Functions
USER-DEFINED FUNCTIONS
Topics Covered:
• Functions
• Return values
• Parameters
• Arguments
Functions
Throughout the first seven chapters, we learned about many of
Python’s built-in functions, including print, input, and round.
Often, especially as our computer programs get longer and more
To write your own Python function, you use the word def (short
for define), followed by the FunctionName and
a ParameterList enclosed in parenthesis, ending with a colon.
Similar to an if statement or loop, the Action block of instructions
included in the function must be indented at the same level. The
final instruction in the function is an optional ReturnStatement.
def FunctionName (ParameterList):
Action
ReturnStatement
To get a better feel for how functions work, we will take a look
at several examples. In the first example, we define a function
Here is the interaction that takes place when the program is run,
and the user enters 9.35 as the hourly wage, and 27 as the weekly
hours worked.
Programming Projects:
8.1. Modify Programming Project 6.2 in the following ways:
Topics Covered:
• List basics
• Slicing a list
• Deleting from a list
• Adding to a list
• Processing a list
• List operators
List basics
A list is an ordered sequence of objects. You can use a list to store
multiple items using a single variable. The Python list has many
similarities to an array, which is provided by most programming
The variable school now stores five data items associated with a
university. Similar to a string, you can access individual elements
of the list by using an index, or subscript. In the example below,
we access the first element (using index 0) and the fourth element
(using index 3). When attempting to access the element using
index 5, Python indicates an error has occurred since the index is
out of range:
Adding to a List
There are multiple ways to add items to a list.
The append() method is a simple technique that just adds the
required argument to the end of a list. In our next example, we
use append to add the value 33 to the end of a five-item list
named things.
The insert() method has two arguments, the position in the list
to place the new item and the value to be inserted. In the second
example, we inserted the value “tiger” at position 2, which is actually
the third item in the list. When the new list is displayed, “tiger”
squeezes into position 2 and all of the items after it are pushed back
one slot.
A third way to add items to a list is to use the extend() method.
This function is similar to the append() method except the
argument to be passed is another list instead of a single data item.
In the example, we created a four-item list named birds and then
List Processing
The code below illustrates three more useful Python list methods.
The first one, sort, arranges the list items in ascending order.
The sort() method can also be applied on a list of strings.
The reverse() method does exactly what you might guess. It just
flips the order of the list. Finally, the clear() method will delete all of
the items from a list. You can see from the example below that a list
is empty when it displays as just two brackets [].
List Operators
Program output.
Often times, we like to use the key as a way to access data directly.
In the example below, we will create a dictionary named states that
stores the population of U.S. states from the year 2000 through
2019. This data was found at a web site called Kaggle, that has
thousand of freely accessible data sets that you can use for
programming projects. A small chunk of this comma-separated data
file is shown here:
Python program that reads CSV file and stores data to a dictionary.
Program output.
Topics Covered:
Here’s the new and improved version of our program for displaying
the contents of the “artists.txt” file:
The main construct in this program is a while loop that allows the
user to log as many runs as they wish. During each iteration of the
loop, the user will provide the four input values discussed above.
The average mile pace is then computed as illustrated in the test
case. Note that we needed to import the math module in order to
use the floor() method. An outputString is created to store the five
items that will be sent to the file along with the comma separators.
This string terminates with a newline so that each logged activity
will appear on its own line. Since that instruction was so long,
Python allows you to continue it on a second line by using the
backslash (\) character. When the user has no more activities to log,
the loop concludes and the close() method for the dataFile is called.
The full program is shown next:
In chapter 12, we will look at how you could create charts like the
one above using the Python Turtle graphics module. In chapter 13,
we examine how to turn that text-based interaction into a graphical
user interface (GUI) that you are used to using with everyday apps.
Finally, in chapter 14, we take a look at how to turn this app into a
web-based application.
Programming Projects:
10.1. A text file named “superbowl.txt” has a list that includes the
winner of every Super Bowl. The first few lines of the file look like
this:
Topics Covered:
• Random numbers
• Guess the number game
• Paper rock scissors game
Random Numbers
Topics Covered:
• Turtle graphics
Using turtle graphics is a fun way to hone your problem solving and
programming skills, as well as a writing code that can generate
graphics. It was part of the original Logo programming language
developed in 1967.
Importing the turtle module into your Python program allows you
to create simple drawings on the screen. The name turtle, or turtle
graphics, is a term in computing that means “using a relative cursor
to draw on a Cartesian plane”. The relative cursor is called the turtle.
The Logo programming language compared the drawing capabilities
• left
• forward
• goto
• write
• penup
• endfill
• dot
Programming Projects:
12.1. Using Turtle Graphics, write a program that asks the user to
type in the following inputs:
• Number of sides
• Length of each side
• Color of the sides
• The pen size
Topics Covered:
Suppose you wanted to build the GUI window shown below. The
window consists of three widgets. We will describe each of these
widgets, as well as how we can add the cool title at the top of the
window.
Listbox Widget
The listbox widget is used to display a list of items from which a
user can select any number of items. In the example below, we first
create a list colorList, associate a string variable colorString with it,
and then call the Listbox() constructor. We use the set() method to
assign a value to colorString. The function colorChange() retrieves
the selected item and we use that index to change color of the
window background.
Programming Projects:
13.1. Use the Python module tkinter to create the following
graphical user interface. Do not worry about functionality at this
point. You will add that in later. Be sure to modify your program so
that it generates a match (title, colors, spacing, etc.) to this window:
Topics Covered:
• HTML
• CSS
• Server-side scripting
Web pages are simple text (ASCII) files that are embedded with
An image named peeps.jpg was also referenced in the web page. The
HTML, CSS, and image files must all be located in the same folder
for the page to render correctly. You can view a web page, as shown
below, by opening it in your browser.
Before we take a look at the server-side script, let’s see how this new
step changes the sequence of events in the client/server sequence.
Now, the server has to send the form input to the Python script
(i.e., processform.py), execute the script, and finally send the script
output back to the client to be rendered by the web browser:
• Internet
• World Wide Web
• Web browser
• SFTP
• Web server
• HTML
• CSS