0

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. What i want to happen is that it prints 1, then 0, then 1 and so on.

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.

I do have to use global variables though, so using only local variables is not the solution.

Regards, Harm

1
  • 6
    Go through the execution with pen and paper. Yes, the result will always be 1. Perhaps you want to use an elif the second time. Commented Apr 11, 2016 at 10:20

2 Answers 2

1

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.

The sensible way to handle that is to use elif, as others have mentioned. Alternatively, you can duplicate the print into both branches, and put an early return in the first branch. The elif approach is better because it avoids the code duplication, and it's also good style to avoid early returns if you can. 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. Capitalized and CamelCase names are used for class names. 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.

See PEP 0008 -- Style Guide for Python Code for details.


Actually, you can alternate a value between zero and one without using an if statement. 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. 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.


I guess I should also mention that you should try to avoid using 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.

Sign up to request clarification or add additional context in comments.

6 Comments

ah i see, i usually use elif, but i thought it wasn't needed in this case, but that was pretty dumb looking back. btw, i use uppercase variables because i think they are easyer to read that way, but thanks for pointing it out. i try to follow the PEP, but never thought about how i name variables :)
@HarmPrins: FWIW, there's actually a much more efficient way to flip a variable between 0 and 1. I'll add some more code to my answer.
Seems like an efficient solution, but in my case i run different parts of the code depending on the Turn variable. I also Always try to avoid global variables, but in this case i can't avoid it. I am using Tkinter, and a 9x9 grid of buttons. each button calls the same function, but with different arguments, but because the buttons are initialized at the start of the program, i can't send the Turn variable as an argument.
@HarmPrins: The usual way to handle that is to create your GUI in a class, so you're sharing data via the attributes of your class instance. Sure, it's a little more work than using global, but it makes the code a lot more modular. And modular design is very handy with GUI programs, since it makes it a lot easier to reuse stuff from one GUI in another.
I am using classes for my GUI, but how do i share variables in classes? i thought self.variablename would work, but this doesn't
|
1

The problem is that you are overwriting Turn once and again. Try using

elif Turn == 0:

instead of

if Turn == 0:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.