代码正在创建,即赋值前引用的局部变量 'p'
The code is creating i.e. local variable 'p' referenced before assignment
我在 python(2) 中写了一个包含 while 语句的函数。这会造成如下所述的错误。请帮我解决这个错误。提前致谢。
错误
the numbers'll increase in order of 2
Traceback (most recent call last):
File "ex28.py", line 27, in <module>
numgame(100, 2)
File "ex28.py", line 20, in numgame
while p < i:
UnboundLocalError: local variable 'p' referenced before assignment
原码
numbers = []
def numgame(i, inc):
print "the numbers'll increase in order of %r" % inc
while p < i:
print "At top is %d" % p
numbers.append(p)
print "The list is %r" % numbers
p += inc
print "The next number to be added to the list is %d" % p
numgame(100, 2)
您需要先用一些值初始化 p
,然后才能比较它 p < i
:
numbers = []
def numgame(i, inc):
print "the numbers'll increase in order of %r" % inc
p = 0 # initialize p
while p < i:
print "At top is %d" % p
numbers.append(p)
print "The list is %r" % numbers
p += inc
print "The next number to be added to the list is %d" % p
numgame(100, 2)
我在 python(2) 中写了一个包含 while 语句的函数。这会造成如下所述的错误。请帮我解决这个错误。提前致谢。
错误
the numbers'll increase in order of 2
Traceback (most recent call last):
File "ex28.py", line 27, in <module>
numgame(100, 2)
File "ex28.py", line 20, in numgame
while p < i:
UnboundLocalError: local variable 'p' referenced before assignment
原码
numbers = []
def numgame(i, inc):
print "the numbers'll increase in order of %r" % inc
while p < i:
print "At top is %d" % p
numbers.append(p)
print "The list is %r" % numbers
p += inc
print "The next number to be added to the list is %d" % p
numgame(100, 2)
您需要先用一些值初始化 p
,然后才能比较它 p < i
:
numbers = []
def numgame(i, inc):
print "the numbers'll increase in order of %r" % inc
p = 0 # initialize p
while p < i:
print "At top is %d" % p
numbers.append(p)
print "The list is %r" % numbers
p += inc
print "The next number to be added to the list is %d" % p
numgame(100, 2)