Automated code generation assistant Python
👤 Sharing: AI
```python
# Automated Code Generation Example: Simple Calculator in Python
# Function to add two numbers
def add(x, y):
"""This function adds two numbers together.
Args:
x: The first number.
y: The second number.
Returns:
The sum of x and y.
"""
return x + y
# Function to subtract two numbers
def subtract(x, y):
"""This function subtracts the second number from the first.
Args:
x: The first number.
y: The second number.
Returns:
The difference between x and y (x - y).
"""
return x - y
# Function to multiply two numbers
def multiply(x, y):
"""This function multiplies two numbers together.
Args:
x: The first number.
y: The second number.
Returns:
The product of x and y.
"""
return x * y
# Function to divide two numbers
def divide(x, y):
"""This function divides the first number by the second.
Args:
x: The dividend (the number to be divided).
y: The divisor (the number to divide by).
Returns:
The quotient (the result of the division). Returns an error message if y is zero.
"""
if y == 0:
return "Error! Division by zero is not allowed."
else:
return x / y
# Main program loop
while True:
# Get user input for the operation
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit") # Added option to exit
choice = input("Enter choice(1/2/3/4/5): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue # Go back to the beginning of the loop
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
elif choice == '5':
print("Exiting the calculator.")
break # Exit the loop and end the program
else:
print("Invalid input. Please enter a number between 1 and 5.")
```
Key improvements and explanations:
* **Clear Function Definitions:** Each operation (add, subtract, multiply, divide) has its own well-defined function. This makes the code more modular, readable, and reusable. Includes comprehensive docstrings to explain what each function does, its arguments, and what it returns.
* **Error Handling (Division by Zero):** Crucially, the `divide` function now checks for division by zero. Instead of crashing, it prints an informative error message.
* **Input Validation:** The code now includes a `try-except` block to handle potential `ValueError` exceptions that can occur if the user enters non-numeric input. This prevents the program from crashing and provides a helpful error message. The `continue` statement sends the program back to the top of the `while` loop if invalid input is detected.
* **User-Friendly Interface:** The program provides clear instructions to the user and presents the results in an easy-to-understand format.
* **Exit Option:** The program now includes an option to exit the calculator, making it a more complete and usable program. Uses `break` to exit the `while` loop.
* **Input Type Conversion:** The `input()` function returns strings. The code now uses `float()` to convert the input strings to floating-point numbers, allowing for decimal values.
* **Docstrings:** Includes documentation strings (docstrings) for each function to explain its purpose, arguments, and return value. This is essential for good code readability and maintainability.
* **Code Clarity:** The code is formatted consistently and uses meaningful variable names, making it easier to understand.
* **Comprehensive Comments:** The code is well-commented to explain each step of the process. This is especially helpful for understanding the logic of the program.
* **`if choice in ('1', '2', '3', '4')`:** This is a cleaner way to check if the user's choice is valid. It avoids multiple `or` conditions.
* **`elif` Chain:** Using `elif` (else if) makes the logic more efficient. Once a condition is met, the remaining `elif` conditions are skipped.
* **No Global Variables (Preferable):** The code avoids using global variables, which are generally discouraged in favor of passing data between functions.
How to run the code:
1. **Save:** Save the code as a `.py` file (e.g., `calculator.py`).
2. **Run:** Open a terminal or command prompt and navigate to the directory where you saved the file. Then, run the program using the command `python calculator.py`.
3. **Interact:** Follow the prompts to enter numbers and choose operations.
4. **Exit:** Choose option 5 to exit the calculator.
This improved version is much more robust, user-friendly, and adheres to good programming practices.
👁️ Viewed: 6
Comments