Skip to content

Instantly share code, notes, and snippets.

@hbisneto
Created July 6, 2023 23:44
Show Gist options
  • Select an option

  • Save hbisneto/e5e94b57dcc89f6c1ec5b119a877bd40 to your computer and use it in GitHub Desktop.

Select an option

Save hbisneto/e5e94b57dcc89f6c1ec5b119a877bd40 to your computer and use it in GitHub Desktop.
Calculator with history of calculations. This code was generated via Artificial Intelligence
class Calculator:
def __init__(self):
self.history = []
def add(self, x, y):
result = x + y
self.history.append(f"{x} + {y} = {result}")
return result
def subtract(self, x, y):
result = x - y
self.history.append(f"{x} - {y} = {result}")
return result
def multiply(self, x, y):
result = x * y
self.history.append(f"{x} * {y} = {result}")
return result
def divide(self, x, y):
if y == 0:
print("Error: Cannot divide by zero")
return None
else:
result = x / y
self.history.append(f"{x} / {y} = {result}")
return result
def save_history(self, filename):
with open(filename, 'w') as f:
for calculation in self.history:
f.write(calculation + '\n')
calc = Calculator()
calc.add(2, 3)
calc.subtract(5, 1)
calc.multiply(6, 4)
calc.divide(8, 2)
calc.save_history('history.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment