How to Use These Practice Exercises
This chapter is a hands-on set of exercises designed to help you test what you can actually build. Each exercise includes (1) a task, (2) constraints, (3) a few example inputs (when relevant), (4) expected outputs, and (5) self-check questions. The goal is not to memorize syntax, but to practice turning a problem statement into working code and then verifying it.
Rules for Practice
- Write the code yourself first. Only look at expected output to verify behavior, not to copy.
- Run your script multiple times with different inputs (including “weird” ones).
- Compare exact output when the exercise specifies exact formatting (spaces, punctuation, line breaks).
- Keep a “tests” section in your file: a few sample calls or sample inputs you can re-run quickly.
- Use self-check questions to confirm you understand why your solution works.
Expected Output vs. Your Output
Some exercises use interactive input, which means your prompts may differ slightly. When comparing results, focus on the computed lines (the final answers). If the exercise says “exact output,” match it exactly. Otherwise, match the meaning.
Exercise 1: Temperature Converter (C ↔ F) with Validation
Task: Write a script that asks the user for a temperature value and a unit (C or F). Convert to the other unit and print the result rounded to 1 decimal place.
Constraints: If the unit is not C or F (case-insensitive), print an error message. If the temperature cannot be parsed as a number, print an error message.
Step-by-step approach:
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
- Read temperature text and unit text.
- Normalize unit with
.strip()and.upper(). - Try converting temperature to
float. - If unit is
C, computeF = C * 9/5 + 32. - If unit is
F, computeC = (F - 32) * 5/9. - Print formatted result with 1 decimal place.
Example run 1 (input): temperature 100, unit C
Expected output:
100.0 C = 212.0 FExample run 2 (input): temperature 32, unit f
Expected output:
32.0 F = 0.0 CExample run 3 (input): temperature ten, unit C
Expected output:
Error: temperature must be a number.Self-check:
- What happens if the user enters
Cwith spaces? - Does your script accept
candCequally? - Do you round correctly to 1 decimal place?
Exercise 2: Password Strength Quick Check
Task: Ask the user for a password and print a simple strength label: weak, ok, or strong.
Rules:
weak: length < 8ok: length ≥ 8 and includes at least one digitstrong: length ≥ 12 and includes at least one digit and at least one uppercase letter
Step-by-step approach:
- Read password string.
- Compute length.
- Scan characters to detect digit and uppercase (you can use
any()with generator expressions). - Apply rules in the correct order (strong first, then ok, then weak).
Example inputs and expected outputs:
Input: hello7 Output: weakInput: password7 Output: okInput: MyLongPassword7 Output: strongSelf-check:
- If the password is 12+ characters but has no digit, what label do you print?
- Do you accidentally label a 7-character password with a digit as
ok? - Are you checking uppercase correctly (not just “not lowercase”)?
Exercise 3: Shopping Receipt with Tax and Tip
Task: Build a small receipt calculator. Ask for three item prices, then ask for tax rate (percent) and tip rate (percent). Print subtotal, tax amount, tip amount, and total. Round money to 2 decimals.
Constraints: If any entered price is negative, print an error message and stop.
Step-by-step approach:
- Read three prices as floats.
- Check for negatives.
- Read tax percent and tip percent as floats.
- Compute subtotal = sum(prices).
- Compute tax = subtotal * tax_percent / 100.
- Compute tip = subtotal * tip_percent / 100.
- Total = subtotal + tax + tip.
- Print each line with 2 decimals.
Example input: prices 10, 5.50, 2.25; tax 8; tip 15
Expected output:
Subtotal: 17.75
Tax: 1.42
Tip: 2.66
Total: 21.83Self-check:
- Are you tipping on subtotal only (not subtotal+tax)?
- Do you format with exactly 2 decimals?
- What happens if the user enters
-1for an item?
Exercise 4: Guess the Number (Limited Attempts)
Task: Create a guessing game where the secret number is fixed (for testing) at 37. The user has 5 attempts to guess. After each wrong guess, print Too low or Too high. If they guess correctly, print You got it! and stop. If they run out of attempts, print Out of attempts. The number was 37.
Constraints: If the user enters something that is not an integer, do not count it as an attempt; print Invalid input and ask again.
Step-by-step approach:
- Set secret = 37.
- Set attempts_left = 5.
- Loop while attempts_left > 0.
- Read guess text, try to parse int.
- If parsing fails: print invalid, continue (attempts_left unchanged).
- If guess == secret: print success and break.
- Otherwise: decrement attempts_left and print hint.
- After loop, if not guessed: print out-of-attempts message.
Example interaction (guesses): 50, abc, 20, 37
Expected output (answer lines):
Too high
Invalid input
Too low
You got it!Self-check:
- Does invalid input reduce attempts? It should not.
- Do you stop immediately after a correct guess?
- Do you print the correct final message when attempts reach 0?
Exercise 5: Build a Mini “Stats” Report from a List of Numbers
Task: Given a list of numbers in your code (not user input), compute and print: count, min, max, sum, and average (rounded to 2 decimals).
Data: Use exactly this list for testing: [3, 7, 7, 2, 9]
Expected output:
Count: 5
Min: 2
Max: 9
Sum: 28
Average: 5.60Self-check:
- Is your average computed as sum/count?
- Do you handle the case of an empty list? (For this exercise, you can add a defensive check and print an error.)
- Are you rounding average to 2 decimals?
Exercise 6: Word Frequency (Ignoring Case and Punctuation)
Task: Given a sentence string in your code, count how many times each word appears. Print the counts sorted by word (alphabetical).
Data: Use: "Hello, hello world! World of Python."
Rules: Treat Hello and hello as the same word. Ignore punctuation characters , ! .
Step-by-step approach:
- Lowercase the string.
- Replace punctuation with spaces (or remove them).
- Split into words.
- Count using a dictionary.
- Print in alphabetical order by key.
Expected output:
hello: 2
of: 1
python: 1
world: 2Self-check:
- Do you accidentally keep empty strings after replacing punctuation?
- Are you sorting by the word, not by the count?
- Does
world!becomeworld?
Exercise 7: Simple Menu Loop (Until Quit)
Task: Create a menu-driven loop that repeatedly asks the user to choose an option: 1 show help, 2 show current time (as a placeholder string), 3 print a random motivational message from a list, q quit.
Constraints: For this exercise, do not use real time or randomness if you don’t want to. You can hard-code the “current time” as 12:00 and select the first message each time. The focus is the loop and branching.
Expected behavior:
- If user enters
1, print a help line. - If user enters
2, printTime: 12:00. - If user enters
3, printMessage: Keep going.(use that exact message for expected output). - If user enters
q, stop the loop. - Otherwise print
Unknown option.
Example inputs: 2, 3, x, q
Expected output:
Time: 12:00
Message: Keep going.
Unknown optionSelf-check:
- Does the loop continue after options 1–3?
- Do you stop only on
q? - Do you handle uppercase
Qif you choose to support it?
Exercise 8: Filename Filter (Keep Only Certain Extensions)
Task: Given a list of filenames, create a new list containing only files ending in .txt or .csv (case-insensitive). Print the filtered list, one per line.
Data: ["notes.TXT", "photo.jpg", "data.csv", "archive.zip", "report.CsV"]
Step-by-step approach:
- Loop through filenames.
- Lowercase each name for checking.
- Use
endswithfor.txtand.csv. - Collect matches into a list.
- Print each match on its own line (original casing preserved).
Expected output:
notes.TXT
data.csv
report.CsVSelf-check:
- Are you checking the end of the string, not “contains”?
- Do you preserve original filename text in output?
- Does
.CsVcount as.csv?
Exercise 9: Dictionary Update from “Transactions”
Task: You have a dictionary of inventory counts and a list of transactions (item, change). Apply each transaction to update the inventory. If an item doesn’t exist, create it starting at 0 before applying the change.
Data:
inventory = {"apple": 5, "banana": 2}
transactions = [("apple", -2), ("banana", 5), ("orange", 3)]Expected output (final inventory printed in alphabetical order):
apple: 3
banana: 7
orange: 3Self-check:
- Do you handle new keys correctly?
- Do you update values rather than replacing them?
- Do you print in sorted key order?
Exercise 10: Log Parser (Count Levels)
Task: Given a list of log lines, count how many are INFO, WARNING, and ERROR. Print counts in this exact order.
Data:
logs = [
"INFO: Start",
"WARNING: Low disk",
"INFO: Running",
"ERROR: Failed",
"INFO: End"
]Rules: The level is the text before the colon. Ignore unknown levels.
Expected output:
INFO: 3
WARNING: 1
ERROR: 1Self-check:
- Are you splitting on the first colon?
- Do you strip spaces around the level?
- What happens if a line has no colon? (You can skip it safely.)
Exercise 11: Build a Reusable “Input Until Valid” Helper
Task: Write a helper function that repeatedly asks for input until it can return a valid integer within a range (inclusive). Then use it to ask for an age between 0 and 120.
Constraints: On invalid input, print a message and ask again. Use these exact messages for testing: Invalid number when parsing fails, and Out of range when the number is outside the range.
Step-by-step approach:
- Define a function like
get_int_in_range(prompt, min_value, max_value). - Inside a loop: read text, try parse int.
- If parse fails: print
Invalid numberand continue. - If value outside range: print
Out of rangeand continue. - Return the valid value.
Example inputs: abc, -5, 200, 25
Expected output (error lines only):
Invalid number
Out of range
Out of rangeThen your program should accept 25 and store it as the age.
Self-check:
- Does the function return only when valid?
- Do you reuse the function instead of writing the loop twice?
- Do you treat 0 and 120 as valid?
Exercise 12: Self-Test Checklist (Debugging Without Guessing)
This final section is not a coding task but a structured self-check you can apply to any small script. Use it after you think you are “done,” especially if your output doesn’t match expected output.
Checklist: Inputs and Edge Cases
- Have you tested the smallest valid input and the largest valid input?
- Have you tested an empty string input (just pressing Enter) where applicable?
- Have you tested invalid types (letters where a number is expected)?
- Have you tested values just outside the allowed range (e.g., -1, max+1)?
Checklist: Output Formatting
- Are you printing extra spaces or missing punctuation?
- Are you rounding numbers as requested (1 decimal vs 2 decimals)?
- Are you printing lines in the required order?
- If sorting is required, are you sorting by the correct key (word vs count)?
Checklist: Logic and Flow
- Are your conditions checked in the correct order (most specific first)?
- Are loops stopping when they should (break conditions)?
- Are you accidentally counting invalid attempts as valid attempts?
- Are you updating variables correctly (incrementing/decrementing in the right place)?
Checklist: Quick “Print Debugging” Technique
If something is wrong and you don’t know why, add temporary prints that show the values your program is using. For example, if your receipt total is wrong, print the subtotal, tax rate, computed tax, tip rate, computed tip, and total before formatting. Once fixed, remove the debug prints so your output matches expected output.
# Example debug prints (remove after fixing)
print("DEBUG subtotal=", subtotal)
print("DEBUG tax=", tax)
print("DEBUG tip=", tip)
print("DEBUG total=", total)Self-check questions to ask yourself:
- Can I explain, in one or two sentences, why each line of output has that value?
- If I change one input, can I predict how the output should change?
- Did I verify behavior with at least 3 different test cases?