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

Python中TypeError: 'str' object is not callable错误的原因与解决

错误原因与修复方案

原因

你使用了Python内置函数input()的同名变量进行赋值,导致内置函数被覆盖。第一次循环执行input = input(...)时,用户输入的字符串会被存到input变量里,此时原本用于获取输入的内置input()函数已经被替换成了字符串类型。第二次循环再试图调用input(...),就变成了调用一个字符串,这就触发了TypeError: 'str' object is not callable错误。

修复方法

  1. 修改变量名:避免使用Python内置函数名作为变量名,把input改成其他名称,比如user_choice。
  2. 简化判断逻辑:用lower()或upper()方法统一输入的大小写,减少重复判断。

修复后的代码:

list1 = ['monkey', 'banana', 'pizza']
list2 = []

for x in list1:
    user_choice = input(f"Do you want to add {x} to list 2? [y/n] ")
    if user_choice.lower() == "y":
        list2.append(x)
    # 输入n时循环会自动继续,无需额外写continue语句

print(list2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:27:26