w3resource

Python Simple Calculator Project with Solutions and Explanations


Calculator:

Input: User provides two numbers and selects an operation (addition, subtraction, multiplication, division).

Output: The result of the chosen operation.

Input and output values:

Input values:

Enter the first number: 5

Enter operation (+, -, *, /): +

Enter the second number: 3

Output value: Result: 8

Here are two different solutions for a basic calculator program in Python. Both solutions will accept user input for two numbers and an arithmetic operation (addition, subtraction, multiplication, or division) and then output the result.

Solution 1: Basic Approach using conditional statements

Code:

# Solution 1: Basic Approach Using Conditional Statements

# Get the first number from the user and convert it to a float
first_number = float(input("Enter the first number: "))

# Get the operation from the user (+, -, *, /)
operation = input("Enter operation (+, -, *, /): ")

# Get the second number from the user and convert it to a float
second_number = float(input("Enter the second number: "))

# Initialize a variable to store the result
result = None

# Perform the chosen operation using conditional statements
if operation == '+':
    # Addition
    result = first_number + second_number
elif operation == '-':
    # Subtraction
    result = first_number - second_number
elif operation == '*':
    # Multiplication
    result = first_number * second_number
elif operation == '/':
    # Division; check if the second number is not zero to avoid division by zero
    if second_number != 0:
        result = first_number / second_number
    else:
        # Handle division by zero error
        print("Error: Division by zero is not allowed.")
else:
    # Handle invalid operations
    print("Error: Invalid operation.")

# Print the result if a valid operation was performed
if result is not None:
    print(f"Result: {result}")

Output:

Enter the first number: 12
Enter operation (+, -, *, /): +
Enter the second number: 33
Result: 45.0
Enter the first number: 5
Enter operation (+, -, *, /): *
Enter the second number: 7
Result: 35.0
Enter the first number: 120
Enter operation (+, -, *, /): /
Enter the second number: 13
Result: 9.23076923076923
Enter the first number: 34
Enter operation (+, -, *, /): -
Enter the second number: 8
Result: 26.0

Explanation:

  • Uses if-elif-else statements to check the user's chosen operation and perform the corresponding arithmetic calculation.
  • Takes user input for two numbers and the desired operation, converts the numbers to floats, and checks for errors such as division by zero or an invalid operation.
  • This solution is straightforward but can become lengthy if more operations are added.

Solution 2: Using a Dictionary and Functions for Cleaner Code

Code:

# Solution 2: Using a Dictionary and Functions for Cleaner Code

# Define functions for each arithmetic operation
def add(x, y):
    """Function to perform addition"""
    return x + y

def subtract(x, y):
    """Function to perform subtraction"""
    return x - y

def multiply(x, y):
    """Function to perform multiplication"""
    return x * y

def divide(x, y):
    """Function to perform division, checks for division by zero"""
    if y == 0:
        return "Error: Division by zero is not allowed."
    return x / y

# Map operations to their corresponding functions using a dictionary
operations = {
    '+': add,
    '-': subtract,
    '*': multiply,
    '/': divide
}

# Get user input for the first number, operation, and second number
first_number = float(input("Enter the first number: "))
operation = input("Enter operation (+, -, *, /): ")
second_number = float(input("Enter the second number: "))

# Check if the chosen operation is valid
if operation in operations:
    # Retrieve the function corresponding to the chosen operation
    result = operations[operation](first_number, second_number)
    print(f"Result: {result}")
else:
    # Handle invalid operations
    print("Error: Invalid operation.")

Output:

Enter the first number: 12
Enter operation (+, -, *, /): +
Enter the second number: 33
Result: 45.0
Enter the first number: 5
Enter operation (+, -, *, /): *
Enter the second number: 7
Result: 35.0
Enter the first number: 120
Enter operation (+, -, *, /): /
Enter the second number: 13
Result: 9.23076923076923
Enter the first number: 34
Enter operation (+, -, *, /): -
Enter the second number: 8
Result: 26.0

Explanation:

  • Defines separate functions for each arithmetic operation (add, subtract, multiply, divide).
  • Uses a dictionary to map user inputs (+, -, *, /) to the corresponding functions.
  • When the user inputs an operation, the corresponding function is called from the dictionary, making the code more modular, organized, and easier to extend.
  • Handles errors such as division by zero and invalid operations in a clean, centralized way.

Note:
Both solutions accomplish the task, but Solution 2 is more modular, making it easier to maintain and extend for future improvements or additional operations.



Follow us on Facebook and Twitter for latest update.