-1

I'm making a little text-based game and I want a function that will create a variable with coordinates I can call on later to graph. Here's what I have:

def addObject(name, x, y):
    global name = [x,y]
addObject(Home, 3,3)
print(Home)

I want to graph it later. This is what I'm having trouble with, though.

  • From the function's definition it looks like it adds an object somewhere, but the function refers to a `global` and then assigns to it (syntax error). What is `Home` that you send in? It's not defined anywhere. I have no idea what you're actually trying to accomplish. – TigerhawkT3 Apr 29 '15 at 23:59
  • @TigerhawkT3 I think he had an indentation problem. Look at Marein's answer. – Reut Sharabani Apr 30 '15 at 00:01
  • To be fair, the indentation problem was actually added by an editor. –  Apr 30 '15 at 00:02
  • 1
    See [this](http://stackoverflow.com/questions/13627865/declare-global-variables-in-python). This is a very bad idea. Global variables are not only slow but create a maintenance issue. – Paul Rooney Apr 30 '15 at 00:02
  • To be fair to the editor (me), the original had no indentation at all. The question and code still make no sense, although the hanging problem that would never actually happen because of the syntax error above it has now been eliminated. – TigerhawkT3 Apr 30 '15 at 00:04
  • Thanks to @PaulRooney's answer I think I understand what the question is trying to be. I found this relevant answer: http://stackoverflow.com/a/11553741/2124834 –  Apr 30 '15 at 00:11

1 Answers1

0

Here is something that appears to do what you want.

def addObject(name, x, y):
    globals()[name] = [x,y]

addObject('Home', 3,3)
print(Home)

Note: Its required to call addObject with the name as a string.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • Oh, thank you that was what I wanted! sorry about the original explanation i'm new. – user3666755 Apr 30 '15 at 00:14
  • No problem. Like I said in the comments `global` variables are universally considered a bad idea in any non trivial program using any programming language. Globals in python are slower to boot see [this](https://wiki.python.org/moin/PythonSpeed/PerformanceTips). – Paul Rooney Apr 30 '15 at 00:17
  • @user3666755 - If that's the answer you were looking for, please click the checkmark to "accept" it. This isn't required, but that way, the next person who has the same question knows that this solution was exactly what **you** were looking for. It also gives some reputation to both you and the person who posted the answer. – Deacon Apr 30 '15 at 13:17