Python code how to do a calculator 🖩 2022

Como hacer una calculadora con código python - Menu de Calculadora básica creada con código Python - Calculator Python code
k

1 February 2022

Comparte | Share

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


def ReadNumber(text):
    read= False
    while not read:
        try:
            number = int(input(text))
        except ValueError:
            print('ERROR: Tienes que introducir un numero entero por favor')
        else:
            read= True
    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():
    suma1 = ReadNumber('Add one: ')
    suma2 = ReadNumber('Add two: ')
    print(f'El total de la suma de los dos números introducidos es: {suma1 + suma2}')


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


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

def Dividir():
    division1 = ReadNumber('Divide one: ')
    division2 = ReadNumber('Divide two: ')
    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 chose 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 to display the choice options on the screen.

Finally, to star 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


def ShowMenu():
    print('---- Calculadora --------')
    print('\tMenu')
    print('\t1) Add\n\t2) Subtract\n\t3) Multiply\n\t4) Divide\n\t5) Show Menu\n\t6) Close Program')

def Calculadora():
   fin = False
   ShowMenu()
   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:
         ShowMenu()
      elif option == 5:
          print('Se ha salido del programa')
          print('Adios')
          fin = True

Calculadora()

 

We are a web desin company based in Canarias. This post is an exercise that Python students usually encounter in their projects.

Comparte | Share
creatuwebpymes quien somos

Francisco Brito Diaz

CEO of creatuwebpymes.com, web design company & digital marketing in Canary Islands.