Exercise
Main Function Parameters For Calculator
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 # Importing the sys module to access command line arguments
# Checking if the correct number of arguments are passed
if len(sys.argv) != 4:
print("Usage: calc ") # Print usage if arguments are incorrect
sys.exit(1) # Exit the program with an error code
# Extracting the numbers and operator from the command line arguments
num1 = float(sys.argv[1]) # Convert the first argument to a float (number1)
operator = sys.argv[2] # The operator (+, -, *, /)
num2 = float(sys.argv[3]) # Convert the third argument to a float (number2)
# Performing the operation based on the operator
if operator == '+':
result = num1 + num2 # Perform addition
elif operator == '-':
result = num1 - num2 # Perform subtraction
elif operator == '*':
result = num1 * num2 # Perform multiplication
elif operator == '/':
if num2 == 0:
print("Error: Division by zero is not allowed") # Handle division by zero
sys.exit(1) # Exit the program with an error code
result = num1 / num2 # Perform division
else:
print("Error: Invalid operator") # Handle invalid operator
sys.exit(1) # Exit the program with an error code
# Print the result of the operation
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