Last active
February 24, 2023 18:10
-
-
Save AnthonyMRodrigues/51ba36c9a58c3a5ebb8f4534a3131676 to your computer and use it in GitHub Desktop.
Calculator improvement example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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