name not defined errors - python

I continue to try nd run this program but keep getting this error:
Traceback (most recent call last):
File "C:\Users\bwhite3500\Documents\School\Spring 2011\CITP 110 - Intro to Computer Programming\pet_list.py", line 57, in <module>
main()
File "C:\Users\bwhite3500\Documents\School\Spring 2011\CITP 110 - Intro to Computer Programming\pet_list.py", line 15, in main
display_list(pets)
NameError: global name 'display_list' is not defined*
Here is my code:
import pet_class
def main():
#get list of pet objects
pets = make_list()
#Display the data in a list.
print 'Here is the data you entered:'
display_list(pets)
#The make_list function gets data from the user for three pets. The function
# returns a list of pet objects containing the data.
def make_list():
#create empty list.
pet_list = []
#Add three pet objects to the list.
print 'Enter data for three pets.'
for count in range (1, 4):
#get the pet data.
print 'Pet number ' + str(count) + ':'
name = raw_input('Enter the pet name:')
animal=raw_input('Enter the pet animal type:')
age=raw_input('Enter the pet age:')
print
#create a new pet object in memory and assign it
#to the pet variable
pet = pet_class.PetName(name,animal,age)
#Add the object to the list.
pet_list.append(pet)
#Return the list
return pet_list
#The display_list function accepts a list containing pet objects
#as an argument and displays the data stored in each object.
def diplay_list(pet_list):
for item in pet_list:
print item.get_name()
print item.get_animal_type()
print item.get_age()
print
#call main function
main()
I am new to this and very confused. Please help

Check your spelling:
def diplay_list(pet_list):

You're calling your function diplay_list, not display_list.

Related

Call to a variable that is inside another function

def HOME():
""" The first screen
"""
print ('Welcome to my program!')
input_grocery_list = input('Hello, please enter here a list of groceries: ')
def input_to_list():
""" This f takes the input
and put it inside a list
without the: ','
and print the list
"""
new_grocery_list = []
separator = ", "
while ',' in input_grocery_list:
d = input_grocery_list.index(',')
y = input_grocery_list[:d]
new_grocery_list.append(y)
input_grocery_list = input_grocery_list[(d+1):]
if ',' not in input_grocery_list:
new_grocery_list.append(input_grocery_list)
print(separator.join(new_grocery_list))
def the_groceries_list():
""" Do somthing to the first input
accord to the next choice
"""
print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
grocery_list = input('please enter here your choice : ')
if grocery_list == '1':
input_to_list(input_grocery_list)
if len(input_grocery_list) != 0:
the_groceries_list()
HOME()
The error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 37, in HOME
File "<stdin>", line 34, in the_groceries_list
TypeError: input_to_list() takes 0 positional arguments but 1 was given
My problem is probably in the second function called "input_to_list ()"
  While I am trying to read / change the "input_grocery_list" variable that is inside the first function (HOME)
It does not recognize him.
I tried to fix it using global or self but I probably don't really know where exactly to put them because in the meantime it didn't work for me.
Anyone know how I can fix this?
As I can see, you try to have a main function, but you should use a class instead of a function, so more like this.
class Home():
def __init__(self):
"""
define your class wide variables here as following
"""
# example
# self.your_name = 'hello'
# to access it in an function IN this class, type: self.your_name
pass
def get_items(self):
print('Welcome to my program!')
input_grocery_list = input('Hello, please enter here a list of groceries (sep with comma): ')
self.input_to_list(input_grocery_list)
# you forgot this
# ||
# \/
def input_to_list(self, grocery_list: str):
""" This f takes the input
and put it inside a list
without the: ','
and print the list
"""
new_grocery_list = grocery_list.split(',')
# to print as list
print(new_grocery_list)
# to print every item in list
for item in new_grocery_list:
print(item)
# print('List End') # if you want to
# I don't really know what that is supposed to do, but whatever it is it wont
"""
def the_groceries_list(self):
# Do somthing to the first input
# accord to the next choice
print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
grocery_list = input('please enter here your choice : ')
if grocery_list == '1':
input_to_list(input_grocery_list)
if len(input_grocery_list) != 0:
the_groceries_list()
"""
# to use this class and it's functions first create an object
home = Home()
# than call a function
home.get_items()
I wont go into details of Classes and Object but here is a link for you.
Read this, it should explain the basics pretty good.
You need to change definition of your nested function so it can take args:
def input_to_list(input_grocery_list):

create multipe telephone directory records in python using list and dict

I'm creating Telephone Directory program by using python, first of all i'm new to python here i created class and declare global list and dict, because i want to store when i call testcreate function we enter name and phone that will stored in list and that list will be stored in dict through save function. To show telephone directory data just call getdata function, but its not working any help thank in advance
class testdl():
testlist=[]
testdic={}
def testcreate():
name = input("enter name : ")
phone = input("enter phone : ")
testdl.save(name,phone)
def save(n,p):
testdl.testlist[n]=p
testdl.testdic = testdl.testlist
def getdata():
print(testdl.testdic)
>>> tdll = testdl()
>>> tdll.testcreate()
**Error Message :**
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
tdll.testcreate()
TypeError: testcreate() takes 0 positional arguments but 1 was given
>>> testdl.testcreate()
enter name : srikanth
enter phone : 1234567890
**Error Message :**
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
testdl.testcreate()
File "<pyshell#79>", line 7, in testcreate
testdl.save(name,phone)
File "<pyshell#79>", line 9, in save
testdl.testlist[n]=p
TypeError: list indices must be integers or slices, not str
Apparently,your function can be a staticmethod and there is no need create a class.If you really want to create a class:
class Testdl:
def __init__(self): # initialize the value
self.testlist=[]
self.testdic={}
self.name = None
self.phone = None
def testcreate(self):
self.name = input("enter name : ")
self.phone = input("enter phone : ")
self.save()
def save(self):
self.testdic[self.name] = self.phone # maybe you need a dict to save them not a list
self.testlist.append(self.testdic) # then you append it in the list
def getdata(self):
print(self.testdic)
testdl = Testdl() # create a instance
testdl.testcreate() # call the function
testdl.getdata() # print the data
If you want to record three groups of data,use:
testdl = Testdl()
for i in range(3):
testdl.testcreate()
testdl.getdata()
Error 1:
Every method in a class needs self as first argument, which refers to the current instance
def testcreate(self):
name = input("enter name : ")
phone = input("enter phone : ")
self.save(name,phone)
Error 2:
def save(self, n,p):
self.testlist[n]=p
lists accept only ints as indices
Errors you will get
Error 3:
self.testlist is empty => IndexError: Index not found
Error 4:
a list is not a dictionary
(in save())
testdl.testdic = testdl.testlist
Possible solution
class testdl():
testdic={}
def testcreate(self, ):
name = input("enter name : ")
phone = input("enter phone : ")
self.save(name,phone)
def save(self, n,p):
self.testlist[n]=p
def getdata(self, n):
print(self.testdic[n])

How do I use raw_input with classes in a definition

Problem
I'm writing a script in Python 2.7 that has the user input the atomic symbol for an element. The script then prints out information about the element.
However, I'm not sure how to have a class use a variable from the raw_input. Here is the code with a couple of the 118 elements gone for readability:
Code
class PTable(object):
def __init__(self, name, atom_num, atom_sym, atom_mass,period, group, atom_type,state):
self.name = name
self.atom_num = atom_num
self.atom_sym = atom_sym
self.atom_mass = atom_mass
self.period = period
self.group = group
self.atom_type = atom_type
self.state = state
h = PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas")
he = PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas")
li = PTable("Lithium",3,"Li",6.941,2,1,"Alkali metal","Solid")
be = PTable("Beryllium",4,"Be",9.0121831,2,2,"Alkaline earth","solid")
og = PTable("Oganesson",1,"H",1.008,1,1,"Nonmetal","Gas")
def results(name, num, sym, mass, per, gro, typ, state):
print "Name:", name
print "Atomic number:", num
print "Atomic symbol:", sym
print "Atomic mass:", mass
print "Period:", per
print "Group:", gro
print "Type:", typ
print "State:", state
# results(h.name, h.atom_num, h.atom_sym, h.atom_mass, h.period, h.group, h.atom_type, h.state)
def hub():
x = raw_input("What element? ")
results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)
hub()
hub()
Errors
The code that gives me the syntax error is:
results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)
The error is obvious; syntax is wrong, so I tried another way:
results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)
That, too, did not work, and I got the error
Traceback (most recent call last):
File "C:/Users/NAME/Desktop/PTable.py", line 146, in
hub()
File "C:/Users/NAME/Desktop/PTable.py", line 143, in hub
results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)
AttributeError: 'str' object has no attribute 'name'
Question
Do you know how I can make it so the user is able to type in the name of the element (the atomic symbol) and the code prints out the information?
Recovering an element
The line x = raw_input("What element? ") provides you with a string, say 'he', so when you call x.name you are attempting to access an attribute of that string and not of the variable he.
What you should do is store your elements in a dictionary instead of having them as variables and access them with the key provided by your user.
periodic_table = {
'h': PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas"),
'he': PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas"),
...
}
symbol = raw_input("What element? ")
try:
element = periodic_table[symbol]
except KeyError:
print('This element does not exist')
Printing the element
As for printing the element, I would suggest a more object-oriented approach by implementing the PTable.__str__ method.
class PTable(object):
...
def __str__(self):
# Add in the format and information that you want to be printed
return "Name: {}".format(self.name)
You can then directly print your elements.
print periodic_table['he']
# prints: 'Name: Helium'

variable defined in a function throws NameError: global name not defined when used in main

I'm trying to run my function: show_total() , but I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\file.py", in <module>
main()
File ".\file.py", in main
total_money = show_total(bags, coins, coin_to_bag)
NameError: global name 'coin_to_bag' is not defined
my code looks like:
def assign_coin_to_bag(bags, coins):
coin_to_bag = {}
print(bags)
print('\n')
print (coins)
print('\n')
for bag in bags:
print('For bag: ' + bag )
coin_type = input('\nWhich coin do you want to put in this bag? ') #e.g. 0.25 * 2
coin_amount = input('\nNumber of this type? ') #e.g. 0.25 * 2
mattress_status = 'stuffed'
for coin in coins:
coin_to_bag[bag] = [coin_type, coin_amount, mattress_status]
print(coin_to_bag)
return (coin_to_bag)
def main():
bags = gather_bag()
coins = gather_coin()
coins_in_the_bag = assign_coin_to_bag(bags, coins)
total_money = show_total(bags, coins, coin_to_bag)
main()
Thank you for your help!
coin_to_bag is a defined in the scope of assign_coin_to_bag, and is not accessible in main. You caught the return value of assign_coin_to_bag in coins_in_the_bag, and need to use that variable in your call to show_total.
There's a common error new programmers make, which is thinking the name of a variable needs to be the same wherever it's used, even across methods. In fact, the name of the variable means absolutely nothing to the computer. Good names are only there for humans.
As an exercise, we used to have students trace code like this:
def foo(one, three, two):
print "%s %s %s" % (one, two, three)
def bar():
return 1, 2, 4
three, two, one = bar()
foo(two, one, three)
Figure out what gets printed, and that will be good practice to break the variable naming habit.

Making a database with custom commands in python

I'm trying to make a simple, local database using Python where I can set values, get values, etc and I keep getting this error:
#Simple Database
#Functions include Set[name][value]
# Get[name]
# Unset[name]
# Numequalto[value]
# End
# Begin, Rollback, Commit
varlist = []
ops = []
class item:
def __init__(self,name,value):
self.name = name
self.value = value
class db:
def __init__(self):
self.varlist = []
self.ops = []
def Set(self,nm,val):
changed = False #Bool for keeping track of update
for item in varlist: #run through current list
if item.name == nm: #If the name is found
item.value = val #update the value
changed = True #found it
break #exit if found
if not changed:
newitem = item() #Create a new one and append it
newitem.name = nm
newitem.value = val
varlist.append(newitem)
def Get(key):
for item in varlist:
if item.name == key:
return item.value
break
def Unset(key):
for item in varlist:
if item.name == key:
item.value = -1
break
def Numequalto(key):
count = 0
for item in varlist:
if item.value == key:
count+=1
return count
def main():
newdb = db()
varlist=[]
comm = "" #prime it
while comm.lower() != "end":
comm = input("Command: ")
if comm.lower() == "begin":
print("----SESSION START---")
while comm.lower() != "end":
comm = input("Command: ")
part = []
for word in comm.split():
part.append(word.lower())
print(part)
if part[0].lower()=="set":
newdb.Set(part[1],part[2])
print(varlist)
elif part[0].lower()=="get":
gotten = Get(part[1])
print(gotten)
elif part[0].lower()=="unset":
Unset(part[1])
elif part[0].lower()=="numequalto":
numequal = Numequalto(part[1])
print(numequal)
print("Finished")
else:
print("--ERROR: Must BEGIN--")
if __name__ == "__main__":
main()
When I run this, and try to create a new item in my list using the command
set a 25
I get this error:
Traceback (most recent call last):
File "/Volumes/CON/LIFE/SimpleDatabase.py", line 81, in <module>
main()
File "/Volumes/CON/LIFE/SimpleDatabase.py", line 65, in main
newdb.Set(part[1],part[2])
File "/Volumes/CON/LIFE/SimpleDatabase.py", line 27, in Set
newitem = item() #Create a new one and append it
UnboundLocalError: local variable 'item' referenced before assignment
Any help would be much appreciated. I'm pretty new to Python
The line
for item in varlist:
shadows the class item with a local variable. So that when you get to your item() it thinks you are trying to call the local variable instead of the class. You can tell that your class item is never being constructed because it would fail as you are passing no parameters to the __init__
Also you should really call your class Item. Once I did that I got the constructor error as expected.
You have a few issues with your code:
You are shadowing the class item with a local variable of the same name.
You are using varlist instead of self.varlist.
Some of your class methods doesn't recieve a self first argument.
Also there is a strong convention in python to name classes with a first capital letter.
Not trying to be implite, just constructive here. I'm concerned that while there are comments questioning the intent to implement your own dictionary, no answer stated this forcefully. I say this only because part of Python (beyond the semantics, language, etc...) is the culture. We speak of things being 'Pythonic' for a reason - part of the value of this language is the culture. There are two aspects here to pay attention to - first, 'Batteries Included' and second, "Don't Reinvent the Wheel". You're reimplimenting the most fundamental composite (oxymoron, I know) data type in Python.
>>> a = {}
>>> a['bob'] = 1
>>> a['frank'] = 2
>>> a
{'frank': 2, 'bob': 1}
>>> del a['frank']
>>> a
{'bob': 1}
>>> del a['bob']
>>> a
{}
>>> a['george'] = 2
>>> b = len([x for x in a.values() if x == 2])
>>> b
1
And there you have it - the pythonic way of handling the functionality you're after.
If you're trying to add functionality or limitations beyond that, you're better off starting from the dict class and extending rather than rolling your own. Since Python is "duck-typed" there's a HUGE benefit to using the existing structure as your basis because it all falls into the same patterns.

Categories

Resources