Python.随机输入两个数和运算符进行四则运算
代码
import random
def function(x,op,y):
try:
x,y=float(x),float(y)
if op=='+':
print('{}+{}={}'.format(x,y,x+y))
elif op=='-':
print('{}-{}={}'.format(x,y,x-y))
elif op=='*':
print('{}*{}={}'.format(x,y,x*y))
elif op=='/':
if y==0:
print("y connot be 0")
else:
print("{}/{}={}".format(x,y,x/y))
else:
print("please enter right operator!")
except ValueError:
print("please enter right Floating point number!")
x,op,y=map(str,input("print input x,op,y:").split(' ',2))
function(x,op,y)
运行结果:
print input x,op,y:4 / 5
4.0/5.0=0.8
print input x,op,y:4 s 5
please enter right operator!
print input x,op,y:4 / 0
y connot be 0