Calculator Program in Python

Calculator Program By Using Python

In this blog let us see how we can create a calculator program using python

code:


# Define function to perform arithmetic operations
def calculator(num1,num2,operation):
if operation== +:
 result= num1+num2
elif operation== -:
 result= num1-num2
elif operation== *:
 result= num1*num2
 elif operation== %:
 result= num1%num2
elif operation== \:
 if (num2==0):
   result = Error can't divide by zero
 else:
   result = num1/num2
else:
 result = invalid operator 
return result

# Take user input for numbers and operator
num1=float(input("Enter num1 :"))
num2=float(input("Enter num2 :"))
operation=input("Enter an operation(+,-,*,/,%) :")

# Call the function to perform the calculation
result=calculator(num1,num2,operation)

# Display the result
print("Result =",result)

Output:


Enter num1 : 5
Enter num2 : 5
Enter an operation(+,-,*,/,%) : +
Result = 10

Enter num1 : 5
Enter num2 : 5
Enter an operation(+,-,*,/,%) : -
Result = 0

Explanation:

This is a simple calculator programme in Python used to perform simple mathematical operations such as addition, subtraction, multiplication, modulus and division.


Algorithm for above program :

    1.Define a function called calculate that takes three parameters: num1, num2 and operation.
    2.Inside the calculator function, use conditional statements (if, elif, else) to check the value of the operator parameter.
    3.If the operation is +, add num1 and num2 and assign the result to a variable called result.
    4.If the operation is -, subtract num2 from num1 and assign the result to result.
    5.If the operation is *, multiply num1 and num2 and assign the result to result.
    6.If the operation is /, check if num2 is equal to 0. If so, assign the string "Error: Cannot divide by zero" to the result. Otherwise, divide num1 by num2 and assign the result to result.
    7.If the operation is none of the above, assign the string "Error: Invalid operation" to the result.
    8.Return the result from the calculator function.
    9.Ask the user to enter the first number and store it in a variable called num1.
    10.Ask the user to enter the operator (+, -, *, /,%) and store it in a variable called operator.
    11.Ask the user to enter the second number and store it in a variable called num2.
    12.Call the calculate function, passing num1, operator, and num2 as arguments, and assign the returned value to a variable called result.
    13.Print the value of the result to display the calculated result.

Post a Comment

Previous Post Next Post