DEV Community

Vishnubhotla V D V Bharadwaj
Vishnubhotla V D V Bharadwaj

Posted on • Originally published at on

Calculator in Python

Today we will create a basic calculator in Python. Though it is a basic calculator, we will cover many topics like functions with outputs, multiple return values, and docstrings, while loops and recursion.

Before going to build a calculator, we should some of the basic concepts:

Functions with outputs they use return instead of using the print function. By this, we can store the value and access it through function definition.

A sample example of it is:

def format_name(f_name, l_name):
    formatted_f_name = f_name.title()
    formatted_l_name = l_name.title()
    return f"{formatted_f_name} {formatted_l_name}"
formatted_string = format_name("ViShNuBhOtLa", "BHARADWaj")

Enter fullscreen mode Exit fullscreen mode

title() function makes the first letter of the word capital and all the following letters into small. In the above code, the f-string is returned as it is stored which is later accessed by the function definition itself.

Using Multiple returns in the program. The above code can be improved to use multiple return statements. It is as follows

def format_name(f_name, l_name):
    if f_name == "" or l_name == "":
        return "Enter valid inputs"
    formatted_f_name = f_name.title()
    formatted_l_name = l_name.title()
    return f"{formatted_f_name} {formatted_l_name}"
print(format_name(input("First name: "), input("Last name: ")))

Enter fullscreen mode Exit fullscreen mode

Here we are taking input from the user and if the input is not given then it returns "enter valid input" and the other return statement is used to return our output.

Now, let's just dive to make our calculator program.

Step - 1: Creating required functions. Since it is a basic calculator, I will only have four basic calculator functions(addition, subtraction, multiplication, division). You can use them as your wish.

def add(n1, n2):
  return n1 + n2
def subtract(n1, n2):
  return n1 - n2
def multiply(n1, n2):
  return n1 * n2
def divide(n1, n2):
  return n1 / n2

Enter fullscreen mode Exit fullscreen mode

Before going to the next step let's see what are docStrings. Normally when we are working with an inbuilt function it shows what should be included in the parenthesis. But, when we are defining our own function we use docstrings to explain to users to get clarity about what that function does.

There are some rules to be followed for writing docstrings:

  • It should be the first line under function definition.
  • It should be written inside three quotation marks ex. """ This is the example of docString """
  • This can also be used as comments, If the comments exceeding one line.

Step -2: Next, it's time to declare the operations that we are going to perform.

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide

Enter fullscreen mode Exit fullscreen mode

By defining our operators in the dictionary we can simultaneously use their functions also.

What is a Recursive function? The function which calls itself.

While defining our calculator function at the ending stage we use a recursive function.

Step -3:

def calculator():

  num1 = float(input("What's the first number?: "))
  for symbol in operations:
  should_continue = True

  while should_continue:
    operation_symbol = input("Pick an operation: ")
    num2 = float(input("What's the next number?: "))
    calculation_function = operations[operation_symbol]
    answer = calculation_function(num1, num2)
    print(f"{num1} {operation_symbol} {num2} = {answer}")

    if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
      num1 = answer
      should_continue = False


Enter fullscreen mode Exit fullscreen mode

Let's see what it is written:

  • we have taken the input from the user.

  • Shown the operators of the calculator.

  • Asking him to pick the operation which he needs to perform.

  • Asking to enter the next element(the second one).

  • Performing the selected operation and printing the result.

  • Asking him to continue with the previous calculation or starting the new calculation. (In the step of the new calculation, the recursive function is used to re-run our calculator program).

That's it this is our brand new Calculator program. Meet you in the next one.

You can check my code here:

Top comments (0)