2017-07-01 3 views
0
import time 

counter = 0 

def create(): 
    global counter 
    print "The value of counter currently" 
    print counter 
    counter =+ 1 
    print counter 
    print "The value of counter after increment" 

while True: 

    create() 
    time.sleep(3) 

上記のコードでは、グローバル値をますます無限大に増やしています。しかし、私は以下のような出力で終わります。このPythonコードで何が間違っていますか?グローバルカウンタがPythonで更新されない

The value of counter currently 
0 
1 
The value of counter after increment 

The value of counter currently 
1 
1 
The value of counter after increment 

The value of counter currently 
1 
1 
The value of counter after increment 

答えて

2

これは簡単なタイプミスです。 (counter = +1と同等です。counter1再割り当て)

counter =+ 1 

これを試してみてください

counter += 1 
+0

これで100行のコードがブロックされました。私は笑っている以外、なぜ私もpythonがエラーをスローしなかった理由を理解しています..ありがとう。 –

+2

@SuhasChikkanna、よろしくお願いします。ハッピーパイソンプログラミング。 – falsetru

1

に置き換える必要があり、あなたはcounter += 1counter =+ 1を変更する必要があります。

import time 

counter = 0 

def create(): 
    global counter 
    print "The value of counter currently" 
    print counter 
    counter += 1 
    print counter 
    print "The value of counter after increment" 

while True: 

    create() 
    time.sleep(3) 
関連する問題