These exercises practice what the Module 6 reading explained. They aren’t graded. Work each one on paper first, then check your answer, and only then run the code to confirm it. The answers are in the collapsed blocks; open one only after you have an answer of your own.
Worked example: reading a slice¶
Take s = "programming". Write the indices under the letters first:
p r o g r a m m i n g
0 1 2 3 4 5 6 7 8 9 10s[3:7]starts at index 3 and stops just before 7, so it takes indices 3, 4, 5, and 6:"gram". It has 7 − 3 = 4 characters.s[-4:]starts four from the end, at index 7, and runs to the end:"ming".s[::-1]takes every character, backward:"gnimmargorp".
Exercise 6.1 (LO-6.1, ★, about 10 minutes)¶
With s = "programming", write a slice of s that gives each string:
"pro""ming", in a different way from the worked example"pormig""margorp"
Hint
The third takes every second character. The fourth goes backward from the first m.
Answer
s[:3], ors[0:3].s[7:], ors[7:11].s[::2]: indices 0, 2, 4, 6, 8, and 10.s[6::-1]: from index 6 backward to the start.s[6:0:-1]stops just before index 0, so it gives"margor", without thep.
Exercise 6.2 (LO-6.1, ★★, about 10 minutes)¶
This function is meant to say whether a word has a letter twice in a row. It prints True for
"letter", then stops with an error for "python". Explain why it works for one word and not the
other, and fix it.
def has_double(word):
"""Return True if any letter in word is the same as the next one."""
for i in range(len(word)):
if word[i] == word[i + 1]:
return True
return False
print(has_double("letter"))
print(has_double("python"))Answer
On its last pass, the loop reads word[i + 1] with i at the last index, one past the end, which is IndexError: string index out of range. For "letter" the loop returns at i = 2, on tt, before it gets that far, so the mistake stays hidden. It shows only for a word with no double letter. Stop the loop one index earlier:
def has_double(word):
"""Return True if any letter in word is the same as the next one."""
for i in range(len(word) - 1):
if word[i] == word[i + 1]:
return True
return FalseTests with only words that have doubles would never have found this mistake; testing one of each kind does.
Worked example: cleaning a typed answer¶
A program asks a yes-or-no question and should accept y or yes, in any case, with spaces
around it:
def is_yes(answer):
"""Return True if answer is y or yes, in any case, with any spaces around it."""
cleaned = answer.strip().lower()
return cleaned == "y" or cleaned == "yes"
print(is_yes(" Yes\n"), is_yes("Y"), is_yes("yeah"), is_yes(""))True True False Falsestrip runs first, then lower, each on the string the one before it returned. A shorter test,
cleaned in "yes", looks right but is wrong: in asks whether cleaned appears inside
"yes", so it accepts "e", "es", and even the empty string, because "" in "yes" is True.
Exercise 6.3 (LO-6.2, ★, about 10 minutes)¶
What does each expression give?
" Data Science ".strip().lower().replace(" ", "_")"x=1;y=2;z=3".split(";")"; ".join(["x=1", "y=2"])"hello world".find("o")"hello world".count("o")"hello world".find("O")"hello".upper().startswith("he")"hello" in "Hello, world"
Answer
"data_science": only the space between the words is left to replace afterstrip.['x=1', 'y=2', 'z=3']"x=1; y=2": the separator goes between the items, not after the last.4: the firsto, inhello.2-1: searches tell capitals from lowercase letters.False:upperruns first, and"HELLO"doesn’t start with"he".False, for the same reason: the text hasHello, with a capital.
Exercise 6.4 (LO-6.2, ★★, about 10 minutes)¶
Write file_extension(filename), which returns the part of a file name after its last dot,
in lowercase, or "" if it has no dot. rfind works like find, but gives the index of the last
match instead of the first.
| Call | Result |
|---|---|
file_extension("report.PDF") | "pdf" |
file_extension("archive.tar.gz") | "gz" |
file_extension("README") | "" |
Hint
Find the last dot with rfind, check for -1 as the reading warns, and then slice from just after the dot.
Answer
def file_extension(filename):
"""Return the lowercase extension after the last dot in filename, or "" if it has none."""
dot = filename.rfind(".")
if dot == -1:
return ""
return filename[dot + 1:].lower()Without the check for -1, "README" gives filename[0:], the whole name, "readme". "notes." gives "", because the slice after a final dot is empty. Splitting works too: filename.split(".") gives the pieces between the dots, and the extension is the last one, [-1], when there is more than one.
Worked example: keeping only some characters¶
A reference number is typed with hyphens, spaces, and other text around it. Keep only its digits:
def digits_only(text):
"""Return the digits 0-9 in text, in order, as a string."""
digits = ""
for character in text:
if character in "0123456789":
digits = digits + character
return digits
print(digits_only("Order 2026-0412-77, box 3"))20260412773This is the accumulator pattern with a string: start empty, and add each character that passes
the test. Testing in "0123456789" rather than isdigit() keeps out digits from other writing
systems, which isdigit accepts.
Exercise 6.5 (LO-6.3, ★★, about 20 minutes)¶
Write is_strong(password), which returns True when a password has at least 10 characters and
contains at least one of each of these: a lowercase letter from a to z, a capital from A to Z, a
digit from 0 to 9, and a character that is none of those and isn’t a space. Test it on both sides
of each rule.
Hint 1
Use four variables that start as False, one for each kind of character, and set each to True when the loop finds that kind. Return the result after the loop.
Hint 2
"a" <= character <= "z" tests for a lowercase letter from a to z, using code points.
Answer
def is_strong(password):
"""Return True if password is 10+ characters with a-z, A-Z, 0-9, and another symbol."""
if len(password) < 10:
return False
has_lower = False
has_upper = False
has_digit = False
has_other = False
for character in password:
if "a" <= character <= "z":
has_lower = True
elif "A" <= character <= "Z":
has_upper = True
elif "0" <= character <= "9":
has_digit = True
elif character != " ":
has_other = True
return has_lower and has_upper and has_digit and has_other
assert is_strong("Abcdefgh1!")
assert not is_strong("Abcdefg1!")
assert not is_strong("abcdefgh1!")
assert not is_strong("ABCDEFGH1!")
assert not is_strong("Abcdefghi!")
assert not is_strong("Abcdefgh12")
assert not is_strong("Abcdefgh1 2")
print("all tests passed")The first test passes every rule with exactly 10 characters. Each other test breaks one rule: 9 characters, then no capital, no lowercase letter, no digit, no symbol, and a space where the symbol should be. Returning False early for a short password saves the loop, and the elif chain sorts each character into exactly one kind.
Exercise 6.6 (LO-6.2, LO-6.3, ★★, about 10 minutes)¶
Write acronym(phrase), which returns the first letter of each word in capitals. A hyphen
separates words too.
| Call | Result |
|---|---|
acronym("portable network graphics") | "PNG" |
acronym(" as soon as possible ") | "ASAP" |
acronym("read-only memory") | "ROM" |
Answer
def acronym(phrase):
"""Return the first letter of each word of phrase, in capitals."""
letters = ""
for word in phrase.replace("-", " ").split():
letters = letters + word[0].upper()
return lettersReplacing each hyphen with a space before splitting turns read-only into two words. word[0] is safe, because split() never gives an empty word, and acronym("") returns "".
Exercise 6.7 (LO-6.4, ★★, about 10 minutes)¶
Put these words in the order Python’s
<puts them, and explain each surprise:"apple","Banana","cherry","apple pie", and"Äpfel".Write
is_ascii(text), which returnsTruewhen every character oftextis in ASCII, that is, has a code point below 128.
Answer
"Banana","apple","apple pie","cherry","Äpfel"."Banana"comes first becauseBis 66 and every lowercase letter is 97 or more."apple"comes before"apple pie"because when one string is the start of the other, the shorter one comes first."Äpfel"comes last becauseÄis 196, after every ASCII letter, though a German dictionary puts it with the a’s.def is_ascii(text): """Return True if every character of text has a code point below 128.""" for character in text: if ord(character) >= 128: return False return TrueStrings also have a method that does this,
text.isascii(). Both returnTruefor the empty string, which has no character outside ASCII.
Exercise 6.8 (LO-6.3, LO-6.4, ★★★, about 25 minutes)¶
A Caesar cipher shifts every letter by the same amount, so trying all 25 shifts breaks it, as
Lab 6 did. The Vigenère cipher shifts each letter by a different amount, taken from a key
word: each letter of the key is a shift, with a as 0, b as 1, and so on, used in turn and
repeated as often as needed. With the key "bad", the shifts are 1, 0, 3, 1, 0, 3, and so on, so
"hello" becomes "ieomo". Only letters use up a letter of the key: a space or punctuation is
copied as it is, and the next letter gets the next shift.
Write vigenere(text, key, direction=1), which shifts each letter from a to z and from A to Z and
keeps its case. key is lowercase letters. With direction=-1 it shifts the other way, so
vigenere(vigenere(text, key), key, -1) is text again.
| Call | Result |
|---|---|
vigenere("hello", "bad") | "ieomo" |
vigenere("a b", "bc") | "b d" |
vigenere("Meet me at noon.", "key") | "Wicd qc kx lysl." |
Hint 1
Keep a count of the letters shifted so far. The shift for the next letter comes from key[count % len(key)], and % wraps the count back to the start of the key.
Hint 2
The reading’s shift_letter shifts a lowercase letter. For a capital, shift its lowercase form, then turn the result back into a capital.
Answer
def shift_letter(letter, shift):
"""Return the lowercase letter shift places further along the alphabet, wrapping around."""
position = ord(letter) - ord("a")
new_position = (position + shift) % 26
return chr(ord("a") + new_position)
def vigenere(text, key, direction=1):
"""Return text with each letter a-z and A-Z shifted by the next letter of key."""
result = ""
used = 0
for character in text:
if "a" <= character <= "z" or "A" <= character <= "Z":
shift = (ord(key[used % len(key)]) - ord("a")) * direction
shifted = shift_letter(character.lower(), shift)
if "A" <= character <= "Z":
shifted = shifted.upper()
result = result + shifted
used = used + 1
else:
result = result + character
return result
assert vigenere("hello", "bad") == "ieomo"
assert vigenere("a b", "bc") == "b d"
assert vigenere("Meet me at noon.", "key") == "Wicd qc kx lysl."
assert vigenere("Zebra", "b") == "Afcsb"
message = "Meet me at noon."
assert vigenere(vigenere(message, "key"), "key", -1) == message
print("all tests passed")The common mistakes are moving to the next key letter on every character, spaces included, which vigenere("a b", "bc") catches by giving "b c", and testing isalpha(), which shifts letters such as é that the cipher should copy. A key of only as shifts nothing, so it is the same as no cipher at all. "Zebra" checks that a capital wraps from Z to A and stays a capital.