Basic calculator program using Python program

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to build a basic calculator in Python. I think all of you have an idea about the basic calculators. We will give six options to the user from which they select one option, and we will perform the respective operation. Following are the arithmetic operations we are going to perform.

  • Addition
  • Subtraction
  • Multiplication
  • Division
  • Floor Division
  • Modulo

Try to implement it's on your own. Follow the below steps to write code for a simple calculator.

Algorithm

1. Initialise the two numbers.
2. Ask the user to enter an option by giving six options.
3. After getting the option from the user write if conditions for every operation based on the option.
4. Perform the respective operation.
5. Print the result.

Let's write the code.

Example

## initializing the numbers
a, b = 15, 2
## displaying catalog for the user choice
print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo")
## getting option from the user
option = int(input("Enter one option from the above list:- "))
## writing condition to perform respective operation
if option == 1:
   print(f"Addition: {a + b}")
elif option == 2:
   print(f"Substraction: {a - b}")
elif option == 3:
   print(f"Multiplication: {a * b}")
elif option == 4:
   print(f"Division: {a / b}")
elif option == 5:
   print(f"Floor Division: {a // b}")
elif option == 6:
   print(f"Modulo: {a % b}")

Output

If you run the above program, you will get the following output.

1 - Addition
2 - Substraction
3 - Multiplication
4 - Division
5 - Floor Division
6 - Modulo
Enter one option from the above list:- 3
Multiplication: 30

Let's execute the program once again

Example

## initializing the numbers
a, b = 15, 2
## displaying catalog for the user choice
print("1 - Addition\n2 - Substraction\n3 - Multiplication\n4 - Division\n5 - Floor Division\n6 - Modulo")
## getting option from the user
option = int(input("Enter one option from the above list:- "))
## writing condition to perform respective operation
if option == 1:
   print(f"Addition: {a + b}")
elif option == 2:
   print(f"Substraction: {a - b}")
elif option == 3:
   print(f"Multiplication: {a * b}")
elif option == 4:
   print(f"Division: {a / b}")
elif option == 5:
   print(f"Floor Division: {a // b}")
elif option == 6:
   print(f"Modulo: {a % b}")

Output

If you run the above program, you will get the following output.

1 - Addition
2 - Substraction
3 - Multiplication
4 - Division
5 - Floor Division
6 - Modulo
Enter one option from the above list:- 6
Modulo: 1

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

raja
Published on 23-Oct-2019 11:44:26
Advertisements