You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将现有Python代码逻辑移入main()函数满足编程作业要求

实现方案

修复说明

针对你提供的代码和需求,先修正原有问题,再对齐作业要求:

  1. 移除全局作用域的输入代码,全部移入main函数内,同时修复int类型输入调用.lower()的语法错误
  2. 调整whatturtle函数的判断逻辑,将颜色、数量判断拆分为独立分支,保证两个结果都能正常生成
  3. 修正相等判断的语法错误,将赋值符=改为相等判断符==
  4. 调整返回逻辑,同时返回两个判断结果,避免单return提前退出函数
  5. 完全符合作业要求:所有业务逻辑脱离全局作用域、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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 13:36:08