+ INFORMATION

Share on social networks!

Python 2.0 Calculator

A few weeks ago we created our first calculator in python and in the previous post we learned to create our own functions.

Well, this week we are going to improve our calculator by creating functions for each of the arithmetic operations.

I'm sure you'll have as much fun as we do improving our calculator on Python and remember that if you want to continue learning you can do it with our master in Advanced Programming in Python for Big Data, Hacking and Machine Learning.

Code from which we start

 create a calculator in python

We start from this code, when we execute it we enter a loop while (if you don't know what it is, I'll explain it to you here) where the calculator menu is shown. In this menu we have several options to perform arithmetic operations.

Create functions

Well, we are going to create functions for each of the cases and thus, in this way, have a much neater code.

Calculator in python

We start by declaring the variables as global number 1 and number2 to be able to use them in any function and we create the functions to add, subtract, multiply and divide They will receive two parameters that will be number 1 and 2. 

In the division function We create an if to validate that the value of “b” is not zero. If it is, we throw the error message because it cannot be divided by zero.

We have omitted the change of numbers since on this occasion we will request the numbers every time we want to do an arithmetic operation.

how to make a calculator in python

In the next section of code, we change to true the value to validate the while, and we put each function in its place, calling the function first enterNumbers() and then to the function that performs the operation we have chosen.

Finally we have added break to get out of the loop while when the user decides. We leave you some screenshots with the results.

make a calculator in python

Subscribe to our newsletter to stay up to date with all the news

EIP International Business School informs you that the data in this form will be processed by Mainjobs Internacional Educativa y Tecnológica, SA as the person responsible for this website. The purpose of collecting and processing personal data is to respond to the query made as well as to send information about the services of the data controller. Legitimation is the consent of the interested party.
You can exercise your rights of access, rectification, limitation and deletion of data in compliance@grupomainjobs.com as well as the right to file a claim with the supervisory authority. You can consult additional and detailed information on Data Protection in the Privacy Policy that you will find in our Web page
marter-in-python

Leave a comment