100 days of code: Day 11 - command line arguments

Last modified on 2020-06-19

Source: 100-days-of-code

I can pass command line arguments to my programs using Python’s built-in sys module and its argv function. Running sys.argv in a program creates a list of all the elements entered at the command prompt when the program is run, and those elements can be accessed and put to use like any other list in Python.

I made a program - lbs2kg - that takes an argument of some number measured in pounds and converts to kilograms …

#!/usr/bin/env python3
# Convert pounds to kilograms.
import sys

# Usage: lbs2kg [number]
pounds = float(sys.argv[1])
kilograms = pounds * 0.4535924
print(f"{pounds}lbs = {kilograms:.1f}kg")

Run …

$ lbs2kg.py 145
145lbs = 65.8kg

Command lbs2kg starts the list at sys.argv[0] and 145 is accessed at sys.argv[1] and assigned to the variable pounds.

Happy hacking!