# How to Make a Python Calculator | Built In

Making a calculator is a classic beginner’s project for those just starting to learn how to program with Python. This project can be completed in a relatively short period of time, making it a great springboard to build more complex programs and explore other areas of software development.

We will build a basic calculator that takes two input numbers and an operator from the user, but the project can be built in the future if you are interested in exploring more complex graphical or logical user interfaces

.

More From Max ReynoldsExplaining the differences between SQL and SOQL Make

## a Python calculator

Here’s what you need to get started with this exercise.

1. A text editor or integrated development environment. Like VS Code. Others include Pycharm, Spyder, vim, etc.

2. Python installed on your computer. (See python.org)

3. A basic understanding of Python syntax, variables, and data types (integers, floats, Booleans, etc.)

### User input

in Python

Let’s start by familiarizing ourselves with input and output in Python or I/O. To collect user input in Python, we can use the input() function. For output, we use print().

Let’s take a user’s input and print it.

inp = input(‘Welcome, please enter a number ‘) print(‘You entered:’,inp)First our program asks the user “

Welcome, enter a number” and then prints the user’s input (stored in the variable inp).

Note: To run a Python program, place the code in a file with the extension .py. At the command line, run python <file name>.py.

Our user input stored in inp is a string. This is fine if we are only printing user input. But we need to convert it if we want to do some kind of calculation with the input. Let’s turn our entrance into a float.

inp = float(input(‘Welcome, please enter a number ‘)) print(‘Entered:’,inp)

### Definition of operators

Now let’s talk about the math we want to incorporate into the calculator. We will allow our calculator to use five operations: addition, subtraction, multiplication, division and exponents.

We will ask the user to enter their two numbers and an operator. We store the three inputs and then generate the whole equation by passing multiple arguments to print().

number1 = float(input(‘Enter the first number: ‘)) op = input(‘Enter the operator (+,-,*,/,^): ‘) number2 = float(input(‘Enter the second number: ‘)) print(number1,op,number2)

Note: We do not convert op to float

.

### Conditionally select an operation

Now we have two numbers and one operator selected by the user.

Now we need to convert that input into Python code to calculate the calculation.

To do this, we need to create a function. Our function will cover three arguments: the two numbers and the operator’s string. We will call the function calculate.

def calculate(n1,n2,op): if op == ‘+’: result = n1+n2 elif op == ‘-‘: result = n1-n2 elif op == ‘*’: result = n1*n2 elif op == ‘/’: result = n1/n2 elif op==’^’: result = n1**n2 return result

The calculate function uses conditional statements, which allow a certain block of code to be executed only if a certain condition is met. In our case, for example, we only need to add the two numbers if the ‘+’ operator is passed. Depending on the operator, we store the result of the calculation using the result variable and return it.

As you can see, basic mathematical operations in Python use typical operators. The only irregular is exponential, which uses ** instead of ^. A**B is the equivalent of AB.

Let’s call our function and put it all together!

def calculate(n1,n2,op): if op == ‘+’: result = n1+n2 elif op == ‘-‘: result = n1-n2 elif op == ‘*’: result = n1*n2 elif op == ‘/’: result = n1/n2 elif op==’^’: result = n1**n2 return result number1 = float(input(‘Enter first number: ‘)) op = input(‘Enter operator (+,-,*,/,**): ‘) number2 = float(input(‘Enter second number: ‘)) print(number1,op,number2) result=calculate(number1,number2,op) print(‘=’, result)

The input and output will look like this

:Enter the first number: 3 Enter the operator (+,-,*,/,**): ^ Enter the second number: 2 3.0 ^ 2.0 = 9.0

More Software Engineering Perspectives A Practical Guide to

Python Python

## Calculator Bells and whistles Now we have a

basic functional Python

calculator

. But we can add some simple things to make it a little easier to use.

Suppose we want to perform several calculations without having to run our script again. One way to do this is to create a variable called continue_calculating. As long as continue_calculating is true, we continue to perform calculations.

continue_calculating = True while continue_calculating is True: number1 = float(input(‘Enter first number: ‘)) op = input(‘Enter operator (+,-,*,/,^): ‘) number2 = float(input(‘Enter second number: ‘)) result=calculate(number1,number2,op) print(‘=’,result) yes_or_no = input(‘Continue? (y/n): ‘) if yes_or_no == ‘n’: continue_calculating = False

We have done some things here. First, we create continue_calculating and initialize it to True. Next, we begin a time loop that continues as long as continue_calculating is True. After performing the calculation, we ask the user if they want to continue using the input again. If they enter ‘n’, then the process ends. If they enter ‘and’, we start the loop again and do another calculation.

If our calculation result is equivalent to an integer (for example, 3.0), we may want to print the output without the decimal. We can use the built-in is_integer feature for this, and our output becomes a bit cleaner.

if result.is_integer(): result = int(result)

Finally, we can generate an error if the user enters an invalid

operator:if op == ‘+’: result = n1+n2 elif op == ‘-‘: result = n1-n2 elif op == ‘*’: result = n1*n2 elif op == ‘/’: result = n1/n2 elif op==’^’: result = n1**n2 else: raise ValueError(‘Invalid operator’)

Our finished calculator script:

def calculate(n1,n2,op): if op == ‘+’: result = n1+n2 elif op == ‘-‘: result = n1-n2 elif op == ‘*’: result = n1*n2 elif op == ‘/’: result = n1/n2 elif op==’^’: result = n1**n2 else: raise ValueError(‘Invalid operator’) if result.is_integer(): result = int(result) return result continue_calculating = True while continue_calculating is True: number1 = float(input(‘Enter first number: ‘)) op = input(‘Enter operator (+,-,*,/,^): ‘) number2 = float(input(‘Enter second number: ‘)) print(number1,op,number2) result=calculate(number1,number2,op) print(‘=’,result) yes_or_no = input(‘Continue? (y/n): ‘) if yes_or_no == ‘n’: continue_calculating = False Creating a

basic calculator program in Python is a great starting point for beginners looking to familiarize themselves with the language and its logic. This project covered some basics of variables, data types, user input, functions, and conditional statements.

The calculator project can be completed in a relatively short period of time and can be extended by adding more complex graphical or logical user interfaces. For example, you can add the ability for a user to press buttons instead of typing text. Or you may want to analyze a single equation chain instead of three separate entries. Either way, I hope this project has been a fun and useful experience.