Python Practice › sys Module Programs › Program 2
Sum numbers from the command line
Write a Python program that adds the numbers passed as arguments.
Output
19.5
Approach
- Convert each argument with
float().
Solution
import subprocessimport sys with open("add.py", "w") as f: f.write("import sys\nprint(sum(float(a) for a in sys.argv[1:]))\n")out = subprocess.run([sys.executable, "add.py", "10", "2.5", "7"], capture_output=True, text=True)print(out.stdout.strip())Output
19.5
Learn the concept
New to this topic? Read the lesson, then come back.