Why can't I define a class in main()?
<p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p>

<pre><code>class graph(object):
    def __init__(self):
        self.nodes = []
        self.edges = []
        self.graphDict = {}

    def addNodes(self):
        self.nodes.append(input("Enter the name for a new node: "))

def main():
    g = graph()

if __name__ == '__main__':
    main()
</code></pre>

<p>And in the console:</p>

<pre><code>&gt;&gt;&gt; g
Traceback (most recent call last):
  File "&lt;pyshell#29&gt;", line 1, in &lt;module&gt;
    g
NameError: name 'g' is not defined
</code></pre>

<p>Any ideas how to fix this?</p>

<p>The variable <code>g</code> is <em>local</em> and exists only inside <code>main()</code>, while you're trying to access it outside <code>main()</code>.</p>

<p>The following tutorial explains the difference between local and global variables: <a href="http://www.python-course.eu/global_vs_local_variables.php" rel="nofollow">http://www.python-course.eu/global_vs_local_variables.php</a></p>

<p>Note that, despite its name, there is nothing special about <code>main()</code>: it's just a function like any other. Any statement that you type into the console is executed at the global scope, i.e. outside all functions.</p>

python class main