代码正在创建,即在赋值之前引用的局部变量'p'

时间:2017-05-11 08:49:52

标签: python variables local

我在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)

1 个答案:

答案 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)