Lecture 9: Loops Exercises
Watch on YouTube →
Overview
The lecture develops loop-based problem solving through four exercises: counting vowels, counting even digits, detecting three-digit Armstrong numbers, and searching for the Riddler’s address. It emphasizes accumulator variables, Python membership tests, string iteration, and arithmetic digit extraction with modulo and integer division, while also advising students to practice without AI and explaining exam preparation expectations.
Key takeaways
- Initialize an accumulator such as count to zero, update it when a condition is met, and return it to report a function's computed result.
- In Python, `letter == 'a' or 'e'` is effectively always true because the nonempty string `'e'` is truthy; compare every candidate explicitly or use `letter in 'aeiou'`.
- Integers are not iterable, so count their digits either by converting to a string or by repeatedly taking `% 10` and applying integer division by 10.
- A while loop can process an unknown number of digits by continuing while the remaining integer is positive; handle input zero separately because the loop otherwise runs zero times.
- For a three-digit Armstrong test, extract each place value, cube each digit, sum the cubes, and compare the result with the original number.
- The Riddler exercise contains a condition-answer mismatch: the prompt specifies a digit sum of 21, while the code's result, 9837, has a sum of 27.
Chapters
- IDLE comes bundled with Python and is the editor used in this class.
- VS Code, Notepad++, and Geany offer features such as autocomplete; PyCharm provides a more industrial-strength Python IDE.
- Vim, Neovim, Emacs, and the newer micro editor are alternatives; basic Vim navigation can help when editing files on remote machines.
- The instructor recommends avoiding AI-generated code while learning because it can produce constructs students do not yet understand, such as list comprehensions.
- The weightlifting analogy is that relying on AI to write code is like having a spotter lift the weight instead of building programming skill.
- Eclipse and IntelliJ are mentioned as likely Java IDEs in the next course.
- The practice exam is designed to be harder than the actual exam, and students are advised to allow two hours when attempting it.
- The exam is likely moving to week seven because a wellness day disrupts the earlier schedule.
- A handwritten or typed one-sheet cheat sheet is permitted, provided it does not interfere with another student's workspace.
- A challenging practice example asks students to reuse a square-drawing function to draw four overlapping squares.
- Exam questions may provide an image and partial code, with blanks for students to fill in to transform one drawing into another.
- Nested for loops, including the practice exam's question 11, are highlighted as a topic that often challenges students.
- The in-class exercises ask students to use return values instead of printing every result.
- The first function, num_vowels(text), should return an integer; for example, "apple" contains two vowels.
- A counter initialized to zero serves as an accumulator, and returning -1 temporarily provides a clear placeholder while the function is being built.
- A for loop can examine each character in text and increment count when the character is a vowel.
- One explicit condition checks whether each letter equals a, e, i, o, or u; the examples initially assume lowercase text and exclude y.
- Python's or operator joins separate Boolean expressions, so each comparison must repeat the variable being tested.
- Writing `letter == 'a' or 'e'` does not compare letter with both values; the standalone string `'e'` is truthy.
- Because nonempty strings evaluate as true in Boolean contexts, the faulty condition can count every character as a vowel.
- Use complete comparisons joined by or, or use a membership test such as `letter in vowels`.
- Defining vowels as `"aeiou"` allows a loop to test each character with `letter in vowels`.
- A second approach loops over the five vowels and adds `text.count(vowel)` to the total.
- The instructor considers membership testing a particularly Python-like option, while noting that all three approaches produce the intended result.
- The next function should return the number of even digits in an integer; for 254, the expected result is two.
- A for loop cannot iterate directly over an integer because an integer is not iterable.
- Two possible strategies are to convert the number to a string or to extract digits mathematically with modulo and integer division.
- Students are given time to attempt the even-digit problem before the instructor demonstrates solutions.
- The string strategy turns the integer into text so a for loop can process one digit character at a time.
- The arithmetic strategy uses `% 10` to obtain the last digit and integer division by 10 to discard it.
- The demonstrated string solution applies `str(num)`, loops over the resulting characters, and converts each character back with `int(digit)`.
- A digit is even when `digit % 2 == 0`; each matching digit increments the counter, which the function returns.
- This method performs extra conversions but is a straightforward beginner solution that works.
- A while loop continues while the number is greater than zero, processing its digits one at a time.
- Modulo 10 retrieves the ones digit; integer division by 10 removes it so the next digit becomes the ones digit.
- The instructor treats zero as a special case because it has one even digit, and notes that digit-counting variations may appear on exam two.
- A three-digit Armstrong number equals the sum of the cubes of its digits: 371 = 3³ + 7³ + 1³, and 370 = 3³ + 7³ + 0³.
- The function extracts ones, tens, and hundreds using modulo 10 and integer division, then compares the number with the sum of the three cubes.
- Returning the Boolean expression directly avoids separate branches that return True or False; 371 tests true and 369 tests false.
- The search checks four-digit candidates from 1000 to 9999 and uses a step of two, starting at 1001, to consider only odd numbers.
- Modulo and integer division extract the ones, tens, hundreds, and thousands digits; six pairwise inequality checks ensure all four are distinct.
- The address found is 9837: its thousands digit is three times its tens digit, and its digits sum to 27.
- The stated puzzle says the digit sum is 21, but the demonstrated code and answer use 27; 9 + 8 + 3 + 7 equals 27.
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Professor Rosen.