患者就诊数据采集Python代码是否需使用return函数?
患者数据采集代码
return使用说明 是否需要使用return
你当前的代码不添加return也能正常运行,但从代码规范、可维护性角度,强烈建议添加return优化结构,现有写法存在两个明显问题:
- 函数
new_patients_info被定义在while循环内部,每次循环都会重复创建同名函数,属于无意义的性能损耗,不符合函数定义的常规写法 - 现有函数直接修改全局列表
patients_info,函数和外部逻辑耦合度过高,后续如果需要复用「生成标准格式患者信息」的逻辑(比如将患者信息存入其他数据集、写入数据库),现有写法完全无法支持。
加上return后可以让函数职责更单一:仅负责根据传入参数生成符合格式要求的患者字典,数据存储、后续处理的逻辑交给外部代码实现,后续调整逻辑、排查问题都会更方便。
return的正确添加方式
- 先将
new_patients_info函数的整体定义移动到while循环外部,不要放在循环体中 - 删除函数内部的
patients_info.append(new_info)语句,函数不需要直接操作全局变量 - 在函数内部完成
new_info所有字段的赋值后,添加return new_info语句,将构造完成的患者字典作为返回值输出 - 调用函数时,先用变量接收函数返回的字典对象,再执行append操作将其加入
patients_info列表即可
修正后的完整参考代码
patients_info = [ { "Name": "Patricia Allen", "Age": 25, "Nationality": "America", "State of Origin": "New York", "Marital Status": "Single", "Gender": "Female", "Purpose of Visit": "Chest Xray and blood pressure checks", "Next Visit date": "28th August, 2022", }, { "Name": "Nicholas Carmen", "Age": 30, "Nationality": "America", "State of Origin": "Seattle", "Marital Status": "Single", "Gender": "Male", "Purpose of Visit": "Blood pressure check up and weight checks", "Next Visit date": "25th September, 2022", }, ] # 函数定义移到循环外,通过return返回生成的患者字典 def new_patients_info(name, age, nation, state, marital, gender, purpose, next_visit): new_info = {} new_info["Name"] = name new_info["Age"] = age new_info["Nationality"] = nation new_info["State of Origin"] = state new_info["Marital Status"] = marital new_info["Gender"] = gender new_info["Purpose of Visit"] = purpose new_info["Next Visit date"] = next_visit # return放在所有字段赋值完成后,返回构造好的标准字典 return new_info record_again = True while record_again: name = input("Patient's name: ") age = int(input("Patient's age: ")) nation = input("Nationality: ") state = input("State of Origin: ") marital = input("Marital status: ") gender = input("Gender: ") purpose = input("Purpose of visit: ") next_visit = input("Next visit date: ") another_patient = input("Will you need to record another patient? 'Yes' or 'No'?\n").lower() # 接收函数返回的患者数据,再存入列表 single_patient = new_patients_info(name, age, nation, state, marital, gender, purpose, next_visit) patients_info.append(single_patient) if another_patient == 'no': print(patients_info) record_again = False
补充:如果这段代码只是一次性临时使用、后续不需要维护调整,不写
return也能得到正确结果,但长期使用的代码建议按上述方式优化。
内容的提问来源于stack exchange,提问作者Emmanuella Ndukwe-Obiukwu
相关产品推荐
相关产品推荐

