章节 4-8 操作符判断怎么写,课程别讲一半不说了呀
源代码如下
""" 1、输入了一个数字,然后输入操作符号,然后输入一个数字,然后就算出结果 2、输入了一个数字,然后输入操作符号,然后输入一个数字,然后输入操作符号,然后输入一个数字.. 然后就算出结果 """ # 声明一个变量,来记录到底是第几次运算 number_of_times = 1 while True: # 判断到底是不是第一次计算 if number_of_times == 1: result = input("请输入第一个数字:") operator = input("请输入操作符号:") if operator == "q": print("计算程序退出") break elif operator == "c": print("计算器清零,重新开始计算") result = 0 number_of_times = 1 continue second_number = input("请输入第二个数字:") result = float(result) second_number = float(second_number) if operator == "+": result += second_number elif operator == "-": result -= second_number elif operator == "*": result *= second_number elif operator == "/": result /= second_number else: print("没有匹配到正确的操作符,操作符号有错误") print("计算的结果是:"+ str(result)) number_of_times += 1 else: operator = input("请输入操作符号:") if operator == "q": print("计算程序退出") break elif operator == "c": print("计算器清零,重新开始计算") result = 0 number_of_times = 1 continue second_number = input("请输入第二个数字:") result = float(result) second_number = float(second_number) if operator == "+": result += second_number elif operator == "-": result -= second_number elif operator == "*": result *= second_number elif operator == "/": result /= second_number else: print("没有匹配到正确的操作符,操作符号有错误") print("计算的结果是:"+ str(result)) number_of_times += 1
24
收起
正在回答 回答被采纳积分+1
1回答
好帮手慕小猿
2023-07-04 10:26:49
同学,你好!可以对输入的操作符进行判断,看操作符是否在特定的运算符内。若是在运算符内,对操作符进行最终赋值,不在操作符内则进行下一次循环
完整参考代码如下:
number_of_times = 1 while True: # 判断到底是不是第一次计算 if number_of_times == 1: result = input("请输入第一个数字:") operator = input("请输入操作符号:") if operator in ["+","-","*","/"]: final_operator=operator else: print("没有匹配到正确的操作符,操作符号有错误") continue if operator == "q": print("计算程序退出") break elif operator == "c": print("计算器清零,重新开始计算") result = 0 number_of_times = 1 continue second_number = input("请输入第二个数字:") result = float(result) second_number = float(second_number) if final_operator == "+": result += second_number elif final_operator == "-": result -= second_number elif final_operator == "*": result *= second_number elif final_operator == "/": result /= second_number else: print("没有匹配到正确的操作符,操作符号有错误") continue print("计算的结果是:" + str(result)) number_of_times += 1 else: operator = input("请输入操作符号:") if operator in ["+","-","*","/"]: final_operator=operator else: print("没有匹配到正确的操作符,操作符号有错误") continue if operator == "q": print("计算程序退出") break elif operator == "c": print("计算器清零,重新开始计算") result = 0 number_of_times = 1 continue second_number = input("请输入第二个数字:") result = float(result) second_number = float(second_number) if final_operator=="+": result+=second_number elif final_operator == "-": result -= second_number elif final_operator == "*": result *= second_number elif final_operator == "/": result /= second_number print("计算的结果是:" + str(result)) number_of_times += 1
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星