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
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.
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.
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.