How To Build A Calculator

I wrote on how to build a basic calculator that can only perform one function, now we are going to build a more advanced calculator that gives the user more choice to choose from to perform what kind of arithmetic expression he/she wants.

Now with our basic understanding of subtracting integers, we will apply the same principle but this time use the if statement.

what is an if statement?

an if statement evaluates whether an expression is true or false

If a statement is true the system executes it, if it’s not ideal an error message should pop up but the if-else statements execute it. I.e any input you put in will fall into another one of those categories either it’s true or not.

With this technique, we will be able to run multiple scenarios

Multiple Scenarios

# function to add two numbersdef add (num1, num2):num1 + num2# function to subtract two numbersdef subtract (num1, num2):num1 — num2# function to multiply two numbersdef multiply (num1, num2):num1 * num2# functionto divide two numbersdef divide (num1, num2):num1 / num2

Print Out

This is used to execute the command line to give you an output

print (“Please select operation -\n”“1. Add \n”“2. Subtract \n”“3. Multiply \n”“4. Divide \n “)

If Statement

# Take input from the userselect = float(input(“Select operations from 1, 2, 3, 4 :”))number_1 = float(input(“Enter first number: “))number_2 = float(input(“Enter second number: “))if select == 1:result = float(number_1) + float(number_2)print(result)elif select == 2:result = float(number_1) — (number_2)print(result)elif select == 3:result = float(number_1) * (number_2)print(result)elif select == 4:result = float(number_1) / (number_2)print (result)else:print(“Invalid input”)


Upload The Code To Github

  • sign-in into your Github
  • open a new repository

add the code “Add file” from your system (localhost) into your repository

here is the link to my code


I hope you have been able to understand the use of the if statement and its benefits, we have been able to cover both whole numbers and decimals with different scenarios from addition to multiplying.

Thank you for taking your time to read

if you have a comment, suggestion, or just want to discuss python please feel free to reach out. I hoping to learn from you.

you can find me here for interesting topics and updates on Twitter



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tobi Aina

Tobi Aina

i love to make things sound nice and help in building product.