BUILD A SIMPLE CALCULATOR USING IF ELIF

In this topic, we discuss how to easily and interestingly to build a simple calculator using if elif in Python programming.  Let’s explore how to build a simple calculator in Python.

Simple Calculator In Python

 

Table of Contents:

  • Introduction
  • Program to build a calculator
  • Output
  • Conclusion

Introduction:

To build a simple calculator using if and elif efficiently, utilize appropriate control statements.  We use ‘if’ and ‘elif’ statements to handle some basic Arithmetic operations like,

Addition,

Subtraction,

Multiplication,

Division

Program:

def calculator():
    print("Simple Calculator Using if and elif")
    print("Select operation do you want:")
    print("1. Addition (+)")
    print("2. Subtraction (-)")
    print("3. Multiplication (*)")
    print("4. Division (/)")

    choice = input("Enter your choice: ")

    if choice in ['1', '2', '3', '4']:
        n1 = float(input("Enter first number: "))
        n2 = float(input("Enter second number: "))

        if choice == '1':
            print(f"Addition of two numbers is  {n1 + n2}")

        elif choice == '2':
            print(f"Subtraction of two numbers  is {n1 - n2}")

        elif choice == '3':
            print(f"Multiplication of two numbers is {n1 * n2}")

        elif choice == '4':
            if n2 != 0:
                print(f"Division of two numbers is {n1 / n2}")
            else:
                print("Error! Division by zero is not allowed.")
    else:
        print("Invalid input. Please enter a number between 1 and 4.")
calculator()

Output:

Simple Calculator Using if and elif
Select operation do you want:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter your choice: 1
Enter first number: 2
Enter second number: 5
Addition of two numbers is 7.0

Select operation do you want:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter your choice: 2
Enter first number: 5
Enter second number: 3
Subtraction of two numbers is 2.0

Select operation do you want:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter your choice: 3
Enter first number: 3
Enter second number: 6
Multiplication of two numbers is 18.0


Select operation do you want:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter your choice: 4
Enter first number: 6
Enter second number: 3
Division of two numbers is 2.0

Conclusion:

In the conclusion, Python programming offers compact statements to build a simple calculator using if and elif in Python.

Thank you for visiting our site!!!!!…..

Leave a Comment

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

Scroll to Top