def division(x, y): global division_error # 声明division_error为全局变量 if y == 0: division_error = 'Error! 0 cannot be used as a divisor.' # 对除数为0时的处理 else: quotient = x / y # 对商为整数时的格式化处理,将浮点型float转化为整数型int approximate_quotient = int(quotient) if approximate_quotient == quotient: return approximate_quotient else: return quotient
# 输入,计算和输出 def calculation_output(): try: num_1=float(input('num1=')) num_2=float(input('num2=')) print('\nWhat do you want to do with it?\n1.num1+num2\n2.num1-num2\n3.num1*num2\n4.num1/num2\n') print('Press the Q key to perform the operation shown in 1') print('Press the W key to perform the operation shown in 1') print('Press the E key to perform the operation shown in 1') print('Press the R key to perform the operation shown in 1\n') key=input('Press:') if key=='q'or key=='Q': print(add(num_1,num_2)) elif key=='w'or key=='W': print(minus(num_1,num_2)) elif key=='e'or key=='E': print(multiply(num_1,num_2)) elif key=='r'or key=='R': print(division(num_1,num_2)) except: print('Error! Input error.') time.sleep(2) print('Next calculation.') time.sleep(2) calculation_output() calculation_output()