简体   繁体   English

Python 2.7-全局变量未更新(使用函数)

[英]Python 2.7 - Global variable not updating (using functions)

Today i was testing some things i neede for my new code, but i ran into a problem. 今天,我正在测试一些我的新代码所需的东西,但是遇到了一个问题。 I reduced the code to the following: 我将代码简化为以下内容:

def SomeFunction():
    global Turn
    if Turn == 1:
        #some code
        Turn = 0

    if Turn == 0:
        #some code
        Turn = 1

    print Turn

Turn = 1
for i in range(10):
    SomeFunction()  

The problem i am having is that this function keeps printing 1, ten times. 我遇到的问题是此功能可以连续打印1次,十次。 What i want to happen is that it prints 1, then 0, then 1 and so on. 我想发生的是它先打印1,然后0,然后1,依此类推。

I looked at some existing stack overflow posts, but they all suggest i have to tell python the variable Turn is global inside the function, but as i am doing this already, this is confusing to me. 我看了一些现有的堆栈溢出帖子,但是它们都建议我必须告诉python函数内部的变量Turn是global,但是由于我已经这样做了,这使我感到困惑。

I do have to use global variables though, so using only local variables is not the solution. 我确实必须使用全局变量,因此仅使用局部变量不是解决方案。

Regards, Harm 问候,伤害

The problem is that you are overwriting Turn once and again. 问题是您覆盖了Turn Turn一次又一次。 Try using 尝试使用

elif Turn == 0:

instead of 代替

if Turn == 0:

If Turn is equal to 1 the first if condition will be True, so Turn will get set to 0. But then execution passes to the second if condition, which is now True , so Turn will get reset to 1. 如果Turn 等于 1,第一if条件是事实,所以Turn将设置为0。但后来执行传递到第二if条件,这是现在True ,所以Turn会得到重置为1。

The sensible way to handle that is to use elif , as others have mentioned. 如其他人所提到的那样,处理此问题的明智方法是使用elif Alternatively, you can duplicate the print into both branches, and put an early return in the first branch. 或者,您可以将print复制到两个分支中,然后在第一个分支中提前return The elif approach is better because it avoids the code duplication, and it's also good style to avoid early return s if you can. elif方法更好,因为它避免了代码重复,并且如果可以的话,它也是避免早期return的好样式。 But I'll show you the code anyway: 但是我还是会向您显示代码:

def SomeFunction():
    global Turn
    if Turn == 1:
        #some code
        Turn = 0
        print Turn
        return

    if Turn == 0:
        #some code
        Turn = 1
        print Turn

Turn = 1
for i in range(10):
    SomeFunction()  

output 输出

0
1
0
1
0
1
0
1
0
1

BTW, the usual Python convention is to use lower case for simple variable and function names. 顺便说一句,通常的Python约定是对简单的变量和函数名称使用小写字母。 Capitalized and CamelCase names are used for class names. 大写和CamelCase名称用作类名称。 Of course, you don't have to follow this convention, but if ypou don't it makes your code look strange when viewed with most syntax highlighting software, so it's unnecessarily confusing to the rest of the Python community. 当然,你不必遵守这个约定,但如果ypou没有它与大多数语法高亮软件观察,你的代码看起来很奇怪,所以这是不必要的混乱,Python社区的其余部分。

See PEP 0008 -- Style Guide for Python Code for details. 有关详细信息,请参见PEP 0008-Python代码样式指南


Actually, you can alternate a value between zero and one without using an if statement. 实际上,您可以在不使用if语句的情况下在零和一之间替换一个值。 The trick is to use the exclusive-OR operator, ^ : 诀窍是使用异或运算符^

def SomeFunction():
    global Turn
    Turn ^= 1
    print Turn

Turn = 1
for i in range(10):
    SomeFunction()  

This results in the same output as before. 结果与以前相同。

If a variable only ever takes on the values zero and one you should consider making at a boolean instead, and have it alternate between False and True , as that can lead to more readable code. 如果一个变量只有永远取值为0和1,你应该考虑在制作布尔代替,并将它之间交替FalseTrue ,因为这可能会导致更可读的代码。 You can alternate it with: 您可以将其替换为:

Turn = not Turn

and you can use a boolean value in arithmetic expressions, where it will behave just like 0 or 1, although some people don't like doing that, and consider it less readable. 并且您可以在算术表达式中使用布尔值,该布尔值的行为就像0或1,尽管有些人不喜欢这样做,并且认为它的可读性较差


I guess I should also mention that you should try to avoid using global . 我想我还应该提到您应该避免使用global It can be handy, but use of modifiable globals breaks the modularity of code. 它可能很方便,但是使用可修改的全局变量会破坏代码的模块化。 It's not a big deal for small scripts, but you will really appreciate modular design when you write large complex programs. 对于小型脚本来说,这没什么大不了的,但是当您编写大型复杂程序时,您将非常欣赏模块化设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM