Hey, everyone!
I just learned Python and found the coolest simplest project I had to build from scratch-a basic calculator. The real apps that are developed could be a little more fancy and not like my version, but it was actually fun coding everything from scratch!
Why This?
It enables you to really understand functions in Python and handling user input
Reinforces conditional statements. That is using if-else logic.
Really great practice with some of these basic programming concepts!
Code – A Basic Python Calculator
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print()
num1 = float(input("What is the first number? "))
for symbol in operations:
print(symbol)
should_continue = True
while should_continue:
operation_symbol = input("Pick an operation: ")
num2 = float(input("What is the next number? "))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
input(f"Type 'y' to continue calculating with the {answer}, or 'n' to to start a new calculation: ") == "y"
num1 = answer
else:
should_continue = False
calculator()
calculator()
How Does It Work?
The user inputs two numbers.
The user selects an operator (+, -, *, /).
The program calculates and prints the result.
What's Next?
I am going to enhance this by:
Adding error handling for invalid inputs.
Allowing multiple calculations without restarting.
Extending it into a GUI calculator.
Have you ever built a calculator? What features would you add to improve this? Share your thoughts in the comments!
Top comments (0)