Python简易加法计算器无法执行加法操作,请求技术排查
简易计算器加法功能失效的问题排查与修复
问题根源
input()函数读取用户输入时返回的是字符串类型,而你在判断时将select与整数1做相等比较,类型不匹配导致条件永远不成立,加法逻辑根本不会执行。
两种修复方案
- 方案1:将输入转为整数类型
修改获取选择的代码,把输入字符串转成整数:select = int(input("enter choice 1/2")) - 方案2:使用字符串进行判断
保持select的字符串类型,判断时用字符串"1"比较:if select == "1":
完整修复后的代码示例
def add(a, b): return a + b def subtract(a, b): return a - b print("choose 1 to add and 2 to subtract") select = int(input("enter choice 1/2")) a = float(input("enter 1st number: ")) # 修正原代码中"nunber"的拼写错误 b = float(input("enter 2nd number: ")) if select == 1: print(a, "+", b, "=", add(a, b)) elif select == 2: print(a, "-", b, "=", subtract(a, b)) else: print("Invalid choice, please enter 1 or 2.")
内容的提问来源于stack exchange,提问作者Youssef swedan
相关产品推荐
相关产品推荐

