Capstone Review: Python Skills Check
Assess your Python skills through integrated problems covering data types, collections, functions, validation, exceptions, and unit testing.
In this lesson, you will learn
- ✓Apply variables, conditions, loops, and functions to solve practical problems.
- ✓Choose suitable Python collections and process their contents correctly.
- ✓Write functions that validate input and handle boundary cases.
- ✓Trace execution and predict exact output, including return values and exceptions.
- ✓Test normal and invalid behavior with assertions and unittest.
- ✓Combine core Python concepts into a small, maintainable task-summary program.
1. Skills check: Understand the data before writing code
A reliable solution starts by identifying its input, output, and rules. Before writing a loop or choosing a collection, determine what the data represents and what result is required.
Python lists are useful when order matters or items may be repeated. Dictionaries associate keys with values. Sets store distinct hashable elements. Tuples are useful for fixed groups of values. Choosing a suitable data structure makes the solution simpler.
Consider a task tracker. Each task can be represented by a dictionary, and all tasks can be stored in a list. A completed field can be a Boolean. You can use a loop to count completed tasks, a condition to validate titles, and a function to separate the calculation from the rest of the application.
Summarize a collection of task records
The list contains three task dictionaries, so len(tasks) returns 3. The generator expression produces one for each task whose completed field is truthy. Here, the field contains Boolean values. Two tasks are completed, so subtracting two from three gives one pending task. The code combines lists, dictionaries, Boolean conditions, a generator expression, arithmetic, and print.
Note
2. Functions, validation, and return values
A function should have a clear responsibility, a meaningful name, and a well-defined result. Parameters provide input, return sends a result back to the caller, and exceptions communicate that an operation could not be completed under the function's rules.
A function can return a dictionary containing multiple related values. Returning a result is different from printing it: a returned value can be stored, tested, transformed, or passed to another function.
Validation should match the requirements. If a function accepts a list of numeric scores, for example, it should decide what to do with an empty list. It should not silently divide by zero or invent a meaningful average where none exists.
Validate and summarize numeric scores
The first call validates the list, computes its total, and divides by the number of scores. The average is 20.0 because the division operator / produces a float for these operands. The empty-list case returns an explicit result with average set to None because no average exists for zero values. The validation excludes Boolean values explicitly. In Python, bool is a subclass of int, so isinstance(True, int) is True. The example assumes scores is a list or another suitable iterable supporting truth testing and len. A production function may need more explicit input-type validation.
Caution
3. Collections, loops, and common data problems
Many practical problems require filtering, counting, searching, or grouping data. A loop makes the processing steps explicit, while a comprehension can express a straightforward transformation concisely.
Use a set when you need distinct values, but remember that sets do not preserve a meaningful sorted order. If output order matters, sort the values explicitly. Use dictionary membership to check keys and the in operator on a list to check whether an element exists.
When processing dictionaries, avoid assuming that every record has every expected key unless your program controls and validates the data. A missing key can raise KeyError. The get method is useful when a missing key has a sensible default, but it should not hide invalid data that ought to be rejected.
Count words and list unique words
split() separates the sentence into whitespace-delimited words. The dictionary stores each word's count. get(word, 0) supplies zero for a word not yet present. set(words) removes duplicate words, and sorted(...) returns a sorted list. The sentence contains eight words, not nine. Count the tokens carefully before trusting an expected output.
Note
4. Exceptions and defensive programming
An exception signals that an operation cannot proceed normally. ValueError is commonly used when a value has the right general type but is unacceptable. TypeError is appropriate when an operation receives a value of an unsuitable type.
A try/except block lets a program respond to a known failure. Catch specific exceptions when possible. Catching every exception and silently ignoring it can conceal programming defects and make debugging harder.
For command-line input, int(input(...)) can raise ValueError if the user enters text that is not an integer. Handle that expected problem close to the input operation, and decide what the user should see or do next.
Convert a task ID safely
The string "12" can be converted to the integer 12. The string "abc" cannot be converted to an integer, so int raises ValueError. The function raises a clearer ValueError with a message that describes the required input. The outer try/except catches that expected exception and prints its message. A string representing zero or a negative integer is rejected by the separate positive-value check.
Caution
5. Combine the skills in a task-summary function
Now combine the concepts into a small program. The function below accepts a list of task dictionaries and calculates total, completed, and pending counts. It validates the required structure rather than silently treating malformed records as valid tasks.
This example deliberately keeps the function independent of input() and print(). Separating calculations from user interaction makes the function easier to reuse and test.
For simplicity, the function requires a list and requires each task to be a dictionary containing a Boolean completed field. It does not validate every possible field used by a full task tracker; validation should match the interface and data guarantees of the actual application.
Build a validated task summary
The function first validates the outer list. Each task must be a dictionary with a completed field whose value is a Boolean. The loop increments completed_count only for tasks marked True. The pending count is the total minus the completed count. An empty list is valid and produces zero for all three counts.
Note
6. Test the integrated function
A skills check should include verification, not just implementation. Tests should cover an ordinary case, an empty collection, and invalid input. Each test should have a clear expectation that can be evaluated independently.
The following example uses unittest. The tests exercise the summary function directly without relying on console output. That makes them less fragile than tests that compare an entire interactive session.
Unit tests for the task summary
| .... |
|---|
| Ran 4 tests |
OK
The first test verifies counts for a mixed list. The second checks the empty-list boundary case. The third confirms that a missing required field is rejected. The fourth confirms that a string such as "yes" is not silently accepted as a Boolean status. The output is representative of a successful unittest run. Timing and exact formatting may vary.
Note
7. Problem-solving checklist
When facing an unfamiliar Python problem, use a repeatable process instead of immediately writing code. First restate the problem in your own words. Identify the input and required output. Work through a small example manually, including an edge case.
Next, choose a suitable data structure and outline the steps. Implement the smallest correct solution, then test it against your manual examples. Finally, consider empty input, invalid values, duplicate items, and performance if those conditions matter to the requirements.
If the code is hard to explain, simplify it. A straightforward loop with clear names is often preferable to a compact expression that you cannot confidently trace.
A repeatable approach to a coding problem
The steps apply to beginner exercises and larger projects. The process is iterative. If a test reveals a wrong assumption, revisit the requirement or design rather than blindly patching the code.
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Writing code before understanding the required output.
Why it happens: Translate the requirement into expected inputs, outputs, and edge cases before coding so the implementation solves the right problem.
Key takeaway: Write down the input, expected result, and important rules before implementing the solution.
#2 Confusing a function's return value with what it prints.
Why it happens: return sends data back to the caller, while print() displays text; callers cannot reuse printed text as a returned value.
Key takeaway: Check whether the function returns a value, prints a value, or does both. Store and test return values directly where possible.
#3 Assuming an empty collection behaves like a non-empty collection.
Why it happens: Empty lists, dictionaries, strings, and other collections often require explicit handling because indexing or iteration assumptions may not hold.
Key takeaway: Check whether indexing, division, or aggregation requires special handling for empty input.
#4 Treating every false-like value as invalid.
Why it happens: Falsy values such as 0, False, None, and an empty string can be valid domain values; validate according to the requirement rather than truthiness alone.
Key takeaway: Validate against the actual requirement. Zero, False, an empty string, and an empty list have different meanings in different contexts.
#5 Using dictionary keys without checking whether they exist.
Why it happens: Dictionary access by a missing key can raise KeyError, so validate keys or use a suitable default when absence is possible.
Key takeaway: Validate required fields or use get with an intentional default when missing keys are acceptable.
#6 Catching every exception and continuing silently.
Why it happens: Silently catching every exception hides the cause of a failure and may allow invalid state to continue through the program.
Key takeaway: Catch specific expected exceptions and give the caller a clear recovery path. Do not hide unexpected defects.
#7 Checking only the ordinary case.
Why it happens: Boundary cases and invalid inputs often reveal defects missed by the ordinary case, so include them in the test plan.
Key takeaway: Test empty input, boundary values, and invalid input when relevant to the function's contract.
#8 Assuming passing tests prove that all bugs have been eliminated.
Why it happens: Passing tests raises confidence for covered behavior but cannot prove all possible inputs and environments are bug-free.
Key takeaway: Treat tests as evidence for the scenarios they cover and review the remaining requirements and untested conditions.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:How do you approach an unfamiliar programming problem?
Q2:What is the difference between a list and a set?
Q3:What is the difference between return and print?
Q4:How would you handle an empty collection when calculating an average?
Q5:What is the difference between ValueError and TypeError?
Q6:Why are small functions helpful?
Q7:How would you test a task-summary function?
Q8:What does a passing test suite tell you?
Q9:How can you make a Python program easier to maintain?
Q10:Why is input validation important in a CLI application?
Key takeaways
- A strong Python solution starts with a clear understanding of the input, output, and requirements.
- Choose lists, dictionaries, sets, and tuples according to the problem's needs.
- Use functions to isolate responsibilities and return values that callers can reuse and test.
- Define how empty collections and invalid values should behave.
- Handle expected exceptions specifically and avoid silently hiding defects.
- Test ordinary behavior, boundary cases, and invalid data where appropriate.
- Passing tests provides evidence for tested cases, not proof that every possible defect has been eliminated.
- Combine implementation, validation, testing, and clear code to make a small project dependable.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: