Code Generator
The goal of this app is to create a basic calculator that can perform basic operations: addition, subtraction,
multiplication and division.
Prompt #1:
Create a function that performs basic operations: Addition, subtraction, multiplication and division.
Response:
def calculator(a, b, operation):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
return a / b
Prompt #2:
Create a simple calculator program in Python that asks the user to input two numbers and choose
an operation (add, subtract, multiply, divide). The program should print the result and handle
division by zero.
def calculator():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
operation = input("Choose operation (add, subtract, multiply, divide): ")
if operation == "add":
print("Result:", a + b)
elif operation == "subtract":
print("Result:", a - b)
elif operation == "multiply":
print("Result:", a * b)
elif operation == "divide":
if b != 0:
print("Result:", a / b)
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid operation.")
calculator()
Prompt #3:
Improve this calculator so that it keeps running until the user decides to exit. Include clear
instructions, input validation and formatted output.
def calculator():
print("=== Basic Calculator ===")
while True:
try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
operation = input("Choose operation (+, -, *, /) or 'q' to quit: ")
if operation == 'q':
print("Goodbye!")
break
elif operation == '+':
print(f"Result: {a} + {b} = {a + b}")
elif operation == '-':
print(f"Result: {a} - {b} = {a - b}")
elif operation == '*':
print(f"Result: {a} * {b} = {a * b}")
elif operation == '/':
if b == 0:
print("Error: Division by zero.")
else:
print(f"Result: {a} / {b} = {a / b}")
else:
print("Invalid operation. Please try again.")
except ValueError:
print("Invalid input. Please enter numbers only.")
calculator()
Reflection:
Through this activity, based on redacting prompts, I learned that providing specific instructions in this
code generator enhances the quality of the desired code. By having a better organization, it allows us to
guide the AI to create a program functional and useful.