Python Program to Make a Simple Calculator

Created with Sketch.

Python Program to Make a Simple Calculator

In Python, you can create a simple calculator, displaying the different arithmetical operations i.e. addition, subtraction, multiplication and division.

The following program is intended to write a simple calculator in Python:

See this example:

  1. # define functions
  2. def add(x, y):
  3.    “””This function adds two numbers””
  4.    return x + y
  5. def subtract(x, y):
  6.    “””This function subtracts two numbers“””
  7.    return x – y
  8. def multiply(x, y):
  9.    “””This function multiplies two numbers“””
  10.    return x * y
  11. def divide(x, y):
  12.    “””This function divides two numbers”””
  13.    return x / y
  14. # take input from the user
  15. print(“Select operation.”)
  16. print(“1.Add”)
  17. print(“2.Subtract”)
  18. print(“3.Multiply”)
  19. print(“4.Divide”)
  20. choice = input(“Enter choice(1/2/3/4):”)
  21. num1 = int(input(“Enter first number: “))
  22. num2 = int(input(“Enter second number: “))
  23. if choice == ‘1’:
  24.    print(num1,“+”,num2,“=”, add(num1,num2))
  25. elif choice == ‘2’:
  26.    print(num1,“-“,num2,“=”, subtract(num1,num2))
  27. elif choice == ‘3’:
  28.    print(num1,“*”,num2,“=”, multiply(num1,num2))
  29. elif choice == ‘4’:
  30.    print(num1,“/”,num2,“=”, divide(num1,num2))
  31. else:
  32.    print(“Invalid input”)

Output:

Python Function Programs5
Python Function Programs6

 

Leave a Reply

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