当我增加变量时,为什么这会给我0,0

2024-04-25 07:08:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图增加变量a和b,所以当我输入它们并按enter键时 变量a和b增加1。我的目标是,当我完成并想要一个 我会键入除a和b之外的任何内容,然后得到变量的值。因此 我编写了以下代码:

def increment():
    a = 0
    b = 0
    c = 0
    d = 0
    e = 0
    f = 0
    g = 0
    h = 0
    i = 0
    j = 0
    k = 0
    l = 0
    m = 0
    n = 0
    o = 0
    p = 0
    q = 0
    r = 0
    s = 0
    t = 0
    u = 0
    v = 0
    w = 0
    x = 0
    y = 0
    z = 0

    statAsk = input("Enter your letter, else type go for overall statistics ")
    if statAsk == "a":
        a = a+1
        increment()
    elif statAsk == "b":
        b = b+1
        increment()
   else:
       print(a,b)

increment()

然而,当我运行这个程序时,i a和b根本没有增加,我得到了以下结果:

Enter your letter, else type go for overall statistics a
Enter your letter, else type go for overall statistics b
Enter your letter, else type go for overall statistics b
Enter your letter, else type go for overall statistics a
Enter your letter, else type go for overall statistics b
Enter your letter, else type go for overall statistics go
0 0

如何修复此逻辑错误


3条回答

在函数内部,只更新局部变量,不触及全局变量

因此,要更改全局变量,请在更改前使用global variable_name,如下所示:

if statAsk == "a":
        global a
        a = a+1
        increment()

等等

使用python全局关键字,每次调用函数时,值都会重置为零。所以在函数外部声明变量,你的increment()函数应该是

def increment():
   

    statAsk = input("Enter your letter, else type go for overall statistics ")
    if statAsk == "a":
        a = a+1
        increment()
    elif statAsk == "b":
        b = b+1
        increment()
    else:
        print(a,b)

increment()

有关全局关键字的详细信息,请参阅: W3Schools

这只是其中之一

正如@schwobasegll所说的,递增的变量a、b、c、…、z是该函数的局部变量。这些变量仅在该函数执行期间存在。离开增量函数时,这些变量将被销毁

但是,当您下次调用增量函数时,您再次定义了局部变量。每次运行此函数时,都会重置值。当设置a=0、b=0等时,可以在增量函数中看到这一点

您要做的是让这些值保持不变。这可以通过在函数之外定义值来实现,这里定义的任何变量都有一个全局范围

a = 0
b = 0
c = 0

#In order to access these variables above from inside a function, we can use the global keyword

def increment():
    ##Now we need to be able to access the global scope from this local scope (that is the scope of the function
    ##This global keyword means that we are accessing the variable a defined int eh global scope
    global a
    ##Run your logic
    if condition is met:
        a = a+1
    

我将避免使用global关键字,而只是通过increment函数将变量作为参数传递

下面是关于python https://www.w3schools.com/PYTHON/python_scope.asp中作用域的更多信息

相关问题 更多 >

    热门问题