Create global variables

6

I am quite new to the Python syntax in particular such as creating global, nonlocal and local variables and how to declare them without syntax errors .

For example in the next 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 used global but it says that I declared the variable too soon.

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()
    
asked by ThePassenger 23.05.2016 в 21:37
source

3 answers

7

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

For example, CamelCase is not used for defining variables, 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

Please note that PEP 8 is only a guide , if you prefer to continue doing it your way, that's fine.

Now yes, with respect to the global variables in your code. The problem is that you are doing it incorrectly.

Consider this script that we will be creating 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 since the use of global is not to define a global variable (even though you may be tempted to do so by its name).

Now, imagine that you want to modify the variable no_choice :

# -*- 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 does not know what variable no_choice you mean and assumes that it should be one within the scope of the function start , but can not find it and throws the error UnboundLocalError (which occurs when you are trying to use a variable that has not been defined).

Now, to be able to modify it we have to indicate to Python that we are wanting to use the global variable, in this case we 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
    
answered by 23.05.2016 в 22:32
5

You do not need the word global when you declare it, because being outside the definition of a function automatically becomes global, but if you need the global identifier in the functions that are going to modify it, but declaring it first like this:

  if userChoice == {1,2,3}:
        global noChoice
        noChoice = False;
        print "Oops!  That was no valid number.  Try again..."
    
answered by 23.05.2016 в 22:15
2

Well, in terms of recommendations and good practices, you've already seen it in other answers.

To answer your question, I will mention the errors that I have noticed from the beginning First:

no_choice = True

When declaring a variable you do not need to use global, you only declare it by its name, its situation as global or local, it is implicit (global in that case).

Then, using "global no_choice" within the def start () you create a reference to the variable outside the def (bone in the global scope), that in my opinion is "legal"

About the "if user_choice == {1,2,3}". This last one will possibly give you an error if you use it that way, since what is entered by the user will only be one of those numbers, not a list with all of them. I recommend you change it for:

if user_choice in {1,2,3}

As for the "global no_choice = False", you better leave it as:

no_choice=False

With the "global" that you put at the beginning of the def start (), you already let the python know which one you wanted to modify, you do not need to use it again.

Finally, the cpuChoice variable, if you are going to use it outside the def then, I would recommend declaring it with the others But if you want to declare a global variable from within some def:

>>>globals().update({"nombre_de_variable":3}) #el 3 es el valor de ejemplo, puedes usar un string u otra variable
>>>nombre_de_variable
3

This declares the variable accessible from any (global) site

On the random, the def to select a random number is randint (minimum, maximum), so I imagine you will use:

globals().update({"cpuChoice":random.randint(1,3)})

or in case you did not plan to create the global variable

cpuChoice=random.randint(1,3)

Resumo:

To use the information of a global variable you do not need to use "global", only to edit it, and if you are going to edit it first

global variable
variable="nuevo valor" # no puedes hacer ambas en una sola linea

or the other option that also declares the variable in case it does not exist.

globals().update({"variable":"nuevo valor"})

To create and modify local variables you do not need to use any special words. And in the case of nonlocal, you only use them when you put a def inside another, I do not recommend it, but if you want an example link

Greetings and good luck n_n

    
answered by 17.04.2017 в 02:24