Create global variables in Python

Question:

I am fairly new to Python syntax in particular how to create global, nonlocal, and local variables and how to declare them without syntax errors .

For example in the following program, I have

# Estamos creando el juego de Piedra, papel o tijera

import random

userScore = 0;
cpuScore = 0;
global noChoice = True;



# result viene de que los jugadores han elegido, no muestro esta parte
# porque no es necesario por el tema de errores de sintaxis por las variables
def result(userChoice, cpuChoice):



# Traimos de saber lo que el usuario quiere elegir como estrategia
def start():
    while (noChoice):
        try:
            userChoice = int(raw_input("Make a move: Rock = 1, Paper = 2, Scissors = 3"));
        except ValueError: "That's definitely not a number"
        if userChoice == {1,2,3}:
            global noChoice = False;
            print "Oops!  That was no valid number.  Try again..."

    cpuChoice = random.getInt();

start()

This gives the following result:

:~$ python pFC.py
  File "pFC.py", line 7
    global noChoice = True;
                    ^
SyntaxError: invalid syntax

I have used global but it says that I have declared the variable too early.

UnboundLocalError: local variable 'noChoice' referenced before assignment

I have used what I have been advised, but the error remains

# Estamos creando el juego de Piedra, papel o tijera

import random

user_score = 0
cpu_score = 0
global no_choice = True



# result viene de que los jugadores han elegido, no muestro esta parte
# porque no es necesario por el tema de errores de sintaxis por las variables
def result(user_choice, cpu_choice):


# Traimos de saber lo que el usuario quiere elegir como estrategia
def start():
    #Hey Python! Vamos a utilizar una variable global!
    global no_choice
    while (no_choice):
        try:
            user_choice = int(raw_input("Make a move: Rock = 1, Paper = 2, Scissors = 3"))
        except ValueError: "That's definitely not a number"
        if user_choice == {1,2,3}:
            global no_choice = False
            print "Oops!  That was no valid number.  Try again..."

    cpuChoice = random.getInt();

start()

Answer:

Well, I think I'll start by recommending that you take a look at PEP 8 – Style Guide for Python Code, which is the style guide that you should keep in mind when using Python.

For example, for the definition of variables CamelCase is not used nor is it necessary to use ; at the end of each sentence:

userScore = 0;
cpuScore = 0;

It should become:

user_score = 0
cpu_score = 0

Keep in mind that PEP 8 is just a guide , if you'd rather keep doing it your way, that's fine.


Now yes, regarding global variables in your code. The problem is that you are doing it the wrong way.

Consider this script that we are going to create progressively:

# -*- coding: utf-8 -*-

# Es una variable global disponible para cualquier función definida dentro de
# este script
no_choice = True

def start():
    # No es necesario indicar que quieres usar la variable global
    print "El valor de no_choice es:", no_choice

if __name__ == '__main__':
    start()

The result would be:

El valor de no_choice es: True

Note that I am not using global as the use of global is not to define a global variable (even though you may be tempted to do so by name).

Now, imagine you want to modify the no_choice variable:

# -*- coding: utf-8 -*-

# Es una variable global disponible para cualquier función definida dentro de
# este script
no_choice = True

def start():
    # No es necesario indicar que quieres usar la variable global
    print "El valor de no_choice es:", no_choice
    # Quiero negar el valor de no_choice (cambiarla a False)
    no_choice = not no_choice

if __name__ == '__main__':
    start()

This will generate an error:

El valor de no_choice es:
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    start()
  File "test.py", line 9, in start
    print "El valor de no_choice es:", no_choice
UnboundLocalError: local variable 'no_choice' referenced before assignment

Python doesn't know which no_choice variable you mean and assumes it must be one within the scope of the start function, but it doesn't find it and throws the UnboundLocalError error (which occurs when you're trying to use a variable that hasn't been defined).

Now, to be able to modify it we have to tell Python that we want to use the global variable, in this case we do have to use global :

# -*- coding: utf-8 -*-

# Es una variable global disponible para cualquier función definida dentro de
# este script
no_choice = True

def start():
    # Hey Python, voy a usar una variable global
    global no_choice
    print "El valor de no_choice es:", no_choice
    # Quiero negar el valor de no_choice (cambiarla a False)
    no_choice = not no_choice
    print "Ahora el valor de no_choice es:", no_choice

if __name__ == '__main__':
    start()

The result would be:

El valor de no_choice es: True
Ahora el valor de no_choice es: False
Scroll to Top