Mathew K Analytics

Lesson 26 · Python Fundamentals

Python Fundamentals: Create a Simple Calculator Step by Step

In this lesson, we will learn how to use Python to perform basic math. A simple calculator is a great way to start programming. You will learn how to write…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Welcome to Python Fundamentals: Build a Simple Calculator!#

In this lesson, we will learn how to use Python to perform basic math.

A simple calculator is a great way to start programming.

You will learn how to write code, get input, and use Python for calculations.

Let us get started!

Why Python and Calculators?#

Python is an easy language to learn.

Calculators help us understand how computers make decisions and do math.

Today, you will build your very first calculator program.

# Let us start with basic math in Python
a = 2 + 3
print(a)
5
# Let us try subtraction
b = 10 - 4
print(b)
6
# Multiplication and division are also easy
mul = 3 * 4
div = 8 / 2
print(mul)
print(div)
12
4.0

What are Variables?#

Variables in Python are like boxes that store information.

You can use variables to hold numbers, words, and more.

# Assigning values to variables
x = 5
y = 7
result = x + y
print(result)
12
# Python can also get numbers from the user
user_num = input('Enter a number: ')
print('You typed: ', user_num)
You typed:  15
 
# Let us convert the input to a real number
user_num = input('Enter a number: ')
num = int(user_num)
print('Your number plus five is:', num + 5)
Your number plus five is: 28
 

Picking a Math Operation#

Let us help the user pick what math to do.

We will let them choose: add, subtract, multiply, or divide.

# Get the operation from the user
operation = input('Type add, subtract, multiply, or divide: ')
print('You chose:', operation)
You chose: add
 
# Ask for two numbers
num1 = int(input('First number? '))
num2 = int(input('Second number? '))
print('Numbers:', num1, num2)
Numbers: 7 4
 
# Now we do math based on the operation
if operation == 'add':
    answer = num1 + num2
elif operation == 'subtract':
    answer = num1 - num2
elif operation == 'multiply':
    answer = num1 * num2
elif operation == 'divide':
    answer = num1 / num2
else:
    answer = 'Unknown operation'
print('Result:', answer)
Result: 11

Handling Mistakes#

What if someone types something wrong or divides by zero?

Let us make our calculator safer by catching these mistakes.

# Use try and except to handle errors
try:
    if operation == 'divide' and num2 == 0:
        print('Cannot divide by zero.')
    else:
        if operation == 'add':
            print(num1 + num2)
        elif operation == 'subtract':
            print(num1 - num2)
        elif operation == 'multiply':
            print(num1 * num2)
        elif operation == 'divide':
            print(num1 / num2)
        else:
            print('Unknown operation.')
except Exception as e:
    print('Something went wrong:', e)
    
11
# Let us make a function to organize our calculator
def calculator(num1, num2, operation):
    if operation == 'add':
        return num1 + num2
    elif operation == 'subtract':
        return num1 - num2
    elif operation == 'multiply':
        return num1 * num2
    elif operation == 'divide':
        if num2 == 0:
            return 'Cannot divide by zero.'
        else:
            return num1 / num2
    else:
        return 'Unknown operation.'
    
result = calculator(10, 5, 'multiply')
print(result)
50
# Now let us get input and use our function
a = int(input('First number: '))
b = int(input('Second number: '))
op = input('Type add, subtract, multiply, or divide: ')
output = calculator(a, b, op)
print('Result:', output)
Result: Cannot divide by zero.
 
# Mini-project part 1: Repeat calculations in a loop
while True:
    a = int(input('First number: '))
    b = int(input('Second number: '))
    op = input('Type add, subtract, multiply, divide, or quit: ')
    if op == 'quit':
        print('Goodbye!')
        break
    result = calculator(a, b, op)
    print('Result:', result)
    print('-' * 20)
    
Result: 5
--------------------
Result: 4
--------------------
Result: Cannot divide by zero.
--------------------
Result: 16
--------------------
Goodbye!
 
# Mini-project part 2: Let us make it friendlier and easier to read
def pretty_calculator():
    print('Welcome to the Friendly Calculator!')
    while True:
        try:
            n1 = int(input('Enter first number: '))
            n2 = int(input('Enter second number: '))
            op = input('Choose add, subtract, multiply, divide, or quit: ')
            if op == 'quit':
                print('See you next time!')
                break
            res = calculator(n1, n2, op)
            print('Answer is:', res)
            print('---')
        except Exception as e:
            print('Whoops! Something happened:', e)

pretty_calculator()
Welcome to the Friendly Calculator!
Answer is: 7
---
Answer is: 1.0
---
Whoops! Something happened: invalid literal for int() with base 10: 'a'
Whoops! Something happened: invalid literal for int() with base 10: 'multiply'
See you next time!
 
# Troubleshooting common mistakes
try:
    bad_num = int(input('Type a number: '))
    print('Number times 2 is:', bad_num * 2)
except ValueError:
    print('That was not a number. Try again!')
    
That was not a number. Try again!
 
# Challenge: Add a new operation for powers (exponentiation)
def pow_calculator(num1, num2):
    return num1 ** num2

print('2 to the power of 3 is:', pow_calculator(2, 3))
2 to the power of 3 is: 8
# Recap: What did we learn?
concepts = [
    'Adding, subtracting, multiplying, dividing',
    'Variables and input',
    'Handling errors',
    'Functions',
    'Loops',
    'User-friendly programs'
]
for c in concepts:
    print('We learned:', c)
    
We learned: Adding, subtracting, multiplying, dividing
We learned: Variables and input
We learned: Handling errors
We learned: Functions
We learned: Loops
We learned: User-friendly programs

Congratulations! You just built your first calculator program.#

Keep experimenting and try making your own features.

If you liked this lesson, please:

  • Like this video
  • Comment below
  • Subscribe for more
  • Share with your friends

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.