Tutorial

How To Make a Calculator Program in Python 3

How To Make a Calculator Program in Python 3

Introduction

The Python programming language is a great tool to use when working with numbers and evaluating mathematical expressions. This quality can be utilized to make useful programs.

This tutorial presents a learning exercise that outlines how to make a command-line calculator program in Python 3. This calculator will be able to perform only basic arithmetic, but the final step of this guide serves as a starting point for how you might improve the code to create a more robust calculator.

We’ll be using math operators, variables, conditional statements, functions, and handle user input to make our calculator.

Prerequisites

For this tutorial, you should have Python 3 installed on your local computer and have a programming environment set up on the machine. If you need to install Python or set up the environment, you can do so by following the appropriate guide for your operating system.

Step 1 — Prompt Users for Input

Calculators work best when a human provides equations for the computer to solve. You’ll start writing your program at the point where the human enters the numbers that they would like the computer to work with.

First, you’ll create a file for your program. For this example, we’ll use the text editor nano and name the file calculator.py:

  1. nano calculator.py

Next, you’ll add contents to this file to run your program. For this program, you’ll have the user input two numbers, so instruct the program to prompt the user for two numbers. You can do this by using Python’s built-in input() function to accept user-generated input from the keyboard. Inside of the parentheses of the input() function you can pass a string to prompt the user, and then assign the user’s input to a variable. Keep in mind that when asking for input, it can be helpful to include a space at the end of your string so that there is a space between the user’s input and the prompting string:

calculator.py
number_1 = input('Enter your first number: ')
number_2 = input('Enter your second number: ')

After writing two lines, you should save the program before running it. If you’re using nano, you can exit by pressing CTRL + X then Y and ENTER.

Run your program with the following command:

  1. python calculator.py

This will begin your program’s prompts and you can respond in the terminal window:

Output
Enter your first number: 5 Enter your second number: 7

If you run this program a few times and vary your input, you’ll notice that you can enter whatever you want when prompted, including words, symbols, whitespace, or the enter key. This is because input() takes data in as strings and doesn’t know that you’re looking for numbers.

You’ll want to use numbers in this program for two reasons:

  1. to enable the program to perform mathematical calculations
  2. to validate that the user’s input is a numerical string

Depending on the needs of your calculator, you may want to convert the string that comes in from the input() function to either an integer or a float. For this tutorial, whole numbers suit our purpose, so wrap the input() function in the int() function to convert the input to the integer data type:

calculator.py
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))

Now, if you run the program and input two integers you won’t run into an error:

Output
Enter your first number: 23 Enter your second number: 674

But, if you enter letters, symbols, or any other non-integers, you’ll encounter the following error:

Output
Enter your first number: sammy Traceback (most recent call last): File "testing.py", line 1, in <module> number_1 = int(input('Enter your first number: ')) ValueError: invalid literal for int() with base 10: 'sammy'

So far, you’ve set up two variables to store user input in the form of integer data types. You can also experiment with converting the input to floats.

Step 2 — Adding Operators

Before the program is complete, you’ll add a total of four mathematical operators: + for addition, - for subtraction, * for multiplication, and / for division.

As you build out the program, you’ll want to make sure that each part is functioning correctly, so start with setting up addition. You’ll add the two numbers within a print function so that the person using the calculator will be able to see the contents:

calculator.py
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))

print(number_1 + number_2)

Run the program and type in two numbers when prompted to ensure that it is working as expected:

Output
Enter your first number: 8 Enter your second number: 3 11

The output shows that the program is working correctly. Now, add some more context for the user to be fully informed throughout the runtime of the program. To do this, use string formatters to help properly format the text and provide feedback. You want the user to receive confirmation about the numbers they are entering and the operator that is being used alongside the produced result:

calculator.py
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))

print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)

Now, when you run the program, you’ll have extra output that will let the user confirm the mathematical expression that is being performed by the program:

Output
Enter your first number: 90 Enter your second number: 717 90 + 717 = 807

Using the string formatters provides the users with more feedback.

At this point, you can add the rest of the operators to the program with the same format used for addition:

calculator.py
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))

# Addition
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)

# Subtraction
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)

# Multiplication
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)

# Division
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)

Here, you’re adding the remaining operators, -, *, and / into the program above. If you run the program at this point, the program will execute all of the operations above. However, you want to limit the program to perform one operation at a time. To do this, you’ll use conditional statements.

Step 3 — Adding Conditional Statements

The goal of the calculator.py program is for the user to be able to choose among the different operators. Start by adding some information at the top of the program, along with a choice to make, so that the person knows what to do.

Write a string on a few different lines by using triple quotes:

'''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
'''

This program uses each of the operator symbols for users to make their choice, so if the user wants division to be performed, they will type /. You could choose whatever symbols you want, though, like 1 for addition, or b for subtraction.

Because you’re asking users for input, you want to use the input() function. Put the string inside of the input() function, and pass the value of that input to a variable, which you’ll name operation:

calculator.py
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')

number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))

print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)

print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)

print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)

print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)

At this point, if you run the program nothing will happen, no matter what you input at the first prompt. To correct this, add some conditional statements into the program. Because of how you have structured the program, the if statement will be where the addition is performed, there will be 3 else-if or elif statements for each of the other operators, and the else statement will be put in place to handle an error if the user did not input an operator symbol:

calculator.py
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')

number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))

if operation == '+':
    print('{} + {} = '.format(number_1, number_2))
    print(number_1 + number_2)

elif operation == '-':
    print('{} - {} = '.format(number_1, number_2))
    print(number_1 - number_2)

elif operation == '*':
    print('{} * {} = '.format(number_1, number_2))
    print(number_1 * number_2)

elif operation == '/':
    print('{} / {} = '.format(number_1, number_2))
    print(number_1 / number_2)

else:
    print('You have not typed a valid operator, please run the program again.')

To walk through this program, first it prompts the user to put in an operation symbol. For example, say the user inputs * to multiply. Next, the program asks for two numbers, and the user inputs 58 and 40. At this point, the program shows the equation performed and the product:

Output
Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division * Please enter the first number: 58 Please enter the second number: 40 58 * 40 = 2320

Because of how you structured the program, if the user enters % when asked for an operation at the first prompt, they won’t receive feedback to try again until after entering numbers. You may want to consider other possible options for handling various situations.

At this point, you have a fully functional program, but you can’t perform a second or third operation without running the program again. The next step involves defining a few functions to add this functionality to the program.

Step 4 — Defining Functions

To handle the ability to perform the program as many times as the user wants, you’ll define some functions. First, put your existing code block into a function. Name the function calculate() and add an additional layer of indentation within the function itself. To ensure the program runs, you’ll also call the function at the bottom of the file:

calculator.py
# Define our function
def calculate():
    operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')

    number_1 = int(input('Please enter the first number: '))
    number_2 = int(input('Please enter the second number: '))

    if operation == '+':
        print('{} + {} = '.format(number_1, number_2))
        print(number_1 + number_2)

    elif operation == '-':
        print('{} - {} = '.format(number_1, number_2))
        print(number_1 - number_2)

    elif operation == '*':
        print('{} * {} = '.format(number_1, number_2))
        print(number_1 * number_2)

    elif operation == '/':
        print('{} / {} = '.format(number_1, number_2))
        print(number_1 / number_2)

    else:
        print('You have not typed a valid operator, please run the program again.')

# Call calculate() outside of the function
calculate()

Next, create a second function made up of more conditional statements. In this block of code, you want to give the user the choice as to whether they want to calculate again or not. You can base this off of the calculator conditional statements, but in this case, you’ll only have one if, one elif, and one else to handle errors.

Name this function again(), and add it after the def calculate(): code block:

calculator.py
... 
# Define again() function to ask user if they want to use the calculator again
def again():

    # Take input from user
    calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')

    # If user types Y, run the calculate() function
    if calc_again == 'Y':
        calculate()

    # If user types N, say good-bye to the user and end the program
    elif calc_again == 'N':
        print('See you later.')

    # If user types another key, run the function again
    else:
        again()

# Call calculate() outside of the function
calculate()

Although there is some error-handling with the else statement above, you could probably make it clearer to accept, say, a lower-case y and n in addition to the upper-case Y and N. To do that, add the string function str.upper():

calculator.py
...
def again():
    calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')

    # Accept 'y' or 'Y' by adding str.upper()
    if calc_again.upper() == 'Y':
        calculate()

    # Accept 'n' or 'N' by adding str.upper()
    elif calc_again.upper() == 'N':
        print('See you later.')

    else:
        again()
...

At this point, you should add the again() function to the end of the calculate() function so that it will trigger the code that asks the user whether or not they would like to continue:

calculator.py
def calculate():
    operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')

    number_1 = int(input('Please enter the first number: '))
    number_2 = int(input('Please enter the second number: '))

    if operation == '+':
        print('{} + {} = '.format(number_1, number_2))
        print(number_1 + number_2)

    elif operation == '-':
        print('{} - {} = '.format(number_1, number_2))
        print(number_1 - number_2)

    elif operation == '*':
        print('{} * {} = '.format(number_1, number_2))
        print(number_1 * number_2)

    elif operation == '/':
        print('{} / {} = '.format(number_1, number_2))
        print(number_1 / number_2)

    else:
        print('You have not typed a valid operator, please run the program again.')

    # Add again() function to calculate() function
    again()

def again():
    calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')

    if calc_again.upper() == 'Y':
        calculate()
    elif calc_again.upper() == 'N':
        print('See you later.')
    else:
        again()

calculate()

You can now run your program with python calculator.py in your terminal window and you’ll be able to calculate as many times as you would like.

Step 5 — Improving the Code

Now you have a nice, fully functional program. However, there is a lot more you can do to improve this code. You can add a welcome function, for example, that welcomes people to the program at the top of the program’s code, like this:

def welcome():
    print('''
Welcome to Calculator
''')
...
# Don’t forget to call the function
welcome()
calculate()

There are opportunities to introduce more error-handling throughout the program. For starters, you can ensure that the program continues to run even if the user types plankton when asked for a number. As the program is right now, if number_1 and number_2 are not integers, the user will get an error and the program will stop running. Also, for cases when the user selects the division operator (/) and types in 0 for their second number (number_2), the user will receive a ZeroDivisionError: division by zero error. For this, you may want to use exception handling with the try ... except statement.

This exercise limited you to four operators, but you can add additional operators, as in:

...
    operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
** for power
% for modulo
''')
...
# Don’t forget to add more conditional statements to solve for power and modulo

Additionally, you may want to rewrite part of the program with a loop statement.

There are many ways to handle errors and modify and improve each and every coding project. It is important to keep in mind that there is no single correct way to solve a problem that we are presented with.

Conclusion

This tutorial walked through one possible approach to building a calculator on the command line. After completing this tutorial, you’ll be able to modify and improve the code and work on other projects that require user input on the command line.

We are interested in seeing your solutions to this basic command-line calculator project! Please feel free to post your calculator projects in the comments.

Next, you may want to create a text-based game like tic-tac-toe or rock-paper-scissors.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
26 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

The easiest way might be the best :)

$ python3
>>> 2 + 4
6

Excelent tutorial! i learn a lot just coding this, thank you.

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
November 25, 2016

Awesome! Thanks for taking the time to comment :)

hello, I found this tutorial very helpful, thank you but, I have doubt, In the code just above step 5 the again function is called before the function is defined and yet the programme is not showing error, am I missing something…?

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
December 2, 2016

Hi there, thanks for your comment!

The again() function appears in the definition of calculate() before being defined, yes, but neither calculate() nor again() are called until the last line of the program file. Calling something that’s not defined is a runtime error, so since the call to again() is in a definition prior to being defined it does not produce an error. Both calculate() and again() are not executed until the bottom of the program, after both have been defined.

You may prefer to have the again() definition above the calculate() definition which is a valid way to construct the program. I put calculate() above because it is the core purpose of the program, but you could switch it :)

yeah makes sense now…thanks for the reply

Although this tutorial seems to be trivial, it cover important concepts like recursion and strings interpolation.

It was pretty fun to do it.

Thanks and waiting for the next!

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
December 6, 2016

Awesome, would love to see if you came up with a more complicated calculator based on what was started here :)

Hi Lisa: great program . Would you have a program for adding fractions of different denominators ??? in Python ??? I am trying to make something for children 5 to 7 grades aprox… so they can actually see the fraction displayed , operations, and get few questions before seeying the result, thanks ! greetings from Santiago of Chile , Richard teaching private maths to small monsters…

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
March 27, 2017

Hi Richard,

Here is something based on the program above with functions for adding fractions:

from fractions import Fraction


def add_fractions(x, y):
    print('Sum of fractions: {0}'.format(x+y))


def calculate():
    x = Fraction(input('Enter your first fraction: '))
    y = Fraction(input('Enter your second fraction: '))
    add_fractions(x, y)
    again()


def again():
    calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')

    if calc_again.upper() == 'Y':
        calculate()
    elif calc_again.upper() == 'N':
        print('See you later.')
    else:
        again()

calculate()

can someone show me how to add more conditional statements to solve for power and module

thanks so much

Just follow the syntax pattern of the other conditional operations, Peterson. Let me know if this hint helps you. I’d be happy to provide you with more hints if and when needed.

  • Roy

Hi Lisa,

Great tutorial!!

My solution uses far less code and is very simplistic.
I also included an option for users to use exponentiation, along with the basic mathematical operations.

def main( ): print(“{:^72}”.format(‘Interactive Python Calculator’)) print(“{:^72}”.format(‘-----------------------------’)) print(“This interactive program will allow you to type a mathematical\n” “expression, then display the value of that expression. You may\n” “perform the following operations: addition ( + ), subtraction( - )\n” “multiplication ( * ), division ( / ), or exponentiation ( ** ). You may\n” “exit the program at any time by typing the following: exit(), followed by\n” “pressing the Enter key, then clicking the OK button in the popup window Kill.”)

for i in range(100):
    express = eval(input('\nEnter your mathematical expression: '))
    print('The value of your expression is',express)
    print( )

main( )

To get operation and calc_again to correctly run

You need to add: raw_input(‘’’

instead of input(‘’’

Excellent article/tutorial, Lisa! Looks like I’m going to be spending some worthwhile time on this website.

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
October 11, 2018

Thank you, glad you are finding the Community tutorials useful!

THANK YOU. I am new to programming and after reviewing countless “simple” calculator tutorials, I found yours to be the clearest. I liked how you built upon each example to introduce the concepts - I did not feel overwhelmed because of this approach. Keep up the great work

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
October 11, 2018

Awesome, I am glad you’re finding the building approach to be useful and that it is helping you get into programming! I hope you are enjoying learning about and developing software :)

hi, if I will like to have number_1 and number_2 to be bigger than 0. How should i amend the program.

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
December 24, 2018

Hi there, in the examples above, the numbers that are used as input examples are bigger than 0. To account for users who want to use 0 as the second input number in division you should implement a try ... except statement for error handling.

hi, awesome tutorial. i’ve tried to write this code :

print ("options")
print("write add to add two numbers")
print("write sub to subtract two numbers")
print("write moltiply to moltiply two numbers")
print("write div to divide two numbers")
print("write quit to quit the program")

users_input = (": ")


if users_input == "quit" :
break

if users_input == "add":
print("enter two numbers")
num1 = int(input("enter first number : "))
num2 = int(input("enter second number : ")
result = str(num1 + num2)
print("result is : "+ result)  

but it display me an error : expected an indended block. can you tell me why? tanks . i’ve just started learning python.

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
January 5, 2019

Hi there, for this part of your code (there would need to be more for this to run), you’ll need to indent four spaces after your if statements, like so:

if users_input == "quit" :
    break

if users_input == "add":
    print("enter two numbers")

Ok that’s clear now, thank you so much

Great tutorial. One problem though, when I run it in the terminal I cannot “play” again even though I type ‘Y’. The ‘N’ portion of the elif statement works. Not sure what I am doing wrong. Below is the screen results and the def again() code. Thanks.

Welcome to Calculator

Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
*

Please enter the first number: 5 Please enter the second number: 5 5 + 5 25

Do you want to calculate again?
Please type Y for Yes and N for No
Y

Do you want to calculate again?
Please type Y for Yes and N for No
Y

Do you want to calculate again?
Please type Y for Yes and N for No
N

def again(): calc_again = input(‘’’ Do you want to calculate again? Please type Y for Yes and N for No ‘’') if calc_again.upper == ‘Y’: calculate() elif calc_again.upper() == ‘N’: print(‘See you later.’) else: again()

I based code o. What you have but would like to know how to show decimal point. The following is the code I’m working with:

unit = int(input('Base unit: ')); dollar = int(input(‘Dollars: ‘)); print (’{} * {} =’.format(unit , dollar)) print (unit * dollar)

Hi there I’m just curious if you know how to make a calculator when the output should look like this In:53-22 The result is 31 In:39%4 The result is 3 In: 65/2 The result is 32 In: 150*2 The result is 300

Thanks a lot Lisa, you’ve made it very clear and simple. wish you the best.

thank you so much for your help. im new here i thought i can send it by msg but you cant do this here so anyways thank for the help. couldnt find this over the internet.

Hope am not laate to the party, well better to be late than to be the Late

here is my assignment;

# here we will try to build a model calculator

def welcome():
    print("Welcome to my Calculator. ")
    proceed = input("""Please select what you would like to do
    C for continue, E for exit""")
    if proceed.upper() == 'C':
        calculate()
    elif proceed.upper() == 'E':
        print("Thanks for using My Calculator, See you again. ")
    else:welcome()
def calculate():
    operation = input(""" please type in the math operation you will like to run
+ for addition
- for subtraction
* for multiplication
/ for division
""")
    number_1 = float(input("please input ur 1st number\n"))
    number_2 = float(input("please input your 2nd number\n"))

    if operation== '+':
        print("{} + {}= ".format(number_1, number_2))
        print(number_1+number_2)

# here we write a code for other operations
# we also add if and else if (elif) statements
    elif operation=='-':
        print("{} - {}= ".format(number_1, number_2))
        print(number_1-number_2)

    elif operation=='*':
        print("{} * {}= ".format(number_1, number_2))
        print(number_1*number_2)

    elif operation=='/':
        print("{} / {}= ".format(number_1, number_2))
        print(number_1/number_2)
    else:print("You have not typed in a 'valid' operation, please run through the program again. ")
    again()
# we add the again function to the calculate as a loop
# to make the calculator continuous we define another variable for continuity called again
def again():
# we will need to take input form user
    calc_again = input(""" please say if you want to calculate again
    say Y for Yes and N for No""")
# if the usr selects Y, then call calculate
# we can make the program accept Y or y by adding the .upper()
    if calc_again.upper() == 'Y':
        calculate()
# if the user types N, say thanks and goodbye
# we can make the program accept N or n by adding the .upper()
    elif calc_again.upper() == "N":
        print("Thanks for using My Calculator, See you again. ")
# if the user types any other key aside N, call calculate
    else:again()
# Call the function Welcome
welcome()
# Call calculate() outside of the function
calculate()

excellent thought process to develop complex program. this helps me get my OOP concepts refreshed after long sabbatical from programming world.

after writing everything, the code replied with local variable ‘operation’ is assigned to but never used. please what can I do, help me

Found this looking for how to make my program print the option to the user to select which function operation they want for the equation and I am over the moon found a great explanation and community to go with it. Thanks.

Hi, how to put or use decimal in programming?

I am in a coding class, and I had no idea how to make a calculator(That was my Homework) in python. Your Tutorial explained EVERYTHING very well. Thank you.

Found this looking for how to make my program print the option to the user to select which function operation they want for the equation and I am over the moon found a great explanation and community to go with it. Thanks.

Hi, how to put or use decimal in programming?

I am in a coding class, and I had no idea how to make a calculator(That was my Homework) in python. Your Tutorial explained EVERYTHING very well. Thank you.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.