Global Variables in functions with if statements

19,146

Only one global statement is enough.

From docs:

The global statement is a declaration which holds for the entire current code block.

x = 5
def add():
    global x
    x += 1
    if x == 7:
        x = 5

Also, if I wanted to return x here, where should I do it?

If you're using global in your function then the return x must come after the global x statement, if you didn't use any global statement and also didn't define any local variable x then you can return x anywhere in the function.

If you've defined a local variable x then return x must come after the definition.

Share:
19,146
Admin
Author by

Admin

Updated on June 29, 2022

Comments

  • Admin
    Admin almost 2 years

    Okay, I am currently doing a project to make a blackjack game in python and I'm having some trouble. One of my issues is I dont know when to define a variable as global, specifically in functions with if statements. If I have a global variable outside the if statement, do I have to claim that the variable is global within the if statement as well? For example:

    x = 5
    def add():
        global x  <--- ?
        x += 1
        if x == 7:
            global x <--- ?
            x = 5
    

    I'm pretty sure I need the "global x" at the 1st question mark, but what about at the second question mark? Would I still need to put a "global x" within my if statement if I wanted my if statement to update a global variable? Or does the global x at the beginning of the function make the x's inside the if statement global? Also, if I wanted to return x here, where should I do it?

  • Voo
    Voo almost 11 years
    Actually in almost all situations no global statement is enough ;-)