Python - 对象和变量错误
Python - object and variable errors
我正在尝试编写一个循环的公式,直到它达到要求循环的数字并给出答案。但是,我似乎遇到了 variable/calling 个错误。
def infinitesequence(n):
a = 0
b = 0
for values in range(0,n+1):
b = b + 2((-2**a)/(2**a)+2)
a += 1
return b
returns
TypeError: 'int' object is not callable
而
def infinitesequence(n):
a = 0
for values in range(0,n+1):
b = b + 2((-2**a)/(2**a)+2)
a += 1
return b
returns
UnboundLocalError: local variable 'b' referenced before assignment
导致此错误的原因是什么?
2((-2**a)/(2**a)+2)
试图将第一个 2
用作函数。您要求 Python 通过传入 (-2**a)/(2**a)+2
表达式的结果来 调用 2()
,但这不起作用:
>>> 2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
也许你忘记在那里使用 *
multiplication operator:
2 * ((-2 ** a) / (2 ** a) + 2)
你的 UnboundLocal
错误源于你删除了 b = 0
行,这不是你原来错误的原因。
我正在尝试编写一个循环的公式,直到它达到要求循环的数字并给出答案。但是,我似乎遇到了 variable/calling 个错误。
def infinitesequence(n):
a = 0
b = 0
for values in range(0,n+1):
b = b + 2((-2**a)/(2**a)+2)
a += 1
return b
returns
TypeError: 'int' object is not callable
而
def infinitesequence(n):
a = 0
for values in range(0,n+1):
b = b + 2((-2**a)/(2**a)+2)
a += 1
return b
returns
UnboundLocalError: local variable 'b' referenced before assignment
导致此错误的原因是什么?
2((-2**a)/(2**a)+2)
试图将第一个 2
用作函数。您要求 Python 通过传入 (-2**a)/(2**a)+2
表达式的结果来 调用 2()
,但这不起作用:
>>> 2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
也许你忘记在那里使用 *
multiplication operator:
2 * ((-2 ** a) / (2 ** a) + 2)
你的 UnboundLocal
错误源于你删除了 b = 0
行,这不是你原来错误的原因。