In this article, we will learn about python program to subtract two numbers using command line arguments with example.
Getting Started
The task is to –
- Accept two numbers as input from user using command line arguments.
- Subtract second number from first numbers.
- Print result after subtraction.
Using User Input (Command Line Arguments)
We can use sys.argv present in sys module in python to accept input from user using command line arguments. Then, subtract those numbers using – operator.
-
Method 1
y1, y2 = sys.argv[1:3] reads two input from user and store them in variable y1 and y2.
int() and float() method type cast input into integer and float respectively.
import sys y1, y2 = sys.argv[1:3] print("Result:", int(y1) - float(y2))
Output:
Result: 39.88
Run above code with command line arguments as 45 and 5.12.
-
Method 2
y1, y2 = sys.argv[1:] reads input from user and store them in variable y1 and y2. Note that omitting second argument in sys.argv means it will read all input starting from 1st index.
import sys y1, y2 = sys.argv[1:] print("Result:", int(y1) - float(y2))
Output:
Result: 39.88
Run above code with command line arguments as 45 and 5.12.
That’s how we can write python program to subtract two numbers using command line arguments with examples.
Reference: Subtraction
Learn about more python examples at – https://tutorialwing.com/python-tutorial/