Skip to content

Instantly share code, notes, and snippets.

@AnthonyMRodrigues
Last active February 24, 2023 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnthonyMRodrigues/51ba36c9a58c3a5ebb8f4534a3131676 to your computer and use it in GitHub Desktop.
Save AnthonyMRodrigues/51ba36c9a58c3a5ebb8f4534a3131676 to your computer and use it in GitHub Desktop.
Calculator improvement example
# This is a calculator improvement used in the Medium post example.
# Original code without improvements available here: https://github.com/sobolevn/python-code-disasters/blob/master/python/my_first_calculator.py
def calculate(number1: int, number2: int, op_sign: str) -> float:
mapper = {
"+": number1 + number2,
"-": number1 - number2,
"/": number1 / number2,
"*": number1 * number2
}
return mapper[op_sign]
print('Welcome to this calculator!')
print('It can add, subtract, multiply and divide whole numbers.')
try:
num1 = int(input('Please choose your first number: '))
sign = input('What do you want to do? +, -, /, or *: ')
num2 = int(input('Please choose your second number: '))
result = calculate(num1, num2, sign)
print(f"""{num1} {sign} {num2} = {result}""")
except ZeroDivisionError:
print("You can't divide by zero")
except KeyError:
print("Invalid sign")
except ValueError:
print("Invalid input")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment