► Python program to do basic calculations

Steps followed:

1. take two numbers and operation user want to perform as input from user

2. validate user input by converting to integer

3. check if input operation is correct

4. perform operation based on given opp and print result

Program

#python program to do basic calculations

#take two numbers and operation user want to perform as input from user

num1 = input("Enter first number: ")

num2 = input("Enter second number: ")

opp = input("Enter opperation you want to perform\ntype + for addition\ntype - for subtraction\ntype * for multiplication\ntype / for division\n: ")

try:

num1=float(num1)

num2=float(num2)

# check if input operation is correct

if opp not in ("+","-","*","/"):

print("invalid operation")

else:

#perform operation based on given opp

if opp == "+":

result = num1 + num2

elif opp == "-":

result = num1 - num2

elif opp == "*":

result = num1 * num2

else:

if num2 == 0:

print("can not perform division as divisor is 0")

else:

result = num1 / num2

print("result for %0.2f %s %0.2f is %0.2f"%(num1,opp,num2,result))

except:

print("---error---")

print("please enter a valid number")

Output

Enter first number: 25

Enter second number: 5

Enter opperation you want to perform

type + for addition

type - for subtraction

type * for multiplication

type / for division

: +

result for 25.00 + 5.00 is 30.00

Enter first number: 60

Enter second number: 40

Enter opperation you want to perform

type + for addition

type - for subtraction

type * for multiplication

type / for division

: -

result for 60.00 - 40.00 is 20.00

Enter first number: 30

Enter second number: 9

Enter opperation you want to perform

type + for addition

type - for subtraction

type * for multiplication

type / for division

: *

result for 30.00 * 9.00 is 270.00

Enter first number: 78

Enter second number: 19

Enter opperation you want to perform

type + for addition

type - for subtraction

type * for multiplication

type / for division

: /

result for 78.00 / 19.00 is 4.11

Enter first number: 68

Enter second number: 0

Enter opperation you want to perform

type + for addition

type - for subtraction

type * for multiplication

type / for division

: /

can not perform division as divisor is 0

Also Read: