Beginning Python: For Loops
2025-10-08
ifelifelseqmd, create a new Python blockif, elif, else) that:
word is in the list of sibilantsplural by adding “ɪz” to the wordvoiceless.
plural to the word + “s”plural to the word + “z”len(), which tells us the length of a string, list, etc.len() of a list, and by creating a counter, we could get our script to print each book one by one…char_index = 0
if char_index < len(charlotte):
print(charlotte[char_index])
char_index += 1
else:
????if only runs once – we have no way to iterate (to repeat the action over and over again)
if Statements vs. for Loopsif statements are used to control which pieces of code are run, depending on certain conditionsfor loops are used to run the same block of code over and over again on items in an iterable.title, book are temporary (loop) variablesbook, title, etc.) persists after the loop is finished:for LoopsBy Dr. Josef Fruehwald
for loopsBelow is a list of five important terms in Linguistics:
Your task: Write a for loop that prints out:
len()) of each word in the listEach printed statement should look like: “python has 6 letters.”
qmd doc is found in.import urllib.request
url = "https://www.gutenberg.org/files/141/141-0.txt" # Mansfield Park
filename = "mansfield_park.txt"
urllib.request.urlretrieve(url, filename)
print("Downloaded:", filename)with open(...) blockprint(book_text[:200])?with open("mansfield_park.txt", "r", encoding="utf-8") as f:
book_lines = f.readlines()
len(book_lines)\n? That’s indicating a line break..rstrip() method..lstrip() method..strip(), which will handle both sides at once:"The" and "the" will count as the same word.lower()upper()mansfield_cleaned. You’ll need this list comprehension:for loop Activitywith open("mansfield_park.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
# Clean it: strip whitespace + lowercase
[mansfield_cleaned = line.strip().lower() for line in lines]
# Check the first 200 characters
print(mansfield_cleaned[0:10])