我在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)
答案 0 :(得分:1)
您需要初始化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)