(eBook PDF) Building Python Programs 1st Edition instant download
(eBook PDF) Building Python Programs 1st Edition instant download
download
https://ebookluna.com/product/ebook-pdf-building-python-
programs-1st-edition/
https://ebookluna.com/product/ebook-pdf-fundamentals-of-python-first-
programs-2nd-edition/
https://ebookluna.com/download/fundamentals-of-python-first-programs-2nd-
edition-ebook-pdf/
(eBook PDF) Building Java Programs: A Back to Basics Approach 5th Edition
https://ebookluna.com/product/ebook-pdf-building-java-programs-a-back-to-
basics-approach-5th-edition/
Building Java Programs: A Back to Basics Approach 4th Edition (eBook PDF)
https://ebookluna.com/product/building-java-programs-a-back-to-basics-
approach-4th-edition-ebook-pdf/
Building Java Programs: A Back to Basics Approach 4th Edition Stuart Reges
- eBook PDF
https://ebookluna.com/download/building-java-programs-a-back-to-basics-
approach-ebook-pdf/
Building Java Programs - A Back to Basics Approach 5th Edition Stuart Reges
- eBook PDF
https://ebookluna.com/download/building-java-programs-a-back-to-basics-
approach-ebook-pdf-2/
https://ebookluna.com/download/progress-in-heterocyclic-chemistry-ebook-
pdf/
https://ebookluna.com/download/python-distilled-ebook-pdf/
(eBook PDF) Building Java Programs: A Back to Basics Approach 4th Edition
by Stuart Reges
https://ebookluna.com/product/ebook-pdf-building-java-programs-a-back-to-
basics-approach-4th-edition-by-stuart-reges/
Preface
The Python programming language has become enormously popular in recent years.
Many people are impressed with how quickly you can learn Python’s simple and intui-
tive syntax and that has led many users to create popular libraries. Python was designed
by Guido van Rossum who has been affectionaly dubbed “Benevolent Dictator For Life
(BDFL)” by the Python community. He has said that he chose the name Python because
he was “in a slightly irreverent mood” and that he is “a big fan of Monty Python’s
Flying Circus” (a British comedy show). Who wouldn’t want to learn a programming
language named after a group of comedians?
Our new Building Python Programs text is designed for use in a first course in com-
puter science. We have class-tested it with hundreds of undergraduates at the University
of Arizona, most of whom were not computer science majors. This textbook is based
on our previous text, Building Java Programs, now in its fourth edition. The Java text
has proven effective in our class testing with thousands of students including our own
at the University of Washington since 2007.
Introductory computer science courses have a long history at many universities
of being “killer” courses with high failure rates. But as Douglas Adams says in The
Hitchhiker’s Guide to the Galaxy, “Don’t panic.” Students can master this material if
they can learn it gradually.
Python has many attributes that make it an appealing language for a first computer
science course. It has a simple and concise yet powerful syntax that makes it pleasant
to learn and great for writing many common programs. A student can write their first
Python program with only a single line of code, as opposed to several lines in most other
languages such as Java or C++. Python includes a built-in interpreter and read-evaluate-
print loop (REPL) for quickly running and testing code, encouraging students to test and
explore the language. Python also offers a rich set of libraries that students can use for
graphics, animation, math, scientific computing, games, and much more. This text has
been built from the start for Python 3, the most modern version of the language as of this
writing, and it embraces the modern features and idioms of that version of the language.
Our teaching materials are based on a “back to basics” approach that focuses on
procedural programming and program decomposition. This is also called the “objects
later” approach, as opposed to the “objects early” approach taught in some schools. We
know from years of experience that a broad range of scientists, engineers, and others
can learn how to program in a procedural manner. Once we have built a solid founda-
tion of procedural techniques, we turn to object-oriented programming. By the end of
the text, students will have learned about both styles of programming.
iii
Brief Contents
xi
Contents
Arithmetic Operators 62
Precedence 66
Mixing and Converting Types 69
2.2 Variables 70
A Program with Variables 74
Increment/Decrement Operators 79
Printing Multiple Values 80
2.3 The for Loop 83
Using a Loop Variable 87
Details about Ranges 90
String Multiplication and Printing Partial Lines 94
Nested for Loops 98
2.4 Managing Complexity 101
Scope 101
Pseudocode 103
Constants 108
2.5 Case Study: Hourglass Figure 111
Problem Decomposition and Pseudocode 112
Initial Structured Version 114
Adding a Constant 115
Images 188
Procedural Decomposition with Graphics 189
3.5 Case Study: Projectile Trajectory 191
Unstructured Solution 195
Structured Solution 196
Graphical Version 199
Introduction
1.1 Basic Computing Concepts
■■ Why Programming?
This chapter begins with a review of some basic terminology about comput- ■■ Hardware and Software
ers and computer programming. Many of these concepts will come up in later ■■ The Digital Realm
chapters, so it will be useful to review them before we start delving into the
■■ The Process of Programming
■■ Why Python?
details of how to program in Python. ■■ The Python Programming
Environment
We will begin our exploration of Python by looking at simple programs
1.2 And Now: Python
that produce text output to a console window. This discussion will allow us
■■ Printing Output
to explore many elements that are common to all Python programs, while ■■ String Literals (Strings)
working with programs that are fairly simple in structure. ■■ Escape Sequences
■■ Printing a Complex Figure
After we have reviewed the basic elements of Python programs, we will ■■ Comments, Whitespace, and
explore the technique of procedural decomposition by learning how to break Readability
up a Python program into several functions. Using this technique, we can 1.3 Program Errors
break up complex tasks into smaller subtasks that are easier to manage and ■■ Syntax Errors
■■ Logic Errors (Bugs)
we can avoid redundancy in our program solutions.
1.4 Procedural Decomposition
■■ Functions
■■ Flow of Control
■■ Identifiers and Keywords
■■ Functions That Call Other
Functions
■■ An Example Runtime Error
Chapter Summary
Self-Check Problems
Exercises
Programming Projects
1
2 Chapter 1 Introduction to Python Programming
Why Programming?
At most universities, the first course in computer science is a programming course.
Many computer scientists are bothered by this because it leaves people with the impres-
sion that computer science is programming. While it is true that many trained computer
scientists spend time programming, there is a lot more to the discipline. So why do we
study programming first?
A Stanford computer scientist named Don Knuth answers this question by saying
that the common thread for most computer scientists is that we all in some way work
with algorithms.
Algorithm
A step-by-step description of how to accomplish a task.
It has often been said that a person does not really understand something until
after teaching it to someone else. Actually a person does not really understand
something until after teaching it to a computer, i.e., expressing it as an
algorithm.1
1
Knuth, Don. Selected Papers on Computer Science. Stanford. CA: Center for the Study of Language and
Information, 1996.
1.1 Basic Computing Concepts 3
Program
A list of instructions to be carried out by a computer.
One key feature that differentiates a computer from a simpler machine like a calculator
is its versatility. The same computer can perform many different tasks (playing games,
computing income taxes, connecting to other computers around the world), depending
on what program it is running at a given moment. A computer can run not only the pro-
grams that exist on it currently, but also new programs that haven’t even been written yet.
The physical components that make up a computer are collectively called hardware.
One of the most important pieces of hardware is the central processing unit, or CPU.
The CPU is the “brain” of the computer: It is what executes the instructions. Also
important is the computer’s memory (often called random access memory, or RAM,
because the computer can access any part of that memory at any time). The computer
uses its memory to store programs that are being executed, along with their data. RAM
is limited in size and does not retain its contents when the computer is turned off.
Therefore, computers generally also use a hard disk as a larger permanent storage area.
Computer programs are collectively called software. The primary piece of soft-
ware running on a computer is its operating system. An operating system provides an
environment in which many programs may be run at the same time; it also provides
4 Chapter 1 Introduction to Python Programming
a bridge among those programs, the hardware, and the user (the person using the
computer). The programs that run inside the operating system are often called
applications or apps.
When the user selects a program for the operating system to run (e.g., by double-
clicking the program’s icon on the desktop), several things happen: The instructions for
that program are loaded into the computer’s memory from the hard disk, the operating
system allocates memory for that program to use, and the instructions to run the pro-
gram are fed from memory to the CPU and executed sequentially.
Digital
Based on numbers that increase in discrete increments, such as the integers
0, 1, 2, 3, etc.
Binary Number
A number composed of just 0s and 1s, also known as a base-2 number.
Humans generally work with decimal or base-10 numbers, which match our physiol-
ogy (10 fingers and 10 toes). However, when we were designing the first computers,
we wanted systems that would be easy to create and very reliable. It turned out to be
simpler to build these systems on top of binary phenomena (e.g., a circuit being open or
closed) rather than having 10 different states that would have to be distinguished from
one another (e.g., 10 different voltage levels).
From a mathematical point of view, you can store things just as easily using binary
numbers as you can using base-10 numbers. But since it is easier to construct a physical
device that uses binary numbers, that’s what computers use.
This does mean, however, that people who aren’t used to computers find their
conventions unfamiliar. As a result, it is worth spending a little time reviewing how
1.1 Basic Computing Concepts 5
binary numbers work. To count with binary numbers, as with base-10 numbers,
you start with 0 and count up, but you run out of digits much faster. So, counting in
binary, you say:
0
1
And already you’ve run out of digits. This is like reaching 9 when you count in
base-10. After you run out of digits, you carry over to the next digit. So, the next two
binary numbers are:
10
11
And again, you’ve run out of digits. This is like reaching 99 in base-10. Again, you
carry over to the next digit to form the three-digit number 100. In binary, whenever you
see a series of ones, such as 111111, you know you’re just one away from the digits
all flipping to 0s with a 1 added in front, the same way that, in base-10, when you see
a number like 999999, you know that you are one away from all those digits turning
to 0s with a 1 added in front. Table 1.1 shows how to count up to the base-10 number
8 using binary.
We can make several useful observations about binary numbers. Notice in the table that
the binary numbers 1, 10, 100, and 1000 are all perfect powers of 2 (20, 21, 22, 23). In the
same way that in base-10 we talk about a ones digit, tens digit, hundreds digit, and so on,
we can think in binary of a ones digit, twos digit, fours digit, eights digit, sixteens digit,
and so on.
Computer scientists quickly found themselves needing to refer to the sizes of dif-
ferent binary quantities, so they invented the term bit to refer to a single binary digit
and the term byte to refer to 8 bits. (The less commonly used term “nibble” refers
to 4 bits, or half a byte.) To talk about large amounts of memory, they invented the
terms kilobytes (KB), megabytes (MB), gigabytes (GB), and so on. Many people think
that these correspond to the metric system, where “kilo” means 1000, but that is only
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
6 Chapter 1 Introduction to Python Programming
approximately true. We use the fact that 210 is approximately equal to 1000 (it actually
equals 1024). Table 1.2 shows some common units of memory storage.
Program Execution
The act of carrying out the instructions contained in a program.
The process of execution is often called running. This term can also be used as a verb
(“When my program runs it does something strange”) or as a noun (“The last run of
my program produced these results”).
A computer program is stored internally as a series of binary numbers known as the
machine language of the computer. In the early days, programmers entered numbers like
these directly into the computer. Obviously, this is a tedious and confusing way to pro-
gram a computer, and we have invented all sorts of mechanisms to simplify this process.
Modern programmers write in what are known as high-level programming languages,
such as Python. Such programs cannot be run directly on a computer: They first have to
be translated into a form that can be executed. Translating a program from a language such
as Python into executable binary instructions can be done two ways: all at once (called
compiling) or incrementally (called interpreting the program). Python is an interpreted
language, which means that after you type and save your program, you directly execute it
without any other steps. Each command written in your program is executed in sequence
by a special program called an interpreter. When you download and install Python on your
computer, the Python interpreter is installed for you so that you can run Python programs.
Interpreter
A program that dynamically reads, translates, and executes instructions from
a computer program.
1.1 Basic Computing Concepts 7
Many other languages such as Java and C are compiled languages. Compiled lan-
guages require you to use a special program known as a compiler to explicitly trans-
late the entire program before it runs. A compiler often translates a program directly
into machine language and creates a program file that can be executed directly on the
computer, known as an executable. Interpreted languages like Python do not usually
produce a separate executable program file.
Compiler
A program that translates an entire computer program written in one language
into an equivalent program in another language (often, but not always, trans-
lating from a high-level language into machine language).
You can write Python code in two ways. The first way is called interactive mode, also
called the Python shell, where you type individual Python commands and immediately
watch them execute and see their results. Interactive mode is useful for trying out com-
mands quickly to experiment and learn more about them. But the commands you type
in interactive mode are not saved anywhere and will be gone when you exit your Python
editor or shut off your computer. The second way is normal mode, where you type a pro-
gram that can consist of many Python commands, save it to a file, and then execute the
program to run all of the commands in sequence. Normal mode is the way to write com-
plete programs that will persist on your computer so they can be executed many times.
Why Python?
Python was created as a hobby project by a Dutch programmer named Guido van
Rossum. The first public versions of Python were released in 1989. As of this writing
the current major version of the language is Python 3, which is the version taught in
this text. The language is named after the classic comedy TV show Monty Python’s
Flying Circus, of which van Rossum was a big fan. Python currently ranks fifth on the
TIOBE index of programming language popularity.
The language’s official web site, python.org, says, “Python is a programming lan-
guage that lets you work quickly and integrate systems more effectively” and that it
is “easy to learn and use.” Python has a plain and simple structure that allows you to
write basic programs more quickly and with less conceptual overhead than many other
popular languages.
Python also includes a large amount of prewritten software that programmers can
utilize to enhance their programs. Such off-the-shelf software components are often
called libraries. For example, if you wish to write a program that connects to a site on
the Internet, Python contains a library to simplify the connection for you. Python con-
tains libraries to draw graphical user interfaces (GUIs), retrieve data from databases,
create games, and perform complex scientific and mathematical computations, among
many other things. The richness of Python libraries has been an important factor in the
rise of Python as a popular language.
8 Chapter 1 Introduction to Python Programming
Library
A collection of preexisting code that provides solutions to common program-
ming problems.
Another reason to use Python is that it has a vibrant programmer community. Extensive
online documentation and tutorials are available to help programmers learn new skills.
The Python official web site contains detailed descriptions of the language’s features,
and many other web sites have written documentation and tutorials for the language.
Python is platform independent; unlike programs written in some other languages,
the same Python program can be executed on many different operating systems, such
as Windows, Mac OS X, and Linux.
Python is used extensively for both research and business applications, which means
that a large number of programming jobs exist in the marketplace today for skilled Python
programmers. Many companies and organizations such as Google, Facebook, Yahoo,
IBM, Quora, and NASA use Python as part of their code base. A sample Google search
for the phrase “Python jobs” returned around 2,000,000 results at the time of this writing.
Try typing the following one-line program into your Python editor:
print("Hello, world!")
Don’t worry about the details of this program right now. We will explore those in the
next section.
Once you have created your program file, move to step 2 and save it. The basic unit
of storage on most computers is a file. Every file has a name. A file name ends with an
extension, which is the part of a file’s name that follows the period. A file’s extension
indicates the type of data contained in the file. For example, files with the extension
.txt are text files, and files with the extension .mp3 are MP3 audio files.
By convention, the Python program files that we will write in this text will use the
extension .py. Python programs can use other extensions, but .py is expected and is
most commonly used.
Discovering Diverse Content Through
Random Scribd Documents
saada oikeutta. Mutta älkää polisia ottako mukaanne. Jos sen teette,
on kaikki hukassa. Tuntematon ystävänne'. No tämäpä on todella
pieni salaseikkailu! Mitä aiotte tehdä, miss Morstan?"
"Ne ovat minulla täällä." vastasi hän ottaen esiin puolen tusinaa
paperilappuja.
Holmes hymyili.
Kolmas luku.
Etsimismatkalla.
Kello oli puoli kuusi, ennenkuin Holmes tuli kotiin. Hän oli iloinen,
innokas ja loistavalla tuulella, — mielellä, joka hänessä vaihteli
synkimmän alakuloisuuden puuskien kanssa.
"Majoori Sholto oli isän hyvä ystävä," sanoi hän. "Hänen kirjeensä
olivat täynnä viittauksia majooriin. Hän ja isä johtivat sotajoukkoja
Andamansaarilla, joten he paljon joutuivat olemaan yhdessä. Kesken
kaiken — löysimme erään eriskummallisen paperin isän tavarain
seassa, jota kukaan ei voinut selittää. En luule sen olevan mistään
arvosta, mutta ajattelin että ehkä tahtoisitte katsoa sitä, ja
sentähden otin sen mukaani. Tässä se on."
Oli syyskuu eikä keila ollut vielä seitsemää, mutta päivä oli ollut
pilvinen, ja paksuna sumuna satoivat pilvet suuren kaupungin
likaisille kaduille. Lyhdyt "the Strand'lla" näyttivät ainoastaan
himmeiltä valopilkuilta, joista levisi heikosti loistava valo kosteille
kivikäytäville. Keltainen valo myymälän ikkunasta tunki raskaaseen,
kosteaan ilmaan ja heitti himmeitä säteitään suorasti poikki kadun,
joka oli täynnä ihmisiä. Minusta oli tuossa jotakin kauheata ja
aavemaista, tuossa loppumattomassa kulussa ihmisnaamoja, jotka
liukuivat ohitse — surullisia ja iloisia, synkkiä ja vilkkaita naamoja.
Ihmiskunnan tavoin kokonaisuudessaan kulkivat ne pimeydestä
valoon ja taas valosta pimeyteen takaisin. Minuun ei helposti mikään
vaikuta, mutta synkkä, pilvinen ilta yhdessä harvinaisen asian
kanssa, jolla olimme, teki minut hermoheikoksi ja alakuloiseksi. Minä
voin miss Morstanin käytöksestä nähdä, että hänkin kärsi samasta
tunteesta. Ainoaltaan Holmesiin ei vaikuttanut näin pikkumaiset
seikat. Hänellä oli avoin muistikirjansa polvellaan ja siihen hän
merkitsi vähän väliä numeroita ja muistiinpanoja pienen
taskulyhtynsä valossa.
Neljäs luku.
"Hyvä on, hyvä on," sanoi Sholto. "Saanko luvan tarjota teille lasin
Chiantia, miss Morstan? Tahi Tokayeria? Muita viinejä en käytä.
Saanko avata pullon? En? No, sitte toivon, ett'ei teillä ole mitään
tupakansavua vastaan, tuota itämaalaisen tupakan palsaminlaista
tuoksua vastaan. Minä olen vähän hermoheikko, ja minun hookah'ini
on arvaamaton rauhoittamaan."
"Isäni oli, kuten ehkä olette arvanneet, majoori John Sholto, ent.
upseeri intialaisessa armeijassa. Hän otti eron noin yksitoista vuotta
sitte ja asettui Pondicherry Lodgeen Yliseen Norwoodiin. Häntä oli
onni seurannut Intiassa ja hän toi mukanaan suurenlaisen pääoman,
suuren kokoelman kallisarvoisia eriskummallisuuksia ja joukon
maassasyntyneitä palvelijoita. Näillä osti hän nyt itselleen talon ja eli
siellä suuressa komeudessa. Kaksoisveljeni Bartholomeus ja minä
olimme ainoat lapset.
"Alussa vuotta 1882 sai isäni Intiasta kirjeen, joka vaikutti hänessä
äkkinäistä pelästystä. Hän milt'ei pyörtyi aamiaispöydässä
avatessaan sitä, ja sen päivän jälkeen ei hän enää koskaan
parantunut. Mitä kirjeessä oli, emme milloinkaan saaneet tietää,
mutta hän piti sitä vähän vinossa, joten minä näin että se oli hyvin
lyhyt ja kirjoitettu hyvin söhrityllä käsialalla. Vuosikausia oli hän
sairastanut, mutta nyt hänen tilansa äkkiä huononi, ja huhtikuun
lopulla saimme kuulla, ett'ei mitään toivoa enää ollut, ja että hän
tahtoi puhutella meitä viimeisen kerran.
"'Tahdon kertoa teille, miten mr Morstan kuoli', jatkoi hän. 'Hän oli
vuosikausia kärsinyt sydänviasta, mutta salasi sen kaikilta.
Ainoastaan minä tiesin sen. Olomme-aikana Intiassa tulimme, minä
ja hän harvinaisten asianhaarain kautta omistamaan suuren aarteen.
Minä kuljetin sen mukanani Englantiin ja samana iltana kuin Morstan
saapui tuli hän suoraan tänne vaatimaan osuuttaan. Hän tuli käyden
asemalta ja vanha uskollinen palvelijani Lal Chowdar, joka nyt on
kuollut, päästi hänet sisään. Morstan ja minä olimme eri mieltä, mitä
koski aarteen jakamista ja meidän välillämme syntyi kiivas
sananvaihto. Morstan oli syössyt tuolilta raivoissaan, ja yht'äkkiä
painoi hän kädellään toista kylkeään, kasvonsa muuttuivat
tuhanharmaiksi, ja hän kaatui taapäin satuttaen päänsä arkun
syrjään, joka sisälsi aarteen. Kumartuessani hänen ylitsensä näin
kauhukseni, että hän oli kuollut.'
Viides luku.
Hän kohotti lyhtyä ja käsi vapisi niin että valo pyöri liehuvissa
piireissä ympärillämme. Miss Morstan tarttui minua käsivarresta, ja
seisoimme kaikki sykkivin sydämmin ja tarkasti kuunnellen.
Suuresta, synkästä rakennuksesta kuului yön hiljaisuudessa
surullisinta ääntä, mitä voi ajatella, — pelästyneen naisen
sydäntäsärkevää, keskeytettyä valitusta.
"Ah, mr Thaddeus, olen niin iloinen, että tulitte, sir! Olen niin kovin
iloinen että tulitte, mr Thaddeus!"
"Nyt ovat asiat hullusti! Voi Bartholomeusta!" huusi hän. "Olen niin
peloissani! Hermoni eivät tätä kestä!"
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookluna.com