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

如何修复Python脚本的‘Invalid syntax’语法错误及功能异常?

Python脚本语法错误与功能修复方案

问题排查

  • 语法错误根源:if answer = "yes"这一行误用了赋值符号=,Python中判断两个值相等必须用双等号==,单等号会直接触发Invalid syntax错误。
  • 功能异常原因:print("Continue?")之后多写了一次input(),这会吃掉用户第一次输入的内容,导致后续answer = input()需要用户重复输入,不符合预期的交互逻辑。

修正后的代码

color_list = []

def add_to_color_list():
    print("Say something")
    color_list.append(input())

    print(color_list)
    print("Continue?")
    answer = input().strip().lower()  # 处理空格和大小写,提升输入容错性

    if answer == "yes": 
        add_to_color_list()

add_to_color_list()

额外优化说明

  • 加入.strip()可以去除用户输入前后的空格,避免输入yes(带空格)时判断失败
  • 加入.lower()可以把输入转为小写,支持Yes、YES等不同大小写的输入,提升交互友好度

内容的提问来源于stack exchange,提问作者MIfoodie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:01:09