Practice: Python Application Development
Q1. Simple dataclass
Create a dataclass Point with int fields x and y, make Point(2, 3) and print it.
Goal: Use dataclasses.
Q2. Dataclass default
Create a dataclass Book with title and pages (default 100). Print the pages of Book("Py").
Goal: Use field defaults.
Q3. Main guard
Write a main() function that prints Ready and call it with a main guard.
Goal: Use the entry point.
Q4. Parse a number option
Using argparse, parse the list ['--n', '5'] with an int option --n and print n squared.
Goal: Use argparse.
Q5. JSON round trip
Convert {'a': 1, 'b': [2, 3]} to JSON text and back to a dictionary. Print the dictionary.
Goal: Use json.
Q6. Write and read a file
Using pathlib, write the text hello to note.txt and print the text read back.
Goal: Use pathlib.
Q7. Custom exception
Define class NegativeError(ValueError). Raise it in a try block and print Caught: negative in the except block.
Goal: Create exceptions.
Q8. Logging to stdout
Configure logging to stdout at WARNING level with format LEVEL: message. Log an info and a warning message, so only the warning is printed.
Goal: Use logging levels.
Q9. Dataclass equality
What does this print?
from dataclasses import dataclass
@dataclass
class P:
x: int
print(P(1) == P(1))Goal: Know dataclass methods.
Q10. Name guard
What does this print when the file is run directly?
print(__name__)
if __name__ == "__main__":
print("direct")Goal: Understand __name__.
Q11. Default factory
What does this print?
from dataclasses import dataclass, field
@dataclass
class Box:
items: list = field(default_factory=list)
a = Box()
b = Box()
a.items.append(1)
print(b.items)Goal: Avoid shared defaults.
Q12. argparse default
What does this print?
import argparse
p = argparse.ArgumentParser()
p.add_argument("--level", type=int, default=3)
print(p.parse_args([]).level)Goal: Use argparse defaults.
Q13. json types
What does this print?
import json
print(json.dumps({"ok": True, "x": None}))Goal: Know JSON mapping.
Q14. Custom exception chain
What does this print?
class AppError(Exception):
pass
def run():
raise AppError("failed")
try:
run()
except ValueError:
print("value")
except AppError:
print("app")
finally:
print("end")Goal: Trace exception handling.
Q15. Path parts
What does this print?
from pathlib import Path
p = Path("data/report.final.csv")
print(p.name, p.suffix, p.stem)Goal: Use pathlib properties.
Q16. Unittest result
What does this print?
import unittest
class T(unittest.TestCase):
def test_a(self):
self.assertEqual(1 + 1, 2)
def test_b(self):
self.assertEqual(2 * 2, 5)
r = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(T).run(r)
print(r.testsRun, len(r.failures))Goal: Read test results.
Q17. Mutable default error
This dataclass raises ValueError. Fix it so that Cart().items prints [].
from dataclasses import dataclass
@dataclass
class Cart:
items: list = []
print(Cart().items)Goal: Fix mutable defaults.
Q18. Import runs the program
Importing this module also starts the program. Fix it so that the call only happens when run directly (the fixed file prints Hi when run).
def main():
print("Hi")
main()Goal: Use main guard.
Q19. Argument type bug
The program should print 10 but raises TypeError. Fix it.
import argparse
p = argparse.ArgumentParser()
p.add_argument("--n")
args = p.parse_args(["--n", "5"])
print(args.n * 2 + 0)
print(args.n + 5)Goal: Convert argument types.
Q20. Why separate logic
Why is it useful to keep program logic in functions separate from input and printing?
Goal: Design for testing.