全局计数器不在python中更新

时间:2017-07-01 13:39:00

标签: python python-2.7

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代码中做错了什么?

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 个答案:

答案 0 :(得分:2)

这是一个简单的错字。

An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while executing the command definition. See the inner exception for details.

(相当于counter =+ 1 ;将counter = +1重新分配给1

应替换为

counter

答案 1 :(得分:1)

试试这个,您需要将counter =+ 1更改为counter += 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)