Calculator program in Python

Calculator program in Python

A simple Calculator can be utilized to carry out the four basic arithmetic operations namely addition, division, multiplication, and subtraction depending on the input of the user.

This tutorial demonstrates how to create a simple Calculator in Python.

Using the while loop along with the if...else conditional statement.

To implement a simple Calculator program in Python, we take the help of the basic while loop along with an if...elif...else conditional statement.

Define functions for Addition, Subtraction, Multiplication and Division

We create four user-defined functions for the four basic operations that exist in a simple Calculator and proceed with the code after creating these functions.

Take user input using input function

Here, we accept input from the user, with the help of the input() function. The input() function is utilized to take input from the user, after which Python evaluates the input and identifies the datatype.

Complete calculator program in Python

The following code uses the while loop and the if...elif...else branching to implement a Simple Calculator program in Python.

Output:

Select one of the four simple operations:
1.Addition
2.Subtraction
3.Multiplication
4.Division
The Selected Operation: 3
Please Enter the first operand: 4
Please Enter the second operand: 8
4.0 * 8.0 = 32.0

Explanation

  • Firstly, we create four user-defined functions for addition, subtraction, multiplication, and division respectively.
  • Then, the user is asked to choose an option between these four operations.
  • Options 1, 2, 3, and 4 are valid while selecting any other option will give the result as Wrong or Invalid Input and the loop goes on until there is a valid option which is selected. Here, we have use float() function to convert String to float in python.
  • The two operands are taken as an input by the user, and an if...elif...else branching is utilized to make the use of the four functions more distinct.
  • All the four user defined functions addition(), subtraction(), multiplication(), and division() evaluate their respective operations based on the input received, and an output is generated.

That’s all about simple calculator program in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *