Command-line programs · 14 / 15 Exercise Hard

Unit converter

Objective

Create a length unit converter with argparse, using required options with a set of allowed values. The arguments of each test are passed to the program as if you typed them in the terminal (they appear in the test cases).

Instructions

  • Use the dictionary FACTORS with the meters each unit is equal to: m: 1, km: 1000, mi: 1609.344 and ft: 0.3048.
  • Positional argument value (decimal) and required options --from and --to, whose values can only be the dictionary keys (choices=FACTORS). Store them with dest="source" and dest="target".
  • Convert by going to meters and from meters to the target unit. Show value source = result target (the value with :g, the result with 2 decimals).
  • If a required option is missing or a value is not allowed, argparse ends with exit code 2.
Output
5 km = 3.11 mi

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise