文章目录
- 1. 实现的功能
- 2. 录入数据及运算符处理函数
- 3. 检查输入的运算符规范性函数
- 4. 录入运算符号处理函数
- 5. 输入的第二个数的处理函数
- 6. 完整代码
- 6. 拓展
1. 实现的功能
- 对输入的两个数进行一次加减乘除
- 对输入的运算符进行判断
2. 录入数据及运算符处理函数
def calc(num1, num2, operator):if operator == '+':return num1 + num2elif operator == '-':return num1 - num2elif operator == '*':return num1 * num2elif operator == '/':return num1 / num2
3. 检查输入的运算符规范性函数
def check_operator(operator):if operator == '+' or operator == '-' or operator == '*' or operator == '/':return Trueelse:return False
4. 录入运算符号处理函数
def input_operator():a = input('请输入运算符号(+ - * /):')while True:if check_operator(a):return aelse:a = input('运算符不正确!请重新输入(+ - * /):')
5. 输入的第二个数的处理函数
def input_num2(operator):num2 = float(input('请输入第二个数:'))while True:if operator == '/' and num2 == 0:num2 = float(input('除数不能为0,请重新输入第二个数:'))else:return num2
6. 完整代码
def calc(num1, num2, operator):if operator == '+':return num1 + num2elif operator == '-':return num1 - num2elif operator == '*':return num1 * num2elif operator == '/':return num1 / num2def check_operator(operator):if operator == '+' or operator == '-' or operator == '*' or operator == '/':return Trueelse:return Falsedef input_operator():a = input('请输入运算符号(+ - * /):')while True:if check_operator(a):return aelse:a = input('运算符不正确!请重新输入(+ - * /):')def input_num2(operator):num2 = float(input('请输入第二个数:'))while True:if operator == '/' and num2 == 0:num2 = float(input('除数不能为0,请重新输入第二个数:'))else:return num2Exit_Flag = 'N'while Exit_Flag == 'N':Input_num1 = float(input('请输入第一个数:'))Input_operator = input_operator()Input_num2 = input_num2(Input_operator)Result = calc(Input_num1, Input_num2, Input_operator)print('运算结果为:', Result)Exit_Flag = input('是否退出计算器模式:Y(退出)/ N(继续):')
6. 拓展