Exercise
Main Function Parameters And Return Value For Calculator
Objective
Develop a Python program that performs arithmetic operations such as addition, subtraction, multiplication, or division by analyzing command line arguments. For example, running the program with calc 5 + 379 should calculate the sum. The input must consist of two numbers and an operator, with the allowed operators being +, -, *, or /.
The program should return the following error codes:
1 if the number of arguments is not exactly 3
2 if the second argument is not a valid operator
3 if the first or third argument is not a valid number
0 if the operation is successfully performed
Example Python Exercise
Show Python Code
import sys # Importing the sys module to access command line arguments
# Function to check if a string can be converted to a valid number
def is_valid_number(value):
try:
float(value) # Try to convert the string to a float
return True # If successful, return True
except ValueError:
return False # If conversion fails, return False
# Checking if the correct number of arguments are passed
if len(sys.argv) != 4:
print("Error: Invalid number of arguments.") # Print error message for incorrect number of arguments
sys.exit(1) # Exit with error code 1
# Extracting the numbers and operator from the command line arguments
num1 = sys.argv[1] # First argument (number1 as string)
operator = sys.argv[2] # Second argument (operator)
num2 = sys.argv[3] # Third argument (number2 as string)
# Check if the operator is valid
if operator not in ['+', '-', '*', '/']:
print("Error: Invalid operator.") # Print error message for invalid operator
sys.exit(2) # Exit with error code 2
# Check if both arguments are valid numbers
if not is_valid_number(num1) or not is_valid_number(num2):
print("Error: Invalid number.") # Print error message for invalid number
sys.exit(3) # Exit with error code 3
# Convert the numbers to floats for calculation
num1 = float(num1)
num2 = float(num2)
# 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.") # Handle division by zero
sys.exit(3) # Exit with error code 3
result = num1 / num2 # Perform division
# Print the result of the operation
print(f"The result of {num1} {operator} {num2} is: {result}")
sys.exit(0) # Exit with success code 0
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.
Case 3:
python calc.py 25 & 4
Error: Invalid operator.
Share this Python Exercise