Instant download An Introduction to Programming and Computer Science with Python First Edition Clayton Cafiero pdf all chapter
Instant download An Introduction to Programming and Computer Science with Python First Edition Clayton Cafiero pdf all chapter
com
https://ebookmeta.com/product/an-introduction-to-
programming-and-computer-science-with-python-first-edition-
clayton-cafiero/
OR CLICK HERE
DOWLOAD NOW
https://ebookmeta.com/product/python-an-introduction-to-
programming-2nd-edition-jim-r-parker/
ebookmeta.com
https://ebookmeta.com/product/an-introduction-to-python-programming-
for-scientists-and-engineers-johnny-wei-bing-lin/
ebookmeta.com
https://ebookmeta.com/product/the-new-real-media-and-mimesis-in-japan-
from-stereographs-to-emoji-jonathan-e-abel/
ebookmeta.com
AD Stufish : Entertainment Architecture 1st Edition Ray
Winkler
https://ebookmeta.com/product/ad-stufish-entertainment-
architecture-1st-edition-ray-winkler/
ebookmeta.com
Perfect Fit Flirty Fitness 1st Edition M.K. Moore & Flirt
Club
https://ebookmeta.com/product/perfect-fit-flirty-fitness-1st-edition-
m-k-moore-flirt-club/
ebookmeta.com
https://ebookmeta.com/product/studies-on-plotinus-and-al-kindi-
variorum-collected-studies-1st-edition-peter-adamson/
ebookmeta.com
https://ebookmeta.com/product/the-american-construction-industry-its-
historical-evolution-and-potential-future-1st-edition-brian-bowen/
ebookmeta.com
Terrorism Criminal Law and Politics The Decline of the
Political Offence Exception to Extradition Transnational
Criminal Justice 1st Edition Julia Jansson
https://ebookmeta.com/product/terrorism-criminal-law-and-politics-the-
decline-of-the-political-offence-exception-to-extradition-
transnational-criminal-justice-1st-edition-julia-jansson/
ebookmeta.com
AN INTRODUCTION TO
PROGRAMMING AND COMPUTER SCIENCE
WITH PYTHON
CLAYTON CAFIERO
An Introduction to
Programming and Computer Science
with Python
Clayton Cafiero
The University of Vermont
This book is for free use under either the GNU Free Documentation License or
the Creative Commons Attribution-ShareAlike 3.0 United States License. Take
your pick.
• http://www.gnu.org/copyleft/fdl.html
• http://creativecommons.org/licenses/by-sa/3.0/us/
Book style has been adapted from the Memoir class for TEX, copyright © 2001–
2011 Peter R. Wilson, 2011–2022 Lars Madsen, and is thus excluded from the
above licence.
Images from Matplotlib.org in Chapter 15 are excluded from the license for
this material. They are subject to Matplotlib’s license at https://matplotlib.o
rg/stable/users/project/license.html. Photo of Edsger Dijkstra by Hamilton
Richards, University Texas at Austin, available under a Creative Commons CC
BY-SA 3.0 license: https://creativecommons.org/licenses/by-sa/3.0/.
No generative AI was used in writing this book.
Manuscript prepared by the author with Quarto, Pandoc, and XƎLATEX.
Illustrations, diagrams, and cover artwork by the author, except for the graph
in Chapter 17, Exercise 2, which is by Harry Sharman.
Version: 0.1.8b (beta)
ISBN: 979-8-9887092-0-6
Library of Congress Control Number: 2023912320
First edition
10 9 8 7 6 5 4 3 2
Printed in the United States of America
For the Bug and the Bull
Table of contents
Table of contents i
Preface v
Acknowledgements ix
1 Introduction 1
5 Functions 75
5.1 Introduction to functions . . . . . . . . . . . . . . . . . . 76
i
ii Table of contents
6 Style 97
6.1 The importance of style . . . . . . . . . . . . . . . . . . . 97
6.2 PEP 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
6.3 Whitespace . . . . . . . . . . . . . . . . . . . . . . . . . . 98
6.4 Names (identifiers) . . . . . . . . . . . . . . . . . . . . . . 100
6.5 Line length . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.6 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.7 Comments in code . . . . . . . . . . . . . . . . . . . . . . 102
6.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10 Sequences 183
10.1 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
10.2 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
10.3 Mutability and immutability . . . . . . . . . . . . . . . . 194
10.4 Subscripts are indices . . . . . . . . . . . . . . . . . . . . 198
10.5 Concatenating lists and tuples . . . . . . . . . . . . . . . 199
10.6 Copying lists . . . . . . . . . . . . . . . . . . . . . . . . . 200
10.7 Finding an element within a sequence . . . . . . . . . . . 201
10.8 Sequence unpacking . . . . . . . . . . . . . . . . . . . . . 203
10.9 Strings are sequences . . . . . . . . . . . . . . . . . . . . . 205
10.10 Sequences: a quick reference guide . . . . . . . . . . . . . 206
10.11 Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
10.12 Passing mutables to functions . . . . . . . . . . . . . . . . 210
10.13 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
10.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
16 Dictionaries 311
16.1 Introduction to dictionaries . . . . . . . . . . . . . . . . . 311
16.2 Iterating over dictionaries . . . . . . . . . . . . . . . . . . 316
16.3 Deleting dictionary keys . . . . . . . . . . . . . . . . . . . 318
16.4 Hashables . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
16.5 Counting letters in a string . . . . . . . . . . . . . . . . . 321
16.6 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
16.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
17 Graphs 325
17.1 Introduction to graphs . . . . . . . . . . . . . . . . . . . . 325
17.2 Searching a graph: breadth-first search . . . . . . . . . . . 327
17.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Appendices 333
A Glossary 333
This book has been written for use in University of Vermont’s CS1210
Introduction to Programming (formerly CS021). This is a semester long
course which covers much of the basics of programming, and an intro-
duction to some fundamental concepts in computer science. Not being
happy with any of the available textbooks, I endeavored to write my own.
Drafting began in August 2022, essentially writing a chapter a week over
the course of the semester, delivered to students via UVM’s learning
management system. The text was revised, edited, and expanded in the
following semester.
UVM’s CS1210 carries “QR” (quantitative reasoning) and “QD”
(quantitative and data literacy) designations. Accordingly, there’s some
mathematics included:
v
vi Preface
Contact
Clayton Cafiero
The University of Vermont
College of Engineering and Mathematical Sciences
Department of Computer Science
Innovation E309
82 University Place
Burlington, VT 05405-0125 (USA)
[email protected]
https://www.uvm.edu/~cbcafier
To the student
vii
Acknowledgements
ix
Chapter 1
Introduction
Computer science is a science of abstraction—creating
the right model for a problem and devising the appro-
priate mechanizable techniques to solve it.
–Alfred V. Aho
1
2 Introduction
Python interpreter. This chapter also introduces the two modes of using
Python. The interactive mode allows the user to interact with the Python
interpreter using the Python shell. Python statements and expressions
are entered one at a time, and the interpreter evaluates or executes the
code entered by the user. This is an essential tool for experimentation
and learning the details of various language features. Script mode allows
the user to write, save, and execute Python programs. This is convenient
since in this mode we can save our work, and run it multiple times
without having to type it again and again at the Python shell.
This chapter also includes a brief introduction to binary numbers and
binary arithmetic.
Functions
Functions are the single most important concept a beginning programmer
can acquire. Functional decomposition is a crucial requirement of writing
reliable, robust, correct code.
This chapter explains why we use functions, how functions are defined,
how functions are called, and how values are returned. We’ve tried to
keep this “non-technical” and so there’s no discussion of a call stack,
though there is discussion of scope.
Because beginning programmers often introduce side effects into func-
tions where they are undesirable or unnecessary, this chapter makes clear
the distinction between pure functions (those without side effects) and
impure functions (those with side effects, including mutating mutable
objects).
Because the math module is so widely used and includes many useful
functions, we introduce the math module in this chapter. In this way, we
also reinforce the idea of information hiding and good functional design.
Do we need to know how the math module implements its sqrt() function?
Of course not. Should we have to know how a function is implemented
3
in order to use it? Apart from knowing what constitutes a valid input
and what it returns as an output, no, we do not!
Style
Our goal here is to encourage the writing of idiomatic Python. Accord-
ingly, we address the high points of PEP 8—the de facto style guide for
Python—and provide examples of good and bad style.
Students don’t always understand how important style is for the read-
ability of one’s code. By following style guidelines we can reduce the
cognitive load that’s required to read code, thereby making it easier to
reason about and understand our code.
Branching
Branching is a programming language’s way of handling conditional ex-
ecution of code. In this chapter, we cover conditions (Boolean expres-
sions) which evaluate to a true or false (or a value which is “truthy”
or “falsey”—like true or like false). Python uses these conditions to de-
termine whether a block of code should be executed. In many cases we
have multiple branches—multiple paths of execution that might be taken.
These are implemented with if, elif (a portmanteau of “else if”), and
often else.
One common confusion that beginners face is understanding which
branch is executed in an if/elif/else structure, and hopefully the chapter
makes this clear.
Also covered are nested if statements, and two ways of visually rep-
resenting branching (each appropriate to different use cases)—decision
trees and flow charts.
Sequences
Sequences—lists, tuples, and strings—are presented in this chapter. It
makes sense to present these before presenting loops for two reasons.
First, sequences are iterable, and as such are used in for loops, and with-
out a clear understanding of what constitutes an iterable, understanding
such loops may present challenges. Second, we often do work within a
loop which might involve constructing or filtering a list of objects.
Common features of sequences—for example, they are all indexed,
support indexed reads, and are iterable—are highlighted throughout the
chapter.
As this chapter introduces our first mutable type, the Python list, we
present the concepts of mutability and immutability in this chapter.
Loops
Loops allow for repetitive work or calculation. In this chapter we present
the two kinds of loop supported by Python—while loops and for loops.
At this point, students have seen iterables (in the form of sequences)
and Boolean expressions, which are a necessary foundation for a proper
presentation of loops.
Also, this chapter introduces two new types—range and enumerate—
and their corresponding constructors. Presentation of range entails dis-
cussion of arithmetic sequences, and presentation of enumerate works
nicely with tuple unpacking (or more generally, sequence unpacking),
and so these are presented first in this chapter.
This chapter also provides a brief introduction to stacks and queues,
which are trivially implemented in Python using list as an underlying
data structure.
I’ve intentionally excluded treatment of comprehensions since begin-
ners have difficulty reading and writing comprehensions without a prior,
solid foundation in for loops.
agers were introduced with Python 2.5 in 2006, and are a much preferred
idiom (as compared to using try/finally). Accordingly, all file I/O demon-
strations make use of context managers created with the Python keyword
with.
Because so much data is in CSV format (or can be exported to this
format easily), we introduce the csv module in this chapter. Using the
csv module reduces some of the complexity we face when reading data
from a file, since we don’t have to parse it ourselves.
Exception handling
In this chapter, we present simple exception handling (using try/except,
but not finally), and explain that some exceptions should not be han-
dled since in doing so, we can hide programming defects which should
be corrected. We also demonstrate the use of exception handling in in-
put validation. When you reach this chapter, you’ll already have seen
while loops for input validation, so the addition of exception handling
represents only an incremental increase in complexity in this context.
Dictionaries
Dictionaries are the last new type we present in the text. Dictionaries
store information using a key/value model—we look up values in a dic-
tionary by their keys. Like sequences, dictionaries are iterable, but since
they have keys rather than indices, this works a little differently. We’ll
see three different ways to iterate over a dictionary.
We’ll also learn about hashability in the context of dictionary keys.
Graphs
Since graphs are so commonplace in computer science, it seems appro-
priate to include a basic introduction to graphs in this text. Plus, graphs
are really fun!
A graph is a collection of vertices (also called nodes) and edges, which
connect the vertices of the graph. The concrete example of a highway map
is used, and an algorithm for breadth-first search (BFS) is demonstrated.
Since queues were introduced in chapter 11, the conceptual leap here—
using a queue in the BFS algorithm—shouldn’t be too great.
6 Introduction
print("Hello, World!")
>>> 1 + 2
3
>>> import math
>>> math.sqrt(36)
6
2
Except in the case of doctests, which are not presented in this text.
7
Other conventions
When referring to functions, whether built-in, from some imported mod-
ule, or otherwise, without any other context or specific problem instance,
we write function identifiers along with parentheses (as a visual indica-
tor that we’re speaking of a function) but without formal parameters.
Example: “The range() function accepts one, two, or three arguments.”
This should not be read as suggesting that range() takes no arguments.
if __name__ == '__main__':
# the rest of your code here
Origin of Python
Python has been around a long time, with the first release appearing
in 1991 (four years before Java). It was invented by Guido van Rossum,
who is now officially Python’s benevolent dictator for life (BDFL).
8 Introduction
Python gets its name from the British comedy troupe Monty Python’s
Flying Circus (Guido is a fan).
Nowadays, Python is one of the most widely used programming lan-
guages on the planet and is supported by an immense ecosystem and
thriving community. See: https://python.org/ for more.
Python version
As this book is written, the current version of Python is 3.11.4. However,
no new language features introduced since version 3.6 are presented in
this book (as most are not appropriate or even useful for beginners).
This book does cover f-strings, which were introduced in version 3.6.
Accordingly, if you have Python version 3.6–3.11, you should be able to
follow along with all code samples and exercises.
Pros
• Definitive and up-to-date
• Documentation for different versions clearly specified
• Thorough and accurate
• Includes references for all standard libraries
• Available in multiple languages
• Includes a comprehensive tutorial for Python beginners
• Coding examples (where given) conform to good Python style (PEP
8)
Cons
• Can be lengthy or technical—not always ideal for beginners
• Don’t always appear at top of search engine results.
python.org
Official Python documentation, tutorials, and other resources are hosted
at https://python.org.
9
• Documentation: https://docs.python.org/3/
• Tutorial: https://docs.python.org/3/tutorial/
• Beginner’s Guide: https://wiki.python.org/moin/BeginnersGuide
Á Warning
Our objective for this chapter is to lay the foundations for the rest of
the course. If you’ve done any programming before, some of this may
seem familiar, but read carefully nonetheless. If you haven’t done any
programming before that’s OK.
Learning objectives
• You will learn how to interact with the Python interpreter using
the Python shell.
• You will learn the difference between interactive mode (in the shell)
and script mode (writing, saving, and running programs).
• You will learn a little about computers, how they are structured,
and that they use binary code.
• You will understand why we wish to write code in something other
than just zeros and ones, and you’ll learn a little about how Python
translates high-level code (written by you, the programmer) into
binary instructions that a computer can execute.
• You will write, save, and run your first Python program—an or-
dered collection of statements and expressions.
Terms introduced
• binary code
• bytecode
• compilation vs interpretation
• compiler
• console
• integrated development environment (IDE)
• interactive mode
• low-level vs high-level programming language
• Python interpreter / shell
• read-evaluate-print loop (REPL)
• semantics
• script mode
11
12 Programming and the Python Shell
• syntax
• terminal
This is unintelligible. It’s bad enough to try to read it, and it would be
even worse if we had to write our computer programs in this fashion.
Computers don’t speak human language, and humans don’t speak
computer language. That’s a problem. The solution is programming lan-
guages.
Programming languages allow us, as humans, to write instructions
in a form we can understand and reason about, and then have these
instructions converted into a form that a computer can read and execute.
There is a tremendous variety of programming languages. Some lan-
guages are low-level, like assembly language, where there’s roughly a
one-to-one correspondence between machine instructions and assembly
language instructions. Here’s a “Hello World!” program in assembly lan-
guage (for ARM64 architecture):1
.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93
.text
.global _start
_start:
stp x29, x30, [sp, -16]!
mov x0, #STDOUT
ldr x1, =msg
mov x2, 13
1
Assembly language code sample from Rosetta Code: https://www.rosettacode.
org/wiki/Hello_world
Why learn a programming language? 13
Now, while this is a lot better than a string of zeros and ones, it’s not
so easy to read, write, and reason about code in assembly language.
Fortunately, we have high-level languages. Here’s the same program
in C++:
#include <iostream>
int main () {
std::cout << "Hello World!" << std::endl;
}
print('Hello World!')
print('Hello World!')
You may run this program from the terminal (command prompt), thus:
$ python hello_world.py
Hello World!
When we run this program, Python first reads the source code, then
produces the intermediate bytecode, then executes each instruction in
the bytecode.