微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 中的 For 循环:

如何解决Python 中的 For 循环:

此程序用于将列表中的颜色替换为白色。为什么我得到 TypeError: 'tuple' object is not callable

squares = ["red","yellow","green","blue","violet","purple","pink"]

for i in range(0,7):

    print("before square:",i,"is",squares[i])

    squares[i] = 'white'

    print("after square:",squares[i])

输出

TypeError                                 Traceback (most recent call last)
<ipython-input-54-bd7b126ebd59> in <module>
      1 squares = ["red","pink"]
      2 
----> 3 for i in range(0,7):

      4     print("before square:",squares[i])

      5     `squares[i] = 'white'`

TypeError: 'tuple' object is not callable

解决方法

这段代码对我来说运行良好(Python 3.7.6)。对于您收到此错误的原因,我最好的猜测是您在代码的其他位置为标签(变量)range 分配了一个元组,因此现在 range() 对您不起作用。

示例:

range = (1,2,3,4,5)

for i in range(10):
    print(i)

这会引发错误:

Traceback (most recent call last):
File "c:/Users/shubh/Desktop/a.py",line 3,in <module>
    for i in range(10):
TypeError: 'tuple' object is not callable

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。