# Python code how to do a calculator 2023 k

12/03/2023

## PYTHON CODE | HOW TO DO A CALCULATOR

The aim of this article is for you to know how to do a Calculator with Python code. This Python code exercise is based on creating a basic program to be able to carry out simple operations as a calculator does.

First of all, the Python code will start by displaying a menu with different options, where each option is related to the type of operation a calculator is able to carry out.

Once the menu of options is displayed, the user will be able to select the option of the type of operation that the user would like to do.

After the selection is made, the Python code will prompt the user to enter two integer numbers in order to calculate such an operation accordingly.

Finally, the final result of the operation chosen by the user for the two integer numbers entered by him/her will be displayed.

To start we will create a function called ReadNumber which will need a parameter. This parameter will be the text which has to display to ask the user to insert the number within the selection offered.

At the same time, this function has a series of exceptions for the hypothetical case that the user does not insert an integer number when he is prompted, as to which operations to chose.

If the user does not enter an integer number, the Python code continues running and keeps asking to choose a type of operation, until the user inserts an integer number that complies with the program requirements. The same situation will happen if the integer number entered by the user does not correspond to any of the options on the menú.

#### Py

``````
try:
number = int(input(text))
except ValueError:
print('ERROR: Tienes que introducir un numero entero por favor')
else:
return number
``````

The next step is to create individual functions related to each operation such as Add, Subtract, Multiply, and Divide. Each of them has two variables that will be each of the numbers inserted by the user which are needed to carry out the operation.

Once the previous step is complied with, the result of the operation is displayed.

#### Py

``````
def Sumar():
print(f'El total de la suma de los dos números introducidos es: {suma1 + suma2}')

def Restar():
print(f'El total de la resta de los dos números introducidos es: {resta1+ resta2}')

def Multiplicar():
print(f'El total de la multiplicacion de los dos números introducidos es: {multiplicacion1+ multiplicacion2 }')

def Dividir():
try:
result = division1 / division2
except ZeroDivisionError:
print('ERROR: No se puede dividir por 0')
else:
print(f'El total de la division de los dos números introducidos es: {division1 + division2 }')
``````

## CALCULATOR AND THE SELECTION OF OPERATIONS

The function Calculadora will offer the user a list of options to choose from. As mentioned earlier, these options are related to the type of operation that the user would like to do. Once the user has selected an operation, the function linked to that option will run.

The function Calculadora consists of a loop – while – that offers options whilst the program is running. However, there is an option offered to the user to stop the Python code from running, hence finishing the program. In any case, once the function Calculadora is called the first time, the program keeps running until the user asks it to do otherwise.

For this purpose we use the variable – fin – Initially, the value of this variable is False. The value of – fin – will not become True, unless the user chooses option 6 to escape from the program.

We also have the variable – option – that collects the user’s selection to later execute the function of the operation linked to that choice.

In the while loop, within the function Calculadora, another function is executed. This second function is called ShowMenu. What it does is display the choice options on the screen.

Finally, to start the entire program the function Calculadora is called,

In short, it is a calculator with Python code that shows on the screen its simple operation options.

#### Py

``````

fin = False
while not(fin):
option = ReadNumber('Seleccione una opción por favor : ')
if option == 1:
Sumar()
elif option == 2:
Restar()
elif option == 3:
Multiplicar()
elif option == 4:
Dividir()
elif option == 5:
elif option == 5:
print('Se ha salido del programa')
fin = True

``````

Creatuwebpymes, is a web design company based in Lanzarote – Canary Islands. We ❤️ programming in Python, hence the reason for this post.

This post is an exercise that Python students usually come across in their initial projects. If you wish to learn more about this language, here are some ebooks to learn Python code.

### Comparte | Share #### Francisco Brito Diaz

CEO of Creatuwebpymes, is a web design company and marketing digital based in Lanzarote – Canary Islands

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos y para fines de afiliación y para mostrarte publicidad relacionada con sus preferencias en base a un perfil elaborado a partir de tus hábitos de navegación. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos.