Objective
Develop a Python program that performs basic arithmetic operations such as addition, subtraction, multiplication, or division based on command line inputs. For example, running the program with calc 5 + 379 will compute the sum. The input must consist of two numbers and an operator, with allowed operators being +, -, *, or /. The program will analyze the command line parameters to determine the appropriate operation.
Example Python Exercise
Show Python Code
import sys
if len(sys.argv) != 4:
print("Usage: calc ")
sys.exit(1)
num1 = float(sys.argv[1])
operator = sys.argv[2]
num2 = float(sys.argv[3])
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("Error: Division by zero is not allowed")
sys.exit(1)
result = num1 / num2
else:
print("Error: Invalid operator")
sys.exit(1)
print(f"The result of {num1} {operator} {num2} is: {result}")
Output
Case 1:
python calc.py 5 + 379
The result of 5.0 + 379.0 is: 384.0
Case 2:
python calc.py 10 / 0
Error: Division by zero is not allowed
Case 3:
python calc.py 25 * 4
The result of 25.0 * 4.0 is: 100.0
Share this Python Exercise