473,392 Members | 1,355 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,392 software developers and data experts.

NameError: global name 'addBook' is not defined

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
2 23723
bvdet
2,851 Expert Mod 2GB
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
That is very helpful, thank you very much, I'll take that and alter it to my specifications, thanks again.
Feb 8 '08 #3

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

Similar topics

5
by: NetKev | last post by:
I added a function 'warn_Admin' and defined it just before another function 'process_log'. 'process_log' calls this warn_Admin' function. However, when it gets called i get the following error...
2
by: a | last post by:
def fn(): for i in range(l) global count count= .... how do i declare count to be global if it is an array subsequently i should access or define count as an array error:
8
by: Evan | last post by:
Hi I have a short script that makes 2 calls to methods in another script as follows: import canPlaces as canp callOne=canp.addMe(3,5) callTwo=canp.estocStn()
3
by: barronmo | last post by:
I'm getting an error msg I don't understand, "global name EMR_globals is not defined", and could use some help. I've separated the application I'm building into several modules. One of the...
1
by: Lalit | last post by:
Hi I am very new to web development. I started with Pylons. I am using http://www.rexx.com/~dkuhlman/pylons_quick_site.html as reference to create a sample web page using pylons. I got stuck...
2
by: jmike | last post by:
I'm using some legacy code that has a user-defined exception in it. The top level program includes this line from TestRunError import * It also imports several other modules. These other...
3
by: Netwatcher | last post by:
im try to activate the tutorial code for wxPython, it is working properly when i tell it to import * from wxPython.wx but with an error about the package, i've done as i was told to change the...
2
by: Geared | last post by:
Hello I'm new to python (been using it all of 2 weeks) and I'm trying to write a program that compares the result of an equation using two different starting numbers that the user chooses. It also...
4
by: jorgejch | last post by:
Hello, I've started with python (3) recently. Initialy only for scripting. Now I'm trying the object oriented bit. I'm getting the following error message <Atom.Atom object at 0x7f0b09597fd0>...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.