A basic calculator in Python takes about 20 lines of code
You can build a working calculator in Python by writing a function that takes two numbers and an operation, then returns the result. The simplest version uses if statements to check which operation the user wants (addition, subtraction, multiplication, or division) and performs the math. Python's straightforward syntax makes this a natural first project after learning variables and functions.
The calculator doesn't need a graphical interface to work. A text-based version that asks the user to type numbers and pick an operation teaches you the core logic you would use in any calculator, whether it runs in a terminal or inside a website.
Key Takeaways
- A basic calculator function takes two numbers and an operation symbol, then uses if statements to perform the correct math and return the result.
- The input() function lets you ask the user to type a number or operation, and float() converts text into a number Python can do math with.
- A while True loop keeps the calculator running so the user can perform multiple calculations without restarting the program.
- Testing each operation (addition, subtraction, multiplication, division) separately before combining them into one program catches mistakes early.
Writing the core calculator function
Start by defining a function called calculate that takes three inputs: the first number, the second number, and the operation. Inside the function, use if statements to check which operation the user chose. If the operation is "+", add the numbers. If it is "-", subtract. If it is "*", multiply. If it is "/", divide. Each branch returns the result.
Here is what the function looks like:
def calculate(num1, num2, operation): if operation == "+": return num1 + num2 elif operation == "-": return num1 - num2 elif operation == "*": return num1 * num2 elif operation == "/": if num2 == 0: return "Cannot divide by zero" return num1 / num2 else: return "Invalid operation"
Notice the division check: if the second number is zero, the function returns an error message instead of crashing. This prevents the program from breaking when someone tries to divide by zero, which is mathematically impossible.
Getting input from the user
To make the calculator interactive, use the input() function to ask the user to type a number. The input() function always returns text, even if the user types "5". To do math with it, convert the text to a number using float(), which handles both whole numbers and decimals.
Here is how to ask for the first number:
num1 = float(input("Enter the first number: "))
Ask for the second number the same way, then ask which operation they want:
num2 = float(input("Enter the second number: ")) operation = input("Enter an operation (+, -, *, /): ")
After you have all three pieces of information, call the calculate function and print the result:
result = calculate(num1, num2, operation) print(f"Result: {result}")
Looping to allow multiple calculations
Right now the calculator runs once and stops. To let the user perform multiple calculations without restarting the program, wrap all the input and calculation code inside a while True loop. This loop runs forever until the user chooses to exit.
Add a question at the end asking if the user wants to calculate again. If they type "no", use the break statement to exit the loop:
while True: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) operation = input("Enter an operation (+, -, *, /): ") result = calculate(num1, num2, operation) print(f"Result: {result}") again = input("Do another calculation? (yes/no): ") if again.lower() == "no": break
The .lower() method converts the user's answer to lowercase, so "No", "NO", and "no" all work the same way. This makes the program more forgiving when users type in different cases.
Testing each operation before combining
Before you run the full calculator, test the calculate function by itself with known numbers. Call it with 10 and 5 using the "+" operation and check that it returns 15. Try 10 minus 5 and verify you get 5. Test multiplication and division the same way. Test division by zero to make sure it returns the error message instead of crashing.
Testing each piece separately before combining them saves time because you know exactly which part is broken if something goes wrong. Once the function works correctly on its own, add the input and loop code around it.
Common mistakes to avoid
The most common mistake is forgetting to convert the user's input to a number. If you write num1 = input("Enter a number: ") without float(), Python treats it as text and cannot do math with it. You will get an error when you try to add or multiply.
Another mistake is using a single equals sign (=) in an if statement instead of two (==). A single equals assigns a value; two equals signs compare values. if operation = "+" will crash, but if operation == "+" works correctly.
Division by zero is the third common problem. Always check whether the second number is zero before dividing, as shown in the function above. Without this check, the program crashes with a ZeroDivisionError.
Expanding the calculator later
Once the basic four operations work, you can add more features. Import the math module to add square root, exponent, or absolute value operations. Add a history feature that stores each calculation in a list so the user can see what they calculated before. Create a menu at the start that lets the user choose between basic math, advanced math, or history.
You could also replace the text input with a graphical interface using a library like tkinter, which comes built into Python. This lets you create buttons and a display screen that looks more like a real calculator. The core calculate function stays exactly the same; you just change how the user enters numbers and sees results.
Frequently Asked Questions
What is the difference between = and == in Python?
A single equals sign (=) assigns a value to a variable. Two equals signs (==) compare two values and return true or false. In an if statement, you always use ==. Writing if operation = "+" tries to assign "+" to operation and crashes. Writing if operation == "+" checks whether operation is "+" and runs the code if it is.
Why do I get an error when I try to do math with user input?
The input() function always returns text, even if the user types "5". To do math, convert it to a number first using float() or int(). float() handles decimals; int() handles whole numbers only. Without conversion, Python sees "5" as the word five, not the number 5.
How do I stop the calculator from crashing when someone divides by zero?
Check whether the second number is zero before dividing. Use an if statement: if num2 == 0: return "Cannot divide by zero". This returns an error message instead of attempting the division, which prevents the crash.
Can I make the calculator look like a real calculator with buttons?
Yes, using the tkinter library, which comes with Python. Tkinter lets you create windows, buttons, and text boxes. Your calculate function stays the same; you just connect the buttons to call it when clicked and display the result on screen instead of printing it to the terminal.