title: Python CGI form (NameError: name 'form' is not defined)
body: <p>I'm not sure why this cgi form doesn't work quite right. The problem is somewhere in the main() function but I'm not quite sure how to fix it. The error when run through the interpreter reads:</p>
  
  <p>File "ptest.py", line 48, in 
  if (form.has_key("action") and form.has_key("name") \
  NameError: name 'form' is not defined</p>
  
  <p>Assume proper indention.</p>
  
  <pre><code># Import the CGI module
  import cgi, cgitb
  
  
  # Required header that tells the browser how to render the HTML.
  print "Content-Type: text/html\n\n"
  
  # Define function to generate HTML form.
  def generate_form():
      print "&lt;HTML&gt;\n"
      print "&lt;HEAD&gt;\n"
      print "\t&lt;TITLE&gt;Info Form&lt;/TITLE&gt;\n"
      print "&lt;/HEAD&gt;\n"
      print "&lt;BODY BGCOLOR = white&gt;\n"
      print "\t&lt;H3&gt;Please, enter your name and age.&lt;/H3&gt;\n"
      print "\t&lt;TABLE BORDER = 0&gt;\n"
      print "\t\t&lt;FORM METHOD = post ACTION = \
                  \"example_7.1.cgi\"&gt;\n"
      print "\t\t&lt;TR&gt;&lt;TH&gt;Name:&lt;/TH&gt;&lt;TD&gt;&lt;INPUT type = text \
                  name = \"name\"&gt;&lt;/TD&gt;&lt;TR&gt;\n"
      print "\t\t&lt;TR&gt;&lt;TH&gt;Age:&lt;/TH&gt;&lt;TD&gt;&lt;INPUT type = text name = \
                  \"age\"&gt;&lt;/TD&gt;&lt;/TR&gt;\n"
      print "\t&lt;/TABLE&gt;\n"
      print "\t&lt;INPUT TYPE = hidden NAME = \"action\" VALUE = \
              \"display\"&gt;\n"
      print "\t&lt;INPUT TYPE = submit VALUE = \"Enter\"&gt;\n"
      print "\t&lt;/FORM&gt;\n"
      print "&lt;/BODY&gt;\n"
      print "&lt;/HTML&gt;\n"
  
  # Define function display data.
  def display_data(name, age):
      print "&lt;HTML&gt;\n"
      print "&lt;HEAD&gt;\n"
      print "\t&lt;TITLE&gt;Info Form&lt;/TITLE&gt;\n"
      print "&lt;/HEAD&gt;\n"
      print "&lt;BODY BGCOLOR = white&gt;\n"
      print name, ", you are", age, "years old."
      print "&lt;/BODY&gt;\n"
      print "&lt;/HTML&gt;\n"
  
  # Define main function.
  
  def main():
      form = cgi.FieldStorage()
      if (form.has_key("action") and form.has_key("name") \
          and form.has_key("age")):
              if (form["action"].value == "display"):
                  display_data(form["name"].value, form["age"].value)
      else:
          generate_form()
  
  if __name__ == '__main__':
      main()
  </code></pre>