Python Program to Add two Numbers using Command Line Arguments

In this article, we will learn about python program to add two numbers using command line arguments.

Getting Started

The task is write a python program that returns sum of two numbers provided as command line arguments.

sys.argv reads input from common line. It is present in sys module in python.

sys.argv[1:3] means read two inputs from command line arguments.

We can do it as below –

 
import sys
a, b = sys.argv[1:3]
print("sum is", float(a) + float(b))

Output:

 
sum is 3.0

Run the program by providing two value using command line arguments. In our case, we provided 1 and 2. So, output is 3.0 .

a, b = sys.argv[1:3] means read two values from command line arguments and store it in variable a and b.

float(a) + float(b): At first both numbers are converted into float numbers. Then, we get sum of float values using + operator.

Returned value is then printed using print() function.

Method 2: Add Numbers using Command Line Arguments

We can omit 2nd value in sys.argv[1:3] and write above program as shown below –

 
import sys
a, b = sys.argv[1:]
print("sum is", float(a) + float(b))

Output:

 
sum is 3.0

a, b = sys.argv[1:] read value from first index in command line arguments and store them in variable a and b.

float(a) and float(b) convert values of variables a and b into float values.

Method 3: Add Numbers using Command Line Arguments

If we want to write above program in more pythonic way, we can do so as shown below –

 
import sys
summ = sum(float(i) for i in sys.argv[1:])
print("sum is", summ)

Output:

 
sum is 3.0

Here, we run a for loop and use built-in function sum() to get sum of two numbers. for loop reads all input from command line. We get summation of all numbers using sum() function. Then, returned value is printed using print() function.

Reference: Official Doc

Learn about more python examples at – https://tutorialwing.com/python-tutorial/

Leave a Reply