Practice: Python Application Development

« Read the chapter

Q1. Simple dataclass

BeginnerCoding

Create a dataclass Point with int fields x and y, make Point(2, 3) and print it.

Goal: Use dataclasses.

Q2. Dataclass default

BeginnerCoding

Create a dataclass Book with title and pages (default 100). Print the pages of Book("Py").

Goal: Use field defaults.

Q3. Main guard

BeginnerCoding

Write a main() function that prints Ready and call it with a main guard.

Goal: Use the entry point.

Q4. Parse a number option

IntermediateCoding

Using argparse, parse the list ['--n', '5'] with an int option --n and print n squared.

Goal: Use argparse.

Q5. JSON round trip

IntermediateCoding

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

IntermediateCoding

Using pathlib, write the text hello to note.txt and print the text read back.

Goal: Use pathlib.

Q7. Custom exception

IntermediateCoding

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

AdvancedCoding

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

BeginnerOutput

What does this print?

Code
from dataclasses import dataclass

@dataclass
class P:
    x: int

print(P(1) == P(1))

Goal: Know dataclass methods.

Q10. Name guard

BeginnerOutput

What does this print when the file is run directly?

Code
print(__name__)
if __name__ == "__main__":
    print("direct")

Goal: Understand __name__.

Q11. Default factory

IntermediateOutput

What does this print?

Code
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

IntermediateOutput

What does this print?

Code
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

IntermediateOutput

What does this print?

Code
import json

print(json.dumps({"ok": True, "x": None}))

Goal: Know JSON mapping.

Q14. Custom exception chain

IntermediateOutput

What does this print?

Code
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

IntermediateOutput

What does this print?

Code
from pathlib import Path

p = Path("data/report.final.csv")
print(p.name, p.suffix, p.stem)

Goal: Use pathlib properties.

Q16. Unittest result

AdvancedOutput

What does this print?

Code
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

IntermediateDebugging

This dataclass raises ValueError. Fix it so that Cart().items prints [].

Code
from dataclasses import dataclass

@dataclass
class Cart:
    items: list = []

print(Cart().items)

Goal: Fix mutable defaults.

Q18. Import runs the program

BeginnerDebugging

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).

Code
def main():
    print("Hi")

main()

Goal: Use main guard.

Q19. Argument type bug

IntermediateDebugging

The program should print 10 but raises TypeError. Fix it.

Code
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

BeginnerConceptual

Why is it useful to keep program logic in functions separate from input and printing?

Goal: Design for testing.