0
0
PythonProgramBeginner · 2 min read

Python Program to Create a Simple Calculator

A simple calculator in Python can be created by taking two numbers and an operator as input, then using if statements to perform +, -, *, or / operations, like if op == '+' : result = num1 + num2.
📋

Examples

Inputnum1=5, num2=3, operator='+'
OutputResult: 8
Inputnum1=10, num2=2, operator='/'
OutputResult: 5.0
Inputnum1=7, num2=0, operator='/'
OutputError: Division by zero is not allowed.
🧠

How to Think About It

To build a simple calculator, first get two numbers and the operation from the user. Then check which operation they want using if or elif. Perform the operation on the numbers and show the result. Handle special cases like division by zero to avoid errors.
📐

Algorithm

1
Get the first number from the user.
2
Get the second number from the user.
3
Get the operator (+, -, *, /) from the user.
4
Check which operator was entered.
5
Perform the corresponding arithmetic operation.
6
Display the result or an error if division by zero occurs.
💻

Code

python
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
operator = input('Enter operator (+, -, *, /): ')

if operator == '+':
    result = num1 + num2
elif operator == '-':
    result = num1 - num2
elif operator == '*':
    result = num1 * num2
elif operator == '/':
    if num2 != 0:
        result = num1 / num2
    else:
        print('Error: Division by zero is not allowed.')
        exit()
else:
    print('Invalid operator')
    exit()

print('Result:', result)
Output
Enter first number: 5 Enter second number: 3 Enter operator (+, -, *, /): + Result: 8.0
🔍

Dry Run

Let's trace the example where num1=5, num2=3, and operator='+'.

1

Input first number

num1 = 5.0

2

Input second number

num2 = 3.0

3

Input operator

operator = '+'

4

Check operator and calculate

operator is '+', so result = 5.0 + 3.0 = 8.0

5

Print result

Output: Result: 8.0

StepVariableValue
1num15.0
2num23.0
3operator+
4result8.0
💡

Why This Works

Step 1: Input numbers and operator

We use input() to get numbers and operator from the user, converting numbers to float for decimal support.

Step 2: Check operator with if-elif

We use if and elif to decide which arithmetic operation to perform based on the operator.

Step 3: Handle division by zero

Before dividing, we check if the second number is zero to avoid errors and print a friendly message if so.

Step 4: Print the result

Finally, we print the calculated result using print().

🔄

Alternative Approaches

Using a dictionary to map operators to functions
python
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return 'Error: Division by zero'
    return a / b

ops = {'+': add, '-': subtract, '*': multiply, '/': divide}

num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
operator = input('Enter operator (+, -, *, /): ')

if operator in ops:
    result = ops[operator](num1, num2)
    print('Result:', result)
else:
    print('Invalid operator')
This approach uses functions and a dictionary for cleaner code and easier extension but is slightly more complex for beginners.
Using eval() function
python
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
operator = input('Enter operator (+, -, *, /): ')

expression = num1 + operator + num2
try:
    result = eval(expression)
    print('Result:', result)
except ZeroDivisionError:
    print('Error: Division by zero is not allowed.')
except Exception:
    print('Invalid input or operator')
Using <code>eval()</code> is concise but risky if inputs are not controlled, so it is not recommended for real applications.

Complexity: O(1) time, O(1) space

Time Complexity

The calculator performs a fixed number of operations regardless of input size, so it runs in constant time O(1).

Space Complexity

It uses a fixed amount of memory for variables and does not grow with input size, so space complexity is O(1).

Which Approach is Fastest?

All approaches run in constant time, but using if-elif is simplest and fastest for beginners, while dictionary mapping adds flexibility with minimal overhead.

ApproachTimeSpaceBest For
If-elif statementsO(1)O(1)Simple and clear code for beginners
Dictionary with functionsO(1)O(1)Cleaner code and easy to extend
Eval functionO(1)O(1)Concise but risky, not safe for untrusted input
💡
Always check for division by zero to avoid runtime errors in your calculator.
⚠️
Beginners often forget to convert input strings to numbers before calculations, causing errors.