Learn Enough Society
Certificate of Course CompletionThis page certifies that actionjdjackson has completed Learn Enough Python to Be Dangerous! 🎉
city
and state
to your current city and state of residence. (If residing outside the U.S., substitute the analogous quantities.) Using interpolation, print a string consisting of the city and state separated by a comma and a space, as in “Los Angeles, CA”.
x
is "foo"
and y
is ""
(the empty string), what is the value of x and y
? Verify using bool()
that x and y
is true in a boolean context.
50
using the convenient code in Listing 2.20, which uses the asterisk *
to “multiply” the string "a"
by 50. Go through the steps in Listing 2.10 again with the new password to verify that Python prints out “Password is too long.”
FILL_IN
replaced by the method name.
for
loop that prints out the characters of soliloquy
in reverse order. Hint: What is the effect of the reversed()
function on a string?
for
loop in Listing 2.27 is that we no longer have access to the index value itself. We could solve this as in Listing 2.28, but the Pythonic way to do it is to use the enumerate()
function to gain access to the index and the element at the same time. Confirm that you can use enumerate()
to obtain the result shown in Listing 2.29.
a
to the result of splitting the string “A man, a plan, a canal, Panama” on comma-space. How many elements does the resulting list have?
a
in place? (Google around if necessary.)
list(str)
returns a list of the characters in a string. How can we make a list consisting of the numbers in the range 0–4? Hint: Recall the range()
function first encountered in Listing 2.24.
list()
with range(17, 42)
.
len()
to select the third element through the third-to-last. Accomplish the same task using a negative index.
"bat"
from the string "ant bat cat"
. (You might have to experiment a little to get the indices just right.)
sort()
and sorted()
support a keyword argument (Section 5.1.2) that does it automatically. Confirm that a.sort(reverse=True)
and sorted(a, reverse=True)
both have the effect of sorting and reversing at the same time.
extend()
method. Does extend()
mutate a1
? Does it mutate a2
?
reversed()
to print out a list’s elements in reverse order.
ant
instead of "ant"
. We could put the quote marks in by hand, but then that would print 42
out as "42"
, which is also wrong. Solve this conundrum using the repr()
function (Section 2.3) to interpolate a representation of each list element, as shown in Listing 3.12.
tuple()
function by converting sorted(t)
from a list to a tuple.
set()
with range()
. (Recall the use of range()
in Listing 2.24.) Confirm that the pop()
method mentioned in Section 3.4.3 allows you to remove one element at a time.
float()
on the string "1.24e6"
? What about if you call str()
on the result?
int(6.28)
and int(6.98)
both equal 6
. This is the same behavior as the floor function (written in mathematics as \( \lfloor x \rfloor \)). Show that Python’s math
module has a floor()
function with the same effect as int()
.
DAYNAMES
out of the hello_world
function, as shown in Listing 4.4. (This is the preferred location for constants in general—under library imports and separated from the rest of the file by two newlines.) Then use the calendar
module to eliminate the constant entirely (Listing 4.5).
re.search()
and the caption in Figure 4.8.6
sonnet.split(/your regex/)
. What is the length of the resulting list?
user
with three attributes (keys): "username"
, "password"
, and "password_confirmation"
. How would you test if the password matches the confirmation?
enumerate()
function in cases where we need the iteration index. Confirm that we can do the same thing with dictionaries using code like Listing 4.9.
d1 | d2
is not in general the same as d2 | d1
. When are they the same?
\w
, an apostrophe, and the plus operator +
.
Counter()
function from the Python collections
module. See this excellent video for more detail on this subject.
help(len)
in the Python interpreter to confirm that help()
works on built-in functions as well. What is the result of running the command help(print)
? (The result in this case is called a multi-line docstring.)
deriver()
function as shown in Listing 5.5 that takes in a function and returns how much it changes over a small interval h
. Confirm that you get the result shown for the square()
function mentioned at the beginning of Section 5.1.1 (which was first defined in Listing 5.1). What is the result of evaluating deriver(math.cos,
math.tau/2)
?5
foo()
with both *args
and **kwargs
as shown in Listing 5.6. What do you get when you execute the function as shown in the final statement of Listing 5.6? (Note that you should not type ...
in the call to foo()
; as we have seen when defining functions, those are continuation characters added automatically by the Python interpreter.)
greeting()
function in day.py
. Fill in the code labeled FILL_IN
in Listing 5.13 to get Listing 5.14 to work.
ispalindrome()
function from Listing 5.17 on emojis. (You may find the Emojipedia links to the racing car and fox face emojis helpful.) If your system supports emojis in this context, the result should look something like Figure 5.8. (Note that an emoji is a “palindrome” if it’s the same when you flip it horizontally, so the fox-face emoji is a palindrome but the racecar emoji isn’t, even though the word “racecar” is a palindrome.)
ispalindrome()
function in one line using the advanced slice operator [::-1]
discussed in Section 3.3. (Some Python programmers may prefer this approach, but I believe the decrease in length doesn’t justify the loss in clarity.)
states
variable and returns a list of URLs of the form https://example.com/<urlified form>
.
in
(Section 2.5) to test for the presence of the string “Dakota” and one that tests for the length of the split list being 2
.
states
with its URL-compatible versions. Hint: Reuse the urlify()
function defined in Listing 6.3.
math.prod()
to find the product of the numbers in the range 1–10. How does this compare to math.factorial(10)
?
louder
method to the Phrase
object that returns a LOUDER (all-caps) version of the content. Confirm in the REPL that the result appears as in Listing 7.7. Hint: Use the appropriate string method from Section 2.5.
list(phrase)
works after the custom iterator has been defined as in Listing 7.8. What about joining on the empty string using "".join(phrase)
?
processed_content()
method is only used internally to the classes. Many object-oriented languages have a way of designating such methods as private, a practice known as encapsulation. Python doesn’t have truly private methods, but it does have a convention for indicating them using a leading underscore. Confirm that the classes still work after changing processed_content()
to _processed_content()
as shown in Listing 7.15. Note: Python has a second convention, known as name mangling, that uses two leading underscores. With this convention, Python automatically changes the name of the method in a standard way so that it can’t be easily accessed through an object instance.
TranslatedPhrase
to use the translation instead of the untranslated content. Arrange for this by overriding the __iter__
method in the derived class (Listing 7.16). Confirm using the Python interpreter that the updated iterator works as expected. (Note that Listing 7.16 incorporates the private method convention from the previous exercise.)
letters()
stub in Listing 8.28 yields a failing state rather than an error state. (This behavior is relatively unusual, with many other languages distinguishing between a non-working method and one that’s missing altogether. In Python, though, the result is the same failing state in either case.)
Phrase
class into the Python REPL and confirm directly that ispalindrome()
can successfully detect palindromes of the form “Madam, I’m Adam.”
12321
. By filling in FILL_IN
in Listing 8.38, write tests for integer non-palindromes and palindromes. Get both tests to green using the code in Listing 8.39, which adds a call to str
to ensure the content is a string and includes \d
in the regex to match digits as well as letters. (Note that we have updated the name of the letters()
method accordingly.)
pyproject.toml
, commit and push your changes, build your package with build
, and upload it with twine
. In your temp directory, upgrade your package using the command in Listing 8.40 and confirm in the REPL that integer-palindrome detection is working. Note: The backslash \
in Listing 8.40 is a continuation character and should be typed literally, but the right angle bracket >
should be added by your shell program automatically and should not be typed.
url
and Bug Tracker
fields with the corresponding GitHub URLs (the tracker URL is just the base URL plus /issues
). Likewise, update the license template in Listing 8.5 with your name and the current year. Commit and push your changes up to GitHub.
print()
with the end=""
option mentioned in Section 2.3 to prevent a duplicate newline.)
main()
) and then call the function only when the file itself is called as a shell script. (See this video for more.) Using the special syntax introduced in Section 7.1, show that the shell script in Listing 9.7 can be converted to Listing 9.8. Does it give the same result when executed at the command line?
main()
call that function, as seen in Listing 9.9. Show that this code still produces the same output as before.
palindromes_url.txt
. Confirm using the diff
utility that the output is identical to the palindromes_file.txt
file from Section 9.1.
wikp
script to your environment’s PATH. (You may find the steps in Learn Enough Text Editor to Be Dangerous helpful.) Confirm that you can run wikp
without prepending ./
to the command name. Note: If you have a conflicting wikp
program from following Learn Enough JavaScript to Be Dangerous or Learn Enough Ruby to Be Dangerous, I suggest replacing it—thus demonstrating the principle that the file’s name is the user interface, and the implementation can change language without affecting users.
wikp
with no argument? Add code to your script to detect the absence of a command-line argument and output an appropriate usage statement. Hint: After printing out the usage statement, you will have to exit, which you can learn how to do with the search python how to exit script.
pbcopy
” trick mentioned in the text works only on macOS, but any Unix-compatible system can redirect the output to a file. What’s the command to redirect the output of wikp
to a file called article.txt
? (You could then open this file, select all, and copy the contents, which has the same basic result as piping to pbcopy
.)
requirements.txt
file using pip -r
. Confirm that the sequence shown in Listing 10.10 results in a restored and working app.
lang
(language) attribute to the html
tag. Add the attribute lang="en"
(for “English”) to the html
tag in Listing 10.22 and confirm using a web inspector that it appears correctly on all three pages.
True
for the empty string, which is a flaw in the palindrome package itself. What happens if you submit a bunch of spaces?
processed_content()
method already filters out spaces, so in the application code you need only consider the case of the empty string, whose boolean value is False
(Section 2.4.2).) Bump the version number and publish your package as in Section 8.5.1. (You can refer to my version if you’d like some help.)
\
in Listing 10.64 but not the right angle bracket >
since the latter will be inserted automatically by your shell program.)
reshape()
don’t match the array size (e.g., np.arange(16).reshape((4, 17))
)?
A = np.random.rand(5, 5)
lets you define a \( 5\times5 \) random matrix.
Ainv
of the \( 5\times5 \) matrix in the previous exercise. (Calculating the inverse of a \( 2\times2 \) matrix as in Section 11.2.2 is fairly simple by hand, but the task rapidly gets harder as the matrix size increases, in which case a computational system like NumPy is indispensable.)
I = A @ Ainv
of the matrices in the previous two exercises? Use the same isclose()
trick from Listing 11.7 to zero out the elements of I
close to zero and confirm that the resulting matrix is indeed the \( 5\times5 \) identity matrix.
suptitle()
method produces a “supertitle” that sits above both plots. See the Matplotlib documentation on subplots for other ways to create multiple subplots.)
"orange"
and linestyle "dashdot"
. Extra credit: Add an annotation as well. (The extra-credit step is much easier in an interactive Jupyter notebook, especially when finding the right coordinates for the annotation label and arrow.)
laureates.csv
dataset. Why did we miss him when we searched for Curies in Listing 11.15? Hint: Search for an entry with "firstname"
equal to "Frédéric"
(making sure to include the proper accents).
nobel.hist()
, with no column specified?
male_
and female_
variables.
RandomForestClassifier()
function takes a keyword argument called n_estimators
that represents the “number of trees in the forest”. According to the documentation, what is the default value for n_estimators
? Use random_state=1
.
n_estimators
in the call to RandomForestClassifier()
, determine the approximate value where the Random Forest classifier is less accurate than Decision Tree. Use random_state=1
.
random_state
, verify that the ordering is not always the same as shown in Listing 11.25. Hint: Try values like 0
, 2
, 3
, and 4
.
Get free access to all 10 Learn Enough courses (including the Ruby on Rails Tutorial) for 7 days!
We require a credit card for security purposes, but it will not be charged during the trial period. After 7 days, you will be enrolled automatically in the monthly All Access subscription.
BUT you can cancel any time and still get the rest of the 7 days for free!
All Learn Enough tutorials come with a 60-day 100% money-back guarantee.