Skip to content
PythonAlgorithms and Capstone Practicebeginner40 min read

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

Summarize a collection of task records
python
tasks = [
{"id": 1, "title": "Learn lists", "completed": True},
{"id": 2, "title": "Practice functions", "completed": False},
{"id": 3, "title": "Review errors", "completed": True},
]
 
total = len(tasks)
completed_count = sum(
1 for task in tasks if task["completed"]
)
pending_count = total - completed_count
 
print("Total:", total)
print("Completed:", completed_count)
print("Pending:", pending_count)
Output
Total: 3 Completed: 2 Pending: 1

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

This summary assumes each task has a completed field containing a Boolean value. If records come from an external source, validate their structure before relying on those fields.

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

Validate and summarize numeric scores
python
def summarize_scores(scores):
"""Return count, total, and average for numeric scores."""
if not scores:
return {
"count": 0,
"total": 0,
"average": None,
}
 
if any(
isinstance(score, bool)
or not isinstance(score, (int, float))
for score in scores
):
raise TypeError("All scores must be numbers")
 
total = sum(scores)
return {
"count": len(scores),
"total": total,
"average": total / len(scores),
}
 
print(summarize_scores([10, 20, 30]))
print(summarize_scores([]))
Output
{'count': 3, 'total': 60, 'average': 20.0} {'count': 0, 'total': 0, 'average': None}

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

Do not use a truthiness check to validate every kind of input. For example, zero and an empty string are both false in a Boolean context, but whether they are valid depends on the function's requirements.

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

Count words and list unique words
python
sentence = "python makes practice useful and python makes learning practical"
words = sentence.split()
 
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
 
unique_words = sorted(set(words))
 
print("Word count:", len(words))
print("Python count:", word_counts["python"])
print("Unique words:", unique_words)
Output
Word count: 9 Python count: 2 Unique words: ['and', 'learning', 'makes', 'practical', 'practice', 'practical', 'python', 'useful']

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

Use this section to practice tracing a collection through every loop iteration. Verify counts from the actual input rather than memorizing an output.

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

Convert a task ID safely
python
def parse_task_id(text):
try:
task_id = int(text)
except ValueError:
raise ValueError("Task ID must be an integer") from None
 
if task_id <= 0:
raise ValueError("Task ID must be positive")
 
return task_id
 
print(parse_task_id("12"))
 
try:
parse_task_id("abc")
except ValueError as error:
print(error)
Output
12 Task ID must be an integer

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

Avoid catching Exception for routine validation unless you have a specific reason. Unexpected exceptions may indicate defects that should not be hidden.

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

Build a validated task summary
python
def summarize_tasks(tasks):
"""Return total, completed, and pending task counts."""
if not isinstance(tasks, list):
raise TypeError("tasks must be a list")
 
completed_count = 0
for task in tasks:
if not isinstance(task, dict):
raise TypeError("each task must be a dictionary")
if "completed" not in task:
raise ValueError("each task needs a completed field")
if not isinstance(task["completed"], bool):
raise TypeError("completed must be a Boolean")
if task["completed"]:
completed_count += 1
 
total = len(tasks)
return {
"total": total,
"completed": completed_count,
"pending": total - completed_count,
}
 
tasks = [
{"id": 1, "title": "Learn Python", "completed": True},
{"id": 2, "title": "Write tests", "completed": False},
{"id": 3, "title": "Review code", "completed": True},
]
 
print(summarize_tasks(tasks))
print(summarize_tasks([]))
Output
{'total': 3, 'completed': 2, 'pending': 1} {'total': 0, 'completed': 0, 'pending': 0}

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

This function raises exceptions for malformed input. A command-line application can catch those exceptions at its input or application boundary and present a useful message.

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

Unit tests for the task summary
python
import unittest
 
def summarize_tasks(tasks):
if not isinstance(tasks, list):
raise TypeError("tasks must be a list")
completed_count = 0
for task in tasks:
if not isinstance(task, dict):
raise TypeError("each task must be a dictionary")
if "completed" not in task:
raise ValueError("each task needs a completed field")
if not isinstance(task["completed"], bool):
raise TypeError("completed must be a Boolean")
if task["completed"]:
completed_count += 1
total = len(tasks)
return {
"total": total,
"completed": completed_count,
"pending": total - completed_count,
}
 
class TestSummarizeTasks(unittest.TestCase):
def test_mixed_tasks(self):
tasks = [
{"completed": True},
{"completed": False},
{"completed": True},
]
self.assertEqual(
summarize_tasks(tasks),
{"total": 3, "completed": 2, "pending": 1},
)
 
def test_empty_list(self):
self.assertEqual(
summarize_tasks([]),
{"total": 0, "completed": 0, "pending": 0},
)
 
def test_rejects_missing_completed_field(self):
with self.assertRaises(ValueError):
summarize_tasks([{"title": "Missing status"}])
 
def test_rejects_non_boolean_status(self):
with self.assertRaises(TypeError):
summarize_tasks([{"completed": "yes"}])
 
if __name__ == "__main__":
unittest.main()
Output
Result Table
....
Ran 4 tests
1 row returned1 column

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

In a real project, keep the implementation in the application module and the tests in a separate test module. This example keeps them together to make the skills-check logic easy to read.

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

A repeatable approach to a coding problem
text
1. Understand the requirement.
2. Identify input, output, and constraints.
3. Work through a small example by hand.
4. Choose the appropriate data structure.
5. Write a clear implementation.
6. Test normal and boundary cases.
7. Investigate failures and correct the cause.
8. Refactor only when clarity or maintainability improves.
Output
A structured process for solving and verifying Python problems.

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.

Incorrect Approach
script.py
python
Writing code before understanding the required output.
Correct Solution
script.py
python
Write down the input, expected result, and important rules before implementing the solution.

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.

Incorrect Approach
script.py
python
Confusing a function's return value with what it prints.
Correct Solution
script.py
python
Check whether the function returns a value, prints a value, or does both. Store and test return values directly where possible.

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.

Incorrect Approach
script.py
python
Assuming an empty collection behaves like a non-empty collection.
Correct Solution
script.py
python
Check whether indexing, division, or aggregation requires special handling for empty input.

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.

Incorrect Approach
script.py
python
Treating every false-like value as invalid.
Correct Solution
script.py
python
Validate against the actual requirement. Zero, False, an empty string, and an empty list have different meanings in different contexts.

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.

Incorrect Approach
script.py
python
Using dictionary keys without checking whether they exist.
Correct Solution
script.py
python
Validate required fields or use get with an intentional default when missing keys are acceptable.

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.

Incorrect Approach
script.py
python
Catching every exception and continuing silently.
Correct Solution
script.py
python
Catch specific expected exceptions and give the caller a clear recovery path. Do not hide unexpected defects.

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.

Incorrect Approach
script.py
python
Checking only the ordinary case.
Correct Solution
script.py
python
Test empty input, boundary values, and invalid input when relevant to the function's contract.

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.

Incorrect Approach
script.py
python
Assuming passing tests prove that all bugs have been eliminated.
Correct Solution
script.py
python
Treat tests as evidence for the scenarios they cover and review the remaining requirements and untested conditions.

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.

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?
Answer:
I clarify the requirements, identify inputs and outputs, work through a small example, choose an appropriate data structure, implement a clear solution, and verify it with normal and boundary cases.
Q2:What is the difference between a list and a set?
Answer:
A list preserves element order and can contain duplicates. A set stores distinct hashable elements and is useful for membership checks and deduplication. A set does not guarantee the sorted order of its elements.
Q3:What is the difference between return and print?
Answer:
return provides a result to the caller and ends the function call. print displays text to the console. A function can print without returning a useful value, and it can return a value without printing it.
Q4:How would you handle an empty collection when calculating an average?
Answer:
I would define the expected behavior explicitly, such as returning None or raising an appropriate exception. I would avoid dividing by zero and add a test for the empty case.
Q5:What is the difference between ValueError and TypeError?
Answer:
TypeError commonly indicates that a value has an inappropriate type for an operation. ValueError commonly indicates that a value has an acceptable general type but an unacceptable value, such as converting a non-integer string with int.
Q6:Why are small functions helpful?
Answer:
Small functions have focused responsibilities, are easier to name and explain, and can often be tested independently. They also make it easier to reuse logic without copying it.
Q7:How would you test a task-summary function?
Answer:
I would test an ordinary list with a known mixture of completed and pending tasks, an empty list, and malformed records if the function promises to validate them. I would compare the actual returned dictionary with the expected dictionary.
Q8:What does a passing test suite tell you?
Answer:
It tells you that the tested cases passed their assertions. It does not prove that every possible input, integration path, or environment will work correctly.
Q9:How can you make a Python program easier to maintain?
Answer:
Use descriptive names, focused functions, explicit input validation, meaningful exception handling, tests for important behavior, and accurate documentation.
Q10:Why is input validation important in a CLI application?
Answer:
Users may enter unexpected values. Validation lets the application reject invalid input deliberately and provide understandable feedback rather than crashing or silently modifying the wrong data.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: