In this post, we will learn how to create a simple calculator in Python with detailed explanation and example.

Creating a simple calculator in any other programming languages like Java, C, or C++, you have to write 40-50 lines of code, but in Python, we will achieve it in just one to two lines of code. Today, I will show you the power of Python.

Python provides us built-in function called eval() and It will help us to create a simple calculator in just one line of code.

Let’s see more about the eval() function.

Python eval() function

the eval() function takes valid Python expression (including mathematical expression) in string format, calculates the expression, and returns the result.

Using this powerful function we achieve our goal to create a simple calculator in Python now let’s see the steps to write the code.

Steps to Create a Simple Calculator in Python

  1. Using the input() function asks the user to enter their mathematical expression and Store it in a variable called expression.
  2. In step no.2 pass the expression to a eval() function and Store the result in a variable called result.
  3. At the end print the result.

Now we know steps to write a program but before we jump into programming part few programming concepts you have to know:

Source Code

expression = input("Enter your mathematical Expression: ")

result = eval(expression)
print(f"{expression} = {result}")

Output-1

Enter your mathematical Expression: 7+6/2*3
7+6/2*3 = 16.0

Output-2

Enter your mathematical Expression: 9+7-5/2*5
9+7-5/2*5 = 3.5

Also, you can modify the above program and rewrite it using the Python functions. Let’s see how.

Create a Simple Calculator in Python Using function

# define a function
def calculator(exp):
    return eval(exp)

expression = input("Enter your mathematical Expression: ")

result = calculator(expression)  # call a function
print(f"{expression} = {result}")

Output

Enter your mathematical Expression: 9+7-5/2*5
9+7-5/2*5 = 3.5

NOTE

Python eval() function is so powerful and it execute any valid python expression so that it is not recommended to pass direct user input to the eval() function.

For instance, if a user entered something like os.system('rm -rf /'), it would be executed if the program runs with sufficient permissions and could cause serious harm by deleting files.

If you want to learn a general approach to creating a simple calculator in Python. checkout this article 👉 Python program to make simple calculator

This is all about how we can create a simple calculator in Python. Hopefully, this post teaches you something new and demonstrates the real power of Python programming. Thank you for reading, and see you in the next article.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment