Python分支逻辑异常:输入2/3时函数不可达问题求助
问题根源与修复方案
核心错误:条件判断逻辑完全错误
你当前的if/elif分支写的是if 1:、elif 2:,在Python里非零数值都会被判定为True,所以第一个分支会永远优先执行,后面的分支根本没机会触发。必须改成判断输入的patient_type是否等于对应数值。
其他需要优化的细节
- 患者类型是整数选项,用
int()接收输入比float()更合理,避免出现1.0这种非预期值 - 函数里的参数(比如
calc_inpatient_charges)完全没用,函数内部重新赋值了,直接删掉就行 - 自定义的
exit函数会覆盖Python内置的exit(),建议改名避免冲突,比如叫exit_program
修正后的完整代码
def calc_inpatient_bill(): days = float(input("How many days did this patient stay in the hospital? ")) rate = float(input("What is the daily rate? ")) meds = float(input("What are the charges for medication? ")) serv = float(input("What are the charges for services? ")) total_charges = (days * rate) + meds + serv print(f"Charges incurred by patient: {total_charges:.2f}") def calc_outpatient_bill(): meds = float(input("What are the charges for medication? ")) serv = float(input("What are the charges for services? ")) total_charges = meds + serv print(f"Charges incurred by patient: {total_charges:.2f}") def exit_program(): print("Exiting program...") print("What type of patient is this?") print(" 1. Inpatient") print(" 2. Outpatient") print(" 3. Exit") patient_type = int(input("--: ")) if patient_type == 1: calc_inpatient_bill() elif patient_type == 2: calc_outpatient_bill() elif patient_type == 3: exit_program() else: print("Invalid input, please enter 1, 2 or 3.")
关键修改说明
- 条件判断修正:把
if 1:改为if patient_type == 1:,确保输入对应数值时才触发对应分支 - 函数参数清理:移除了每个函数中无意义的参数,让函数逻辑更简洁
- 输入类型调整:用
int()接收患者类型输入,符合业务逻辑(选项是整数) - 函数名优化:把自定义的
exit改为exit_program,避免覆盖Python内置函数 - 异常输入处理:添加
else分支提示用户输入无效值
内容的提问来源于stack exchange,提问作者user22193348
相关产品推荐
相关产品推荐

