Explain it simply
Explain it simply
This lesson teaches nothing new. It is a self-test of the variables, data types, strings, lists, loops and functions from the Basics chapter. Like a musician practising scales every day, things you already know only stick when your own hands write them again and again.
Write and run each task yourself, and go back to earlier lessons when you get stuck. The goal is not to copy a correct answer but to work through the logic on your own. Alongside the tasks, you will practise one method for approaching any task.
Problem → Why → Solution
The problem: right once is not right
Look at a learner's first draft. count_vowels("Python Programming") prints 4, which is correct, so the learner moves on. But trying "AEIOU" gives 0, because capital letters were forgotten. And since the function prints instead of returning, no other code can use or check the result.
The age part is worse: input() always hands back what the user typed as a str, so age + 1 stops with a TypeError. Testing with one sample would never have revealed either bug.
def count_vowels(text):
count = 0
for ch in text:
if ch in "aeiou": # capital letters are never counted
count += 1
print(count) # prints, so nothing can test the result
count_vowels("Python Programming") # 4 - looks finished
age = input("Age: ")
print(age + 1) # TypeError: input() returned a strWhy did these bugs slip through?
The sample in a task is only one of many possible inputs. Without thinking ahead about the edges, such as capital letters, an empty string, an empty list or a negative number, there is no reason to trust the program. And if a function does not return its value, those cases cannot be checked automatically at all.
Core concept: five steps for any exercise
Exercises do not test whether you remember syntax. They test whether you can break a problem into input, checks, transformation and output. Follow these steps for each of the four tasks.
1. Write examples first
Before coding, list input → expected output pairs: at least one normal case from the task, one edge case such as an empty string or list, and one invalid case such as "abc" given as an age. This table becomes your tests.
2. Plan the steps in comments
Three lines of pseudocode such as "loop over each letter, add one for a vowel, return the count" decide the shape of the code before syntax gets in the way.
3. Return a value
Write each task as a function that returns its result. Keep input() and print() at the edges of the program, so the function can be checked and reused elsewhere.
4. Check with assert
A line such as assert count_vowels("") == 0 does nothing when it holds and raises AssertionError with the line number when it does not. When one fails, read the traceback from the bottom and find the smallest input that still fails.
5. Refactor once it is correct
Only when every assert passes, tidy up, for example by replacing a loop with a list comprehension. The asserts immediately tell you the refactor broke nothing.
| Task | Normal → output | Edge → output |
|---|---|---|
| count_vowels | "Python Programming" → 4 | "rhythm" → 0 |
| evens | [4, 7, 2] → [4, 2] | [-4, -3, 0] → [-4, 0] |
| multiples_of_3 | 50 → 3 ... 48 | 2 → [] |
- Write examples before any code
- Plan the steps as comments
- Return a value from a function
- Assert normal, edge, invalid cases
- Refactor only when all pass
Writing the example table feels slow, but it saves far more time than it costs in debugging.
General pattern
def solve(data):
result = ... # build the answer step by step
return result # return it; let the caller decide to print
assert solve(normal_input) == expected_output
assert solve(edge_input) == edge_output
print(solve(normal_input))The function returns the answer, the asserts turn your example table into code, and print() is called once, at the end.
The four tasks, solved without input()
Task 1 does not call input() directly, because a script that does hangs wherever there is no user, such as a test or an automated runner. Instead the greeting is a greet(name, age) function that receives the values as arguments. Task 4 prints its sixteen numbers on one line instead of sixteen, and the file ends with edge-case asserts.
# Task 1: Greeting - build the sentence in a function so it can be tested.
# In an interactive script the values would come from input(), which always
# returns a str: name = input("Name: "); age = int(input("Age: "))
def greet(name, age):
return f"Hi {name}, you are {age} years old"
# Task 2: Count vowels (upper and lower case)
def count_vowels(text):
count = 0
for ch in text.lower():
if ch in "aeiou":
count += 1
return count
# Task 3: Keep only the even numbers
def evens(numbers):
return [n for n in numbers if n % 2 == 0]
# Task 4 (bonus): multiples of 3 from 1 to 50
def multiples_of_3(limit):
return [i for i in range(1, limit + 1) if i % 3 == 0]
print(greet("Aye Aye", 21))
print("Vowels in 'Python Programming':", count_vowels("Python Programming"))
print("Even numbers:", evens([4, 7, 2, 9, 10, 15, 6]))
print("Multiples of 3:", *multiples_of_3(50))
# Edge cases: one sample output is not proof, so check the corners too
assert count_vowels("") == 0
assert count_vowels("rhythm") == 0 # y is not in our vowel list
assert count_vowels("AEIOU") == 5 # upper case counts
assert evens([]) == []
assert evens([-4, -3, 0]) == [-4, 0] # negatives and zero are fine
assert multiples_of_3(2) == []
print("All edge-case checks passed")Code breakdown
- Return the sentence
def greet(name, age):The function returns a string, so it can be checked with assert greet("Su", 9) == "Hi Su, you are 9 years old". input() belongs at the edge of the program, in the main code.
- Lower-case once
for ch in text.lower():Lower-casing the whole text means comparing against just "aeiou" while still counting capitals.
- Filter with a comprehension
return [n for n in numbers if n % 2 == 0]n % 2 == 0 also works for negatives and zero (-4 % 2 is 0). The comprehension builds a new list, so the original list is untouched.
- range() stops before its end
return [i for i in range(1, limit + 1) if i % 3 == 0]range(1, limit) excludes limit itself, so "up to 50" needs limit + 1. That way, a limit that is itself a multiple of 3, such as 51, is included.
- Unpack into print
print("Multiples of 3:", *multiples_of_3(50))The * spreads the list into separate arguments, so print() writes them on one line separated by spaces.
- Edge cases as asserts
assert count_vowels("rhythm") == 0 # y is not in our vowel listThe asserts cover cases the task's sample never tries. If one is wrong, you get an AssertionError instead of the final "All edge-case checks passed" line.
Hi Aye Aye, you are 21 years old
Vowels in 'Python Programming': 4
Even numbers: [4, 2, 10, 6]
Multiples of 3: 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48
All edge-case checks passedinput() always returns a str
Even when the user types 21, input() returns the string "21". Adding the string "1" joins the text into "211", and adding the number 1 raises TypeError. So convert once with int() at the edge of the program and let the rest of the code work with numbers. Remember that int() raises ValueError when the user types "abc"; the challenge handles exactly that.
raw = "21" # what input() hands you when the user types 21
print(type(raw).__name__, raw + "1")
age = int(raw) # convert once, at the edge of the program
print(type(age).__name__, age + 1)In real projects
In real projects
These tasks are small, but the habit transfers directly to work. In coding interviews, interviewers often ask for examples and edge cases before any code, and forgetting the empty input is one of the most common slips. Teams write this lesson's asserts as pytest test functions, for example def test_count_vowels_empty(): assert count_vowels("") == 0. When a reviewer asks "what happens with an empty string?", they are asking about step 1.
When you finish this exercise, show yourself a result for each task with its example table, its code and its asserts. That is the same shape as a pull request at work, where a reviewer wants to see at a glance what changed, which cases were checked and whether the tests pass.
Common mistakes
Common mistakes
Printing instead of returning
A function that only calls print() returns None, so total = count_vowels(text) + 1 raises TypeError and nothing can be asserted. Return the value and let the caller print it.
Treating input() as a number
After age = input(), age + 1 raises TypeError, while age * 2 silently returns "2121". The second is more dangerous precisely because nothing complains.
Forgetting where range() stops
range(1, 50) stops at 49; "from 1 to 50" needs range(1, 51). Off-by-one errors rarely show in the sample output, only at the boundary value.
Validating user input with assert
assert is a check for developers. Running python -O skips every assert, so validate user input with if statements and ValueError instead.
Best practices
Best practices
- Stuck on a task for more than fifteen minutes? Revisit the example table; the gap is usually understanding, not syntax
- Name each function after what it returns, such as count_vowels or evens
- Every time you find a bug, add an assert that catches it before you fix it
- After reading a solution, rewrite it the next day without looking
Mini challenge
Four new basics tasks
Write the four functions below. For each, write a normal and an edge example before coding, and add at least one assert per function.
- initials("aung kyaw moe") returns "A.K.M." and an empty string gives ""
- long_words(text, min_length) strips punctuation and returns words at least min_length long
- running_total([5, 10, -3, 8]) returns [5, 15, 12, 20]
- parse_age(text) returns an int from 1 to 129, otherwise None (including "abc", "-4" and "")
def initials(full_name):
# TODO: split into words; join the first letter of each, upper-cased, with "."
...
def long_words(text, min_length):
# TODO: split, strip ".,!?" from each word, keep the long ones
...
def running_total(numbers):
# TODO: keep a running sum and append it after each number
...
def parse_age(text):
# TODO: int() inside try/except ValueError; None if invalid or out of range
...
# TODO: print one call per function, then assert at least one edge case eachExpected: A.K.M., ['Python', 'loops', 'powerful'], [5, 15, 12, 20] and [21, 35, None, None, None, None], followed by All checks passed.
Show hint
" su su ".split() ignores the extra spaces and gives ["su", "su"]. int(" 35 ") accepts surrounding spaces, and int("abc") raises ValueError.
Show solution
def initials(full_name):
parts = full_name.split()
return ".".join(p[0].upper() for p in parts) + "." if parts else ""
def long_words(text, min_length):
words = [w.strip(".,!?") for w in text.split()]
return [w for w in words if len(w) >= min_length]
def running_total(numbers):
totals, total = [], 0
for n in numbers:
total += n
totals.append(total)
return totals
def parse_age(text):
try:
age = int(text) # int() ignores surrounding spaces
except ValueError:
return None
return age if 0 < age < 130 else None
print(initials("aung kyaw moe"))
print(long_words("Python is fun, and loops are powerful!", 5))
print(running_total([5, 10, -3, 8]))
print([parse_age(t) for t in ["21", " 35 ", "abc", "-4", "200", ""]])
assert initials("") == ""
assert initials(" su su ") == "S.S."
assert long_words("", 3) == []
assert running_total([]) == []
print("All checks passed")Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Write normal, edge and invalid examples before writing code
- Write each task as a function that returns a value; keep input() and print() at the edges
- input() returns a str: convert once with int() and handle ValueError
- assert is a developer check; validate user input with if statements
The Python Tutorial — Python Software Foundation