Main Function Parameters and Return Value for Calculator - Python Programming Exercise

In this exercise, you will develop a Python program that performs arithmetic operations such as addition, subtraction, multiplication, or division by analyzing command line arguments. This exercise is perfect for practicing command-line input handling, arithmetic operations, and error handling in Python. By implementing this program, you will gain hands-on experience in handling command-line input, performing arithmetic operations, and using error handling in Python. This exercise not only reinforces your understanding of command-line input handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Mastering Functions

 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

 Copy 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

 More Python Programming Exercises of Mastering Functions

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Function to Find Array's Min and Max Values

    In this exercise, you will develop a Python program that defines a function to find the smallest and largest numbers in a list. The function should accept the list as...

  •  Recursive Function to Invert a Sequence

    In this exercise, you will develop a Python program that utilizes recursion to reverse a sequence of characters. This exercise is perfect for practicing functi...

  •  Function to Display a Rectangle

    In this exercise, you will develop a Python program that defines a function to print a filled rectangle on the screen, where the dimensions (width and height) are pro...

  •  Iterative Palindrome Function

    In this exercise, you will develop a Python program with an iterative function to check if a string is a palindrome (symmetric). This exercise is perfect for p...

  •  Recursive Palindrome Function

    In this exercise, you will develop a Python program with a recursive function to determine if a string is symmetric (a palindrome). This exercise is perfect fo...

  •  Function FindMinMax

    In this exercise, you will develop a Python program with a function called "FindRange", where the user is prompted to input a minimum value (a number) and a maximum v...