user3339203
user3339203

Reputation: 133

How to return global variables

I'm writing a function that creates a graphics window, get points from the user and draws a line with those points in the window. Here is my code:

def setUp():
    w = GraphWin("Demo",500,500)
    return w
def userInput():
   x1, y1, x2, y2 = (eval(input("Enter 4 numbers: ")))
   return x1, y1, x2, y2

def displayLine(w,x1,y1,x2,y2):
    var = Line (point(x1, y1), Point(x2, y2))
    var.draw(w)  

def main():
    w = setUp()         
    userInput() 
    displayLine(w,x1,y1,x2,y2)  
main()

The error I am getting is global name 'x1' is not defined. The x1 variable is defined in the userInput() function.

Upvotes: 0

Views: 740

Answers (2)

metatoaster
metatoaster

Reputation: 18938

Since you return 4 values in userInput(), you also want to expand them in the same scope right before you want to use it, so try something like this for your main()

def main():
    w = setUp()         
    x1, y1, x2, y2 = userInput() 
    displayLine(w,x1,y1,x2,y2)  
main()

Do note that your input method (eval) is definitely insecure since you are executing arbitrary user input, and user has to delimit their numbers specifically with commas which they are not informed of.

Upvotes: 2

shaktimaan
shaktimaan

Reputation: 12092

The error is from the main method. main method does not have x1, y1, x2 or y2 declared in it. You should be doing

x1,y1,x2,y2 = userInput()

since userInput() returns these 4 values, while you are not accepting it in the main method.

Upvotes: 0

Related Questions