Python Question

Python variables in functions?

I have a little question about variables. My main language is Java (and I'm learning Python) so, I have a problem calling a variable in a function, it doesn't refresh its new value:

# Values
global e1x, e1y, e1c, e2x, e2y, e2c, altx, alty, x, y

def getValues():
print("Taking Ax + By = C:")
e1x = float(input("Value of x in first equation: "))
#...
if(confirm()): # A function I ommited 'cause its irrelevant
return e1x, e1y, e1c, e2x, e2y, e2c
else:
getValues()

def calculateValues():
# Stuff with variables


# MAIN
getValues()
calculateValues()


I tried to write it without the global, tried to use the self word but, It doesn't work. (Using Python 3)

ERROR:

Traceback (most recent call last):
File "E002_GaussSeidel.py", line 41, in <module>
calculateValues()
File "E002_GaussSeidel.py", line 34, in calculateValues
print(str(e1x))
NameError: name 'e1x' is not defined

Answer

You need to include global within your function. Outside it does nothing.

def getValues():
    global e1x, e1y, e1c, e2x, e2y, e2c, altx, alty, x, y
    print("Taking Ax + By = C:")
    e1x = float(input("Value of x in first equation: "))
    #...
    if(confirm()): # A function I ommited 'cause its irrelevant
        return e1x, e1y, e1c, e2x, e2y, e2c
    else:
        getValues()

def calculateValues():
    # Stuff with variables


# MAIN
getValues()
calculateValues()

But why do you need global variables? Are you going to use those variables outside your function? global is only necessary if you need to modify values that exist outside the scope of the function.

Reformat your code to be like:

def getValues():
    print("Taking Ax + By = C:")
    e1x = float(input("Value of x in first equation: "))
    #...
    if(confirm()): # A function I ommited 'cause its irrelevant
        return e1x, e1y, e1c, e2x, e2y, e2c
    else:
        getValues()

def calculateValues(values):
    # Stuff with variables


# MAIN
calculateValues(getValues())

Instead of passing information with global variables, this passes information by return values. There are hundreds of articles on why global variables are evil.

values holds the returned variables e1x, e1y, e1c, e2x, e2y, e2c. It is accessible using list index notation. If you want to refer to the variables by their names, use:

#...
def calculateValues(e1x, e1y, e1c, e2x, e2y, e2c):
    # Stuff with variables


# MAIN
calculateValues(*getValues())

*foo is list unpacking notation. It is an advanced topic, but it is useful in your situation. You can read more about list unpacking here.

Comments