By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,187 Members | 1,638 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,187 IT Pros & Developers. It's quick & easy.

NameError: global name 'addBook' is not defined

P: 2
I am fairly new to programming but have some very basic Java background. I am just learning python and tried to make a module that would allow me to create a file containing an address book. I was planning to then create a program to detect input and use this module, but I am hung up. I have constructed the code that I thought would work (though there may be a better way) and I got this error message.
Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "<interactive input>", line 1, in <module>
  3.   File "addBook2.py", line 45, in addEntry
  4.     addBook[name]=[address,phoneNumber]
  5. NameError: global name 'addBook' is not defined
Here is the code (I still have a few things left to finish like delEntry and help with that would be appreciated as well)
Expand|Select|Wrap|Line Numbers
  1. #opens file containing address book
  2. def createBook(file="defaultBook.txt"):
  3.     addBook={}
  4.     add=open(file,"a")
  5.     view=open(file,"r")
  6.     global addBook
  7.     global add
  8.     global view
  9.     list=[]
  10.     for line in view.readlines():    #reads file given as address book and stores as a list
  11.         for item in line.split():
  12.             list.append(item)
  13.     name,address,number='','',''      #read data type in list and stores to addBook{}
  14.     while len(list): #stops when a list is deleted
  15.         if name and address and number: #if variables set, stores to addBook{}
  16.             addBook[name.strip()]=[address.strip(),number.strip()]
  17.             name,address,number='','','' #resets variables after storing them
  18.         if list[0]=="Name:":
  19.             del list[0]
  20.             while list[0]!="Address:": #stores values to name until "Address:" is reached
  21.                 name+=' '+list[0]
  22.                 del list[0]
  23.         if list[0]=="Address:": 
  24.             del list[0]
  25.             while list[0]!="Number:": #stores values to address until "Number:" is reached
  26.                 address+=' '+list[0]
  27.                 del list[0]
  28.         if list[0]=="Number:":
  29.             del list[0]
  30.             while list[0]!="Name:" and list: #stores values to number until "Name:" is reached or list is gone
  31.                 number+=' '+list[0]
  32.                 del list[0]
  33.  
  34. #adds an entry containing name, address, and phone number        
  35. def addEntry(name, address, phoneNumber):
  36.     addBook[name]=[address,phoneNumber]
  37.     if add:
  38.         add.write("Name:\t\t%s\nAddress:\t%s\nPhone:\t\t%s\n\n" % (name,address,phoneNumber))
  39.     add.close()
  40.     add=open(file,"a")
  41.  
  42. #deletes an entry based on name
  43. def delEntry(name):
  44.     del add
  45.  
  46. #name = null reads all entries, name='name' returns entry with name 'name'
  47. def showEntry(name = 'null'):
  48.     if name == 'null':
  49.         for entry in addBook.keys():
  50.             print 'Name:\t\t%s' % entry , 'Address:\t%s' % addBook[entry][0] , 'Phone:\t\t%s' % addBook[entry][1]
  51.     elif addBook.keys().index(name)>=0:
  52.         print 'Name:\t\t%s' % name , 'Address:\t%s' % addBook[name][0] , 'Phone:\t\t%s' % addBook[name][1]
  53.     else:
  54.         print 'Sorry, no entry for: ',name
  55.  
  56. #name = null returns dictionary of all entries, name='name' returns list['name',address,phone]        
  57. def readEntry(name = 'null'):
  58.     if name == 'null':
  59.         return addBook
  60.     elif addBook.keys().index(name)>=0:
  61.         list=[name,addBook[name][0],addBook[name][1]]
  62.         return list
  63.     else:
  64.         print 'Sorry, no entry for: ',name
  65.  
  66. #closes readable and saves editable files
  67. def saveBook():
  68.     add.close()
  69.     view.close()
If you have any advice, questions, etc., please let me know. Thank you all in advance for any help.
Feb 7 '08 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
I would advise staying away from global variables. Also you should avoid using Python built-in function names for variable names. Your functions and variables can be encapsulated in a class object. The following may not be the best way or suit your preferences, but it may give you some ideas.
Expand|Select|Wrap|Line Numbers
  1. class AddBook(object):
  2.  
  3.     def __init__(self, fn="address_book.txt"):
  4.         self.fn = fn
  5.         addBook={}
  6.         lineList = open(fn).readlines()
  7.         # create the dictionary, allow duplicate names
  8.         for i, line in enumerate(lineList):
  9.             if line.startswith('Name'):
  10.                 name =  line.split(':')[1].strip()
  11.                 address = lineList[i+1].split(':')[1].strip()
  12.                 number = lineList[i+2].split(':')[1].strip()
  13.                 addBook.setdefault(name, []).append([address, number])
  14.         self.addBook = addBook       
  15.  
  16.     def addEntry(self, name, address, number):
  17.         # adds an entry containing name, address, and phone number
  18.         # there is no check for exact duplicate entries
  19.         self.addBook.setdefault(name, []).append([address, number])
  20.  
  21.     #deletes an entry based on name
  22.     def delEntry(self, name):
  23.         if name in self.addBook:
  24.             del name
  25.         else:
  26.             print "%s is not in the address book." % name
  27.  
  28.     def showEntry(self, *names):
  29.         # prints each name and info, otherwise prints all entries
  30.         if not names:
  31.             for entry in self.addBook.keys():
  32.                 for info in self.addBook[entry]:
  33.                     print 'Name:\t\t%s\nAddress:\t%s\nPhone:\t\t%s\n' % (entry, info[0], info[1])
  34.         else:
  35.             for name in names:
  36.                 infos = self.addBook.get(name, [['N/A', 'N/A']])
  37.                 for info in infos:
  38.                     print 'Name:\t\t%s\nAddress:\t%s\nPhone:\t\t%s\n' % (name, info[0], info[1])
  39.  
  40.     def readEntry(self, *names):
  41.         # return list of names as a list of lists, otherwise returns self.addBook
  42.         if not names:
  43.             return self.addBook
  44.         else:
  45.             lineList = []
  46.             for name in names:
  47.                 infos = self.addBook.get(name, [['N/A', 'N/A']])
  48.                 for info in infos:
  49.                     lineList.append([name,info[0],info[1]])
  50.             return lineList
  51.  
  52.     def saveBook(self):
  53.         # saves updated address book
  54.         f = open(self.fn, 'w')
  55.         addList = []
  56.         for key in self.addBook:
  57.             for info in self.addBook[key]:
  58.                 addList.append("Name:\t\t%s\nAddress:\t%s\nPhone:\t\t%s\n\n" % (key, info[0], info[1]))
  59.         f.write(''.join(addList))
  60.         f.close()
  61.  
  62. if __name__ == '__main__':
  63.     a = AddBook()
  64.     a.showEntry()
  65.     print 20*'#'
  66.     a.addEntry('Terry Miller', '245 Gist Av.', '(621) 545-6060')
  67.     a.showEntry()
  68.     print 20*'#'
  69.     a.showEntry('Bill Jones')
  70.     print 20*'#'
  71.     a.showEntry('Sam Jones', 'Terry Miller')
  72.     print 20*'#'
  73.     print a.readEntry()
  74.     print 20*'#'
  75.     print a.readEntry('Janet Smith', 'Sam Mitchell')
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> Name:        Janet Smith
  2. Address:    200 Back Avenue
  3. Phone:        (770) 400-1212
  4.  
  5. Name:        Bill Jones
  6. Address:    100 Front Street
  7. Phone:        (615) 555-1212
  8.  
  9. Name:        Bill Jones
  10. Address:    999 Airplane Blvd.
  11. Phone:        (399) 111-7272
  12.  
  13. Name:        Sam Mitchell
  14. Address:    300 Side Place
  15. Phone:        (919) 366-2121
  16.  
  17. ####################
  18. Name:        Janet Smith
  19. Address:    200 Back Avenue
  20. Phone:        (770) 400-1212
  21.  
  22. Name:        Bill Jones
  23. Address:    100 Front Street
  24. Phone:        (615) 555-1212
  25.  
  26. Name:        Bill Jones
  27. Address:    999 Airplane Blvd.
  28. Phone:        (399) 111-7272
  29.  
  30. Name:        Terry Miller
  31. Address:    245 Gist Av.
  32. Phone:        (621) 545-6060
  33.  
  34. Name:        Sam Mitchell
  35. Address:    300 Side Place
  36. Phone:        (919) 366-2121
  37.  
  38. ####################
  39. Name:        Bill Jones
  40. Address:    100 Front Street
  41. Phone:        (615) 555-1212
  42.  
  43. Name:        Bill Jones
  44. Address:    999 Airplane Blvd.
  45. Phone:        (399) 111-7272
  46.  
  47. ####################
  48. Name:        Sam Jones
  49. Address:    N/A
  50. Phone:        N/A
  51.  
  52. Name:        Terry Miller
  53. Address:    245 Gist Av.
  54. Phone:        (621) 545-6060
  55.  
  56. ####################
  57. {'Janet Smith': [['200 Back Avenue', '(770) 400-1212']], 'Bill Jones': [['100 Front Street', '(615) 555-1212'], ['999 Airplane Blvd.', '(399) 111-7272']], 'Terry Miller': [['245 Gist Av.', '(621) 545-6060']], 'Sam Mitchell': [['300 Side Place', '(919) 366-2121']]}
  58. ####################
  59. [['Janet Smith', '200 Back Avenue', '(770) 400-1212'], ['Sam Mitchell', '300 Side Place', '(919) 366-2121']]
  60. >>> 
Feb 7 '08 #2

P: 2
That is very helpful, thank you very much, I'll take that and alter it to my specifications, thanks again.
Feb 8 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.