2017-05-11 13 views
-3

私はPython(2)でwhile文を含む関数を書きました。これは、以下に述べるエラーを引き起こしています。このエラーを解決するのを手伝ってください。前もって感謝します。あなたはp < iそれを比較することができます前に、いくつかの値でpを初期化する必要がコードは、割り当ての前に参照されるローカル変数 'p'を作成しています

エラー

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) 
+2

エラーは非常に明確で、while条件で使用する前に 'p'を定義していませんでした。 – Lafexlos

答えて

1

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) 
+0

まだエラーが発生しています –

+0

ファイルを実行する前に「保存」したことがありますか? –

+0

はい私は保存をヒットします。私の問題は解決された私は関数の外で変数を宣言していた –

関連する問題