Python Programming Exercises Gently Explained Al Sweigart pdf download
Python Programming Exercises Gently Explained Al Sweigart pdf download
Sweigart download
https://ebookbell.com/product/python-programming-exercises-
gently-explained-al-sweigart-49467034
https://ebookbell.com/product/python-programming-for-beginners-crash-
course-with-handson-exercises-including-numpy-pandas-and-matplotlib-
ibnul-jaif-farabi-47378174
https://ebookbell.com/product/python-programming-mastery-a-
comprehensive-beginners-journey-through-practical-exercises-chloe-
annable-57498174
https://ebookbell.com/product/python-programming-for-beginners-python-
mastery-in-7-days-topsecret-coding-tips-with-handson-exercises-for-
your-dream-job-1st-edition-oswald-thornton-55556426
Python Programming For Beginners 2 Books In 1 The Ultimate Stepbystep
Guide To Learn Python Programming Quickly With Practical Exercises
Mark Reed
https://ebookbell.com/product/python-programming-for-
beginners-2-books-in-1-the-ultimate-stepbystep-guide-to-learn-python-
programming-quickly-with-practical-exercises-mark-reed-43835132
https://ebookbell.com/product/python-programming-for-beginners-the-
definitive-guide-with-handson-exercises-and-secret-coding-tips-
maxwell-ernstrom-55556946
https://ebookbell.com/product/python-programming-for-beginners-from-
basics-to-ai-integrations-5minute-illustrated-tutorials-coding-hacks-
handson-exercises-case-studies-to-master-python-in-7-days-and-get-
paid-more-prince-54975116
https://ebookbell.com/product/python-programming-bible-3-in-1-the-
complete-crash-course-to-learn-and-explore-python-beyond-the-basics-
including-examples-and-practical-exercises-to-master-python-from-
beginners-to-pro-james-p-meyers-56059682
https://ebookbell.com/product/python-programming-the-ultimate-
beginners-guide-to-python-language-fundamentals-a-crash-course-with-
stepbystep-exercises-john-russel-53747934
PYTHON
PROGRAMMING
EXERCISES,
GENTLY EXPLAINED
AL SWEIGART
AUTHOR OF AUTOMATE THE BORING STUFF WITH PYTHON
INVENTWITHPYTHON.COM
ISBN-13: 979-8-3553-8768-6
For information about this book and its content, please contact
[email protected].
First printing.
The information in this book is distributed on an "As Is" basis, without warranty.
While every precaution has been taken in the preparation of this work, the
author shall not have any liability for any loss or damage caused or alleged to be
caused directly or indirectly by the information contained in it.
―How can I get better at programming?‖ I see this common question often from those who have
started their programming journey. Of course, there are plenty of Python programming tutorials for
total beginners. However, these tutorials can carry the reader so far. After finishing these lessons,
readers often find their skills more than capable for yet another ―Hello, world!‖ tutorial but not
advanced enough to begin writing their own programs. They find themselves in the so-called ―tutorial
hell.‖ They learn the basic syntax of a programming language, but wonder where to begin when it
comes to applying them to their own programs.
Programming is like any other skill: it gets better with practice. I’ve chosen the exercises in this
book because they are short and straightforward. Each exercise involves only a handful of
programming concepts and you can solve them in a single session at the computer. If you’ve been
intimidated by ―competitive programming‖ or ―hacker challenge‖ websites, you’ll find these to be an
instructive and gentler way to level up your coding skills.
When I wrote Automate the Boring Stuff with Python, I wanted to teach programming to as many
non-programmers as possible. So, I released that book (and all of my other programming books)
under a Creative Commons license so they could be downloaded and shared for free from my website
https://inventwithpython.com. You can pay for a physical print book but it’s important to me to lower all
barriers to access, so the books are available online for free. I’ll cite some of these books in the
Further Reading section of the exercises in this book.
Prerequisites
While this isn’t a book to teach programming to complete beginners, you don’t need to be a
programming expert before tackling the challenges here. Any beginner’s resource, such as one of my
free books, Automate the Boring Stuff with Python or Invent Your Own Computer Games with Python, is more
1
Python Programming Exercises, Gently Explained
than enough to prepare you for these exercises. You can find these books for free at
https://inventwithpython.com. I also recommend Python Crash Course by Eric Matthes as an excellent book
for people with no programming experience. These books are published by No Starch Press, which
has an extensive library of high-quality Python books at https://nostarch.com/catalog/python.
To solve the exercises in this book, you should already know, or at least be familiar with, the
following Python programming concepts:
Downloading and installing the Python interpreter
Entering Python code into the interactive shell and into .py source code files
Storing values in variables with the = assignment operator
Knowing the difference between data types such as integers, strings, and floats
Math, comparison, and Boolean operators such as +, <=, and not.
How Python evaluates expressions such as (2 * 3) + 4 or 'Sun' + 'day'
Getting and displaying text with the input() and print() functions
Working with strings and string methods such as upper() or startswith()
Using if, elif, and else flow control statements
Using for loops and while loops, along with break and continue statements
Defining your own functions with parameters and returning values
Using data structures such as lists, tuples, and dictionaries
Importing modules such as math or random to use their functions
You don’t need a mastery of classes and object-oriented programming. You don’t need to know
advanced concepts such as machine learning or data science. But if you’d like to eventually build your
skills to advanced topics like these, this book can help you start along that path.
Even if you’ve moved past the beginner stage, this book can help you assess your programming
ability. By the time you’re ready to start applying to junior software developer positions, you should be
able to solve all of the exercises in this book easily.
2
Python Programming Exercises, Gently Explained
Special Cases and Gotchas – Describes common mistakes or surprising ―gotchas‖ you
may encounter when writing code for the solution. Some exercises have special cases that
your solution will need to address.
Solution Template – A copy of my own solution for the exercise, with selected parts
replaced by blanks for you to fill in. Your solution can still be correct if it doesn’t match
mine. But if you’re having trouble knowing where to start with your program, these
templates provide some but not all of the solution code.
Many solution programs to the exercises in this book are only a few lines of code long, and none
of them are longer than 50 lines. If you find yourself writing several hundred lines of code, you’re
probably overthinking the solution and should probably read the Exercise Description section
again.
Each exercise has several assert statements that detail the expected results from your solution.
In Python, assert statements are the assert keyword followed by a condition. They stop the
program with an AssertionError if their condition is False. They are a basic sanity check and,
for this book, tell you the expected behavior of your solution. For example, Exercise #3, ―Odd &
Even‖ has assert isOdd(9999) == True, which tells you that the correct solution involves the
isOdd() function returning True when passed an argument of 9999. Examine all of the assert
statements for an exercise before writing your solution program.
Some exercises don’t have assert statements, but rather show you the output that your
solution should produce. You can compare this output to your solution’s output to verify that your
solution is correct.
I provide complete solutions in Appendix A. But there are many ways to solve any given
programming problem. You don’t need to produce an identical copy of my solutions; it just needs to
pass the assert statements. I wrote my solutions to be conceptually simple and easy for the
intended audience of this book to understand. They produce correct results but aren’t necessarily the
fastest or most efficient solutions. As you get more experience programming, you can revisit the
exercises in this book and attempt to write high-performance solutions to them.
3
Python Programming Exercises, Gently Explained
Most of the solutions involve writing functions that return values based on the arguments passed
to the function call. In these cases, you can write your code assuming that the arguments are always of
the expected data type. So for example, if your function expects an integer, it will have to handle
arguments like 42, 0, or -3 but doesn’t have to handle arguments like 3.14 or 'hello'.
Keep in mind that there is a difference between a parameter and an argument. When we define a
function such as Exercise #3’s def isOdd(number):, the local variable number is a parameter.
When we call this function with isOdd(42), the integer 42 is an argument. The argument is passed to
the function and assigned as the value to the parameter. It’s easy to use ―parameter‖ and ―argument‖
interchangeably, but this book uses them in their correct technical sense.
Python is a practical language with many helpful functions in its standard library. Some exercises
will explicitly forbid you from using these functions. For example, Exercise #34, ―Uppercase Letters‖
tasks you to write code to convert a string to uppercase letters. Using Python’s built-in upper()
string method to do this for you would defeat the purpose of the exercise, so the Exercise
Description section points out that your solution shouldn’t call it.
I recommend solving the exercises in this book repeatedly until it becomes effortless. If you can
solve an exercise once, try solving it again a couple of weeks later or without looking at the hints in
the later sections. After a while, you’ll find yourself quickly being able to come up with strategies to
solve these exercises.
Let’s begin!
4
EXERCISE #1: HELLO, WORLD!
―Hello, world!‖ is a common first program to write when learning any programming language. It
makes the text ―Hello, world!‖ appear on the screen. While not much of a program, it serves as a
simple test for whether the programmer has the language interpreter correctly installed, the computer
environment set up, and a basic understanding of how to write a complete program.
This exercise adds an additional step to collect keyboard input from the user. You’ll also need to
concatenate (that is, join together) string values to greet the user by name. The exercises in this book
are for those with some experience writing programs, so if this exercise is currently beyond your skill
level, I’d recommend reading some of the beginner resources I discussed in the Prerequisites section
of the Introduction.
Exercise Description
Write a program that, when run, greets the user by printing ―Hello, world!‖ on the screen. Then it
prints a message on the screen asking the user to enter their name. The program greets the user by
name by printing the ―Hello,‖ followed by the user’s name.
Let’s use ―Alice‖ as the example name. Your program’s output should look like this:
Hello, world!
What is your name?
Alice
Hello, Alice
Try to write a solution based on the information in this description. If you still have trouble
solving this exercise, read the Solution Design and Special Cases and Gotchas sections for
additional hints.
Prerequisite concepts: print(), strings, string concatenation
5
Python Programming Exercises, Gently Explained
Solution Design
There is no surprising design to the solution. It is a straightforward four-line program:
1. Print the text, ―Hello, world!‖
2. Print the text, ―What is your name?‖
3. Let the user enter their name and store this in a variable.
4. Print the text ―Hello,‖ followed by their name.
The program calls Python’s print() function to display string values on the screen. As always,
the quotes of the string aren’t displayed on the screen because those aren’t part of the string value’s
text, but rather mark where the string begins and ends in the source code of the program. The
program calls Python’s input() function to get the user input from the keyboard and stores this in a
variable.
The + operator is used to add numeric values like integers or floating-point numbers together,
but it can also create a new string value from the concatenation of two other string values.
Solution Template
Try to first write a solution from scratch, But if you have difficulty, you can use the following
partial program as a starting place. Copy the following code from https://invpy.com/helloworld-template.py
and paste it into your code editor. Replace the underscores with code to make a working program:
# Print "Hello, world!" on the screen:
____('Hello, world!')
# Ask the user for their name:
____('What is your name?')
# Get the user's name from their keyboard input:
name = ____()
# Greet the user by their name:
print('Hello, ' + ____)
The complete solution for this exercise is given in Appendix A and https://invpy.com/helloworld.py.
You can view each step of this program as it runs under a debugger at https://invpy.com/helloworld-
debug/.
Further Reading
A ―Hello, world!‖ program is a good target program to create when learning a new programming
language. Most languages have a concept of standard streams for text-based, command-line
programs. These programs have a stream of input text and a stream of output text. The stream of
output text the program produces appears on the screen (via print() in Python). The stream of
6
Python Programming Exercises, Gently Explained
input text the program accepts comes from the keyboard (via input() in Python). The main benefit
of streams is that you can redirect them: the text output can go to a file instead of the screen, or a
program’s input can come from the output of another program instead of the keyboard. You can
learn more about the command-line interface, also called terminal windows, in the free book ―Beyond the
Basic Stuff with Python‖ at https://inventwithpython.com/beyond/. Command-line programs tend to be
simpler than graphical programs, and you can find nearly a hundred such programs in the free book,
The Big Book of Small Python Projects at https://inventwithpython.com/bigbookpython/.
7
EXERCISE #2: TEMPERATURE
CONVERSION
convertToCelsius(32) → 0.0
convertToFahrenheit(100) → 212
Converting between Celsius and Fahrenheit involves a basic calculation and provides a good
exercise for writing functions that take in a numeric input and return a numeric output. This exercise
tests your ability to use Python’s math operators and translate math equations into Python code.
Exercise Description
Write a convertToFahrenheit() function with a degreesCelsius parameter. This
function returns the number of this temperature in degrees Fahrenheit. Then write a function named
convertToCelsius() with a degreesFahrenheit parameter and returns a number of this
temperature in degrees Celsius.
Use these two formulas for converting between Celsius and Fahrenheit:
Fahrenheit = Celsius × (9 / 5) + 32
Celsius = (Fahrenheit - 32) × (5 / 9)
These Python assert statements stop the program if their condition is False. Copy them to
the bottom of your solution program. Your solution is correct if the following assert statements’
conditions are all True:
assert convertToCelsius(0) == -17.77777777777778
assert convertToCelsius(180) == 82.22222222222223
assert convertToFahrenheit(0) == 32
assert convertToFahrenheit(100) == 212
assert convertToCelsius(convertToFahrenheit(15)) == 15
Try to write a solution based on the information in this description. If you still have trouble
solving this exercise, read the Solution Design and Special Cases and Gotchas sections for
additional hints.
8
Random documents with unrelated
content Scribd suggests to you:
A. Twice.
Q. I will ask you to step down and walk over to the defendants’
dock and see whether or not you find the man Gebhardt sitting in
the dock.
(The witness complied and pointed to the defendant Gebhardt.)
Thank you. Sit down.
I will ask that the record show that the witness properly
identified the defendant Gebhardt.
Presiding Judge Beals: The record will show that the witness
identified the defendant Gebhardt in the dock.
Mr. McHaney: I have no further questions at this time.
Presiding Judge Beals: Will Dr. Alexander again be put on the stand
in connection with the examination of this witness?
Mr. McHaney: Yes, but if there is any cross-examination we can
probably finish that before lunch.
Presiding Judge Beals: Do any of the defense counsel desire to
cross-examine this witness?
Dr. Seidl (counsel for the defendants Gebhardt, Oberheuser, and
Fischer): I do not intend to cross-examine this witness, but this does
not mean that my clients admit the correctness of all statements
made by this witness.
Presiding Judge Beals: Does any other of the defense counsel
desire to examine the witness?
(No response.)
[43]
Final plea is recorded in mimeographed transcript, 15 July
1947, pp. 10874-10910.
[44]
Dr. Maczka appeared as witness before the Tribunal, 10
January 1947, Tr. pp. 1430-1462.
[45]
Complete testimony is recorded in mimeographed
transcript, 20 Dec. 1946, pp. 815-832.
[46]
This testimony is recorded in mimeographed transcript, 20
Dec. 1946, pp. 832-838.
7. SEA-WATER EXPERIMENTS
a. Introduction
The defendants Karl Brandt, Handloser, Rostock, Schroeder,
Gebhardt, Rudolf Brandt, Mrugowsky, Poppendick, Sievers, Becker-
Freyseng, Schaefer, and Beiglboeck were charged with special
responsibility for and participation in criminal conduct involving sea-
water experiments (par. 6 (G) of the indictment). In the course of
the trial the prosecution withdrew the charge in the case of
Mrugowsky. On this charge the defendants Schroeder, Gebhardt,
Sievers, Becker-Freyseng, and Beiglboeck were convicted and the
defendants Karl Brandt, Handloser, Rostock, Rudolf Brandt,
Poppendick, and Schaefer were acquitted.
The prosecution’s summation of the evidence on the sea-water
experiments is contained in its final brief against the defendant
Schroeder. Extracts from that brief are set forth below on pages 419
to 443. A corresponding summation of the evidence by the defense
on these experiments has been selected from the final plea for the
defendant Schroeder and from the closing brief for the defendant
Beiglboeck. It appears below on pages 434 to 446. This
argumentation is followed by selections from the evidence on pages
447 to 494.
Sea-Water Experiments
CROSS-EXAMINATION
ebookbell.com