Calculator program in Python

In the preceding article we have written a program to determine whether a given year is a leap year. Now we will look at a program to implement basic common calculator utility functions for user-given input numbers for whichever operation is selected. If we imagine a calculator and it’s working, we understand that there needs to be choice for entering numbers, for selecting a particular option out of the ones available. Since our program is limited in function, we will also provide an error message upon entering invalid choices.

Implementation of Calculator program in Python

We will implement the basic operations such as addition, subtraction, multiplication and division. However, this program logic can be expanded in the future if required to incorporate more operations by either defining the working or by utilizing the math library functions which would prove to be very useful for such a case. At it’s most ultimate, it could be packed to work as a GUI calculator application.

#Python Simple Calculator Implementation
import sys
print("""Please select operation:
1.Add
2.Subtract
3.Multiply 
4.Division	  
""")
choice=int(input("Select Operation  from 1, 2, 3 or 4 "))
if choice not in (1,2,3,4):
    print("Invalid Choice")
    sys.exit()
a = int(input("Enter First Number: "))
b=int(input("Enter Second Number: "))
if choice == 1:
    res= a + b
elif choice == 2:
    res= a - b
elif choice == 3:
    res= a * b
else:
    res=a/b
print("Result is", res)
Output:
Please select operation:
1.Add
2.Subtract
3.Multiply 
4.Division    

Select Operation  from 1, 2, 3 or 4: 4
Enter First Number: 22
Enter Second Number: 7
Result is 3.142857142857143


Please select operation:
1.Add
2.Subtract
3.Multiply 
4.Division    

Select Operation  from 1, 2, 3 or 4: 3
Enter First Number: 3
Enter Second Number: 5
Result is 15

The program is able to receive input and perform the respective Calculator operations accordingly, we import the ‘sys’ library so that the program is able to quit if the invalid choice is entered. As we can see the program is quite limited, and for now only performs arithmetic operations.

In the next article we will have a further look at loop concepts.

Leave a Comment