如何将现有Python代码逻辑移入main()函数满足编程作业要求
实现方案
修复说明
针对你提供的代码和需求,先修正原有问题,再对齐作业要求:
- 移除全局作用域的输入代码,全部移入
main函数内,同时修复int类型输入调用.lower()的语法错误 - 调整
whatturtle函数的判断逻辑,将颜色、数量判断拆分为独立分支,保证两个结果都能正常生成 - 修正相等判断的语法错误,将赋值符
=改为相等判断符== - 调整返回逻辑,同时返回两个判断结果,避免单return提前退出函数
- 完全符合作业要求:所有业务逻辑脱离全局作用域、main调用自定义函数、自定义函数接收入参、自定义函数返回可用值
完整可运行代码
def whatturtle(color, numofshapes): # 处理颜色判断逻辑 if color == "blue": answer1 = "his name is leonardo" else: answer1 = "you are colorblind" # 处理图形数量判断逻辑 if numofshapes == 5: answer2 = "he drew some regular polygons with 3,4,6,9,12 sides!" else: answer2 = "he did not draw that amount of shapes" # 同时返回两个结果供调用方使用 return answer1, answer2 def main(): # 输入逻辑全部放在main内部,不污染全局作用域 color = str(input("What color turtle was drawing the shapes? ")).lower() numofshapes = int(input("how many shapes did it draw? ")) # 调用自定义函数获取结果 res1, res2 = whatturtle(color, numofshapes) # 拼接输出最终结果 print(f"{res1} and {res2}") if __name__ == "__main__": main()
运行示例
输入1:
What color turtle was drawing the shapes?orange
how many shapes did it draw?3
输出:you are colorblind and he did not draw that amount of shapes
输入2:
What color turtle was drawing the shapes?blue
how many shapes did it draw?5
输出:his name is leonardo and he drew some regular polygons with 3,4,6,9,12 sides!
内容的提问来源于stack exchange,提问作者user17361242
相关产品推荐
相关产品推荐

