carmmmm / AutoCoder

Configuration files for GitHub Actions and scripts to interact with ChatGPT
1 stars 2 forks source link

Generate a Simple Calculator in Python #6

Open carmmmm opened 1 month ago

carmmmm commented 1 month ago

Prompt for Code Generation

Please generate a Python script for a simple calculator. The script should include the following features:

  1. Addition: The calculator should be able to add two numbers.
  2. Subtraction: The calculator should be able to subtract one number from another.
  3. Multiplication: The calculator should be able to multiply two numbers.
  4. Division: The calculator should be able to divide one number by another, handling division by zero gracefully.

The script should be saved as calculator.py and should include:

Please make sure the code is well-commented and easy to understand.


The generated file should be named calculator.py.

Labels:

codebyNJ commented 3 weeks ago
# calculator.py

def add(x, y):
    """Add two numbers."""
    return x + y

def subtract(x, y):
    """Subtract the second number from the first number."""
    return x - y

def multiply(x, y):
    """Multiply two numbers."""
    return x * y

def divide(x, y):
    """Divide the first number by the second number, handling division by zero."""
    if y == 0:
        return "Error: Division by zero is not allowed."
    return x / y

def main():
    """Main function to run the calculator."""
    print("Simple Calculator")
    print("Available operations:")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")

    # Get user input for operation
    operation = input("Choose an operation (1/2/3/4): ")

    # Get user input for numbers
    try:
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))
    except ValueError:
        print("Error: Invalid input. Please enter numeric values.")
        return

    # Perform the chosen operation
    if operation == '1':
        print(f"Result: {add(num1, num2)}")
    elif operation == '2':
        print(f"Result: {subtract(num1, num2)}")
    elif operation == '3':
        print(f"Result: {multiply(num1, num2)}")
    elif operation == '4':
        print(f"Result: {divide(num1, num2)}")
    else:
        print("Error: Invalid operation choice.")

if __name__ == "__main__":
    main()