Why is the module not callable - python

I have most of my program done however I keep getting the error and can't seem to figure out why it keeps doing so. I've also tried animal_list = Zoo.Zoo()
line 43, in addAnimal
animal_list = Zoo()
TypeError: 'module' object is not callable
here is some of my program
import Animal
import Zoo
def main():
#set user choice
choice = 0
while choice != "3":
display_menu()
#get user's choice
choice = str(input("What would you like to do? "))
#Perform selected choice
if choice.isalpha():
print("Please enter a numeical value")
elif choice == "1":
addAnimal()
and
#Add animal to list
def addAnimal():
atype = input("What type of animal would you like to create? ")
aname = input("What is the animal's name? ")
theAnimal = Animal.Animal(atype, aname)
theAnimal.set_animal_type(atype)
theAnimal.set_name(aname)
animal_list = Zoo()
animal_list.add_animal(theAnimal,Animal)

From looking at your other questions, your Zoo class is quite wrong.
Your Zoo class should be written like this:
class Zoo:
def __init__(self):
self.__animals = []
def add_animal(self, animals):
self.__animals.append(animal)
def show_animals(self):
size = len(self.__animals)
if size == 0:
print("There are no animals in your zoo!")
else:
return __animals
Instead you define methods like this:
def __init__(Animal):
and define variables like:
Animal.__animals = []
which simply don't make sense.
Your problem is that you used a module (Animal) instead of self. I have no idea where you might have gotten this idea, but you may want to peruse class definition in the Python documentation.

Related

How to compare 2 objects from a class

I have created a class called Dog_card. With this, I created player_card and computer_card. I am trying to compare the same attribute from both of these objects. There are more values to each than friendliness, but I have removed them so it is easier to test. I keep getting the error:
NameError: name 'player_card' is not defined
Here is my code:
class Dog_card:
def __init__(self):
self.name = ""
self.friendliness = ""
def printing_card(self):
prnt_str = "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
return prnt_str
def printing_player_card():
player_card = Dog_card()
player_card.name = dogs_list_player[0]
player_card.friendliness = random.randint(1,101)
def printing_computer_card():
computer_card = Dog_card()
computer_card.name = dogs_list_computer[0]
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")
Any help would be appreciated
The problem is as it's stated in the error. Basically you are trying to use player_card when it is not defined inside the definition of choose_category(). I suggest you pass the value of player_card to the function like the following
def choose_category(player_card):
or you can define it as an attribute so that it can be accessed by the methods of the same class.
you need to initialize play_card before using it. Maybe you call printing_player_card in order to intnialize before, but as you don't return anything from that function, the created object and the variable player_card only lives in scope of the function. When that function finished, player_card object variable is unknown and the object is destroyed.
if you want player_card (as well as computer_card) survice its function, you need to return it an save it to a variable outside the function code.
Furthermore your function name "printing" is bad, as you don't print anything. You just initialize your object.
Maybe that's what you are aiming at.
class Dog_card:
def __init__(self, name, friendliness=1):
self.name = name
self.friendliness = friendliness
def __str__(self):
return "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
player_card = Dog_card(dogs_list_player[0], random.randint(1,101))
computer_card = Dog_card(dogs_list_copmuter[0])
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")

Entering a Changing Class Object into a List for Python

I'm trying to make a program that creates objects from another class I made and calls the class methods based on user input. The problem I'm having is that once a object is created I'm trying to enter that object into a dictionary, so I can compress it with pickle for later use. I'm having trouble trying to find the best way to append these class objects into a list when the name for the created objects are the same as the name variable I prompt from the user. The lines I am talking about are lines 34 to 41. I have so far change it to set the object named personObject to create a object and repeat if another user is created. It seems to work, I just feel there is a better way.
from budgetaccount import *
import pickle
import sys
class mainprogram:
def __init__(self):
self.account_list = {}
self.name = ""
def main(self):
grab_user()
endProgram = 0
while endProgram != 6:
print('Welcome to our monthly budget program\n')
print('1-Create a new account')
print('2-Exit')
selection = input("Enter your Selection: ")
if selection != "":
choice = int(selection)
if choice == 1:
self.create_user()
if choice == 2:
break
continue
name = self.account_list[0]
name.showSetBudgetLimits()
def create_user(self):
cancel = False
while (True):
self.name = input("Type your username: ")
name = self.name
income = float(input("Enter your income: "))
personObject = BudgetAccount(name, income)
personObject.setUserExspenseLimit()
self.account_list.append({
"%s"% (name) : personObject
})
cont = input("Want to add another? (Y/N)")
if cont == "N":
break
continue
print(self.account_list)
self.pickle_data1()
def pickle_data1(self): ###Pickle writes to userdata1.pickle from account_list###
pickle_out = open("userdata1.pickle", "wb")
pickle.dump(self.account_list, pickle_out)
pickle_out.close()
def grab_user():
pickle_in = open("E:/Python/Lib/idlelib/userdata1.pickle","rb")
account_list = pickle.load(pickle_in)
print(account_list)
print(account_list)
test = ihateThis()
test.main()

Why am I getting an error of list not being defined?

I keep getting an error:
NameError: name 'animal_list' is not defined for line 4
I have gone through my code and can't seem to figure out why. Thanks for any help!
import Animal
def main():
animals = make_list()
print("Here is the data you entered:", display_list(animal_list))
def make_list():
animal_list = []
run = True
while(run):
atype = input("What type of animal would you like to create? ")
aname = input("What is the animals name? ")
alist = Animal.Animal(atype, aname)
animal_list.append(alist)
another = input("Would you like to add more animals (y/n)? ")
if (another !="y"):
run = False
return animal_list
def display_list(animal_list):
print("Animal List")
print("------------")
print()
for item in animal_list:
print(item.get_name(), "the", item.get_animal_type(), "is")
main()
You are not passing the animals but animal_list, change to this, should work:
def main():
animals = make_list()
print("Here is the data you entered:", display_list(animals))
As the animal_list is within make_list function scope, and you have no access to this name within main() function scope.
As you're returning animal_list from make_list and assign animals to the result, you should just pass this to display_list directly.

python: global name 'user_input' is not defined

I keep getting the error message "global name 'user_input' not defined. new to python and to SO, hope you can help. Here's my code. Sorry if it's a mess. just starting out and teaching myself...
def menu():
'''list of options of unit types to have converted for the user
ex:
>>> _1)Length
_2)Tempurature
_3)Volume
'''
print('_1)Length\n' '_2)Temperature\n' '_3)Volume\n' '_4)Mass\n' '_5)Area\n'
'_6)Time\n' '_7)Speed\n' '_8)Digital Storage\n')
ask_user()
sub_menu(user_input)
def ask_user():
''' asks the user what units they would like converted
ex:
>>> what units do you need to convert? meter, feet
>>> 3.281
'''
user_input = input("Make a selection: ")
print ("you entered", user_input)
#conversion(user_input)
return user_input
def convert_meters_to_feet(num):
'''converts a user determined ammount of meters into feet
ex:
>>> convert_meters_to_feet(50)
>>> 164.042
'''
num_feet = num * 3.28084
print(num_feet)
def convert_fahrenheit_to_celsius(num):
'''converts a user determined temperature in fahrenheit to celsius
ex:
>>> convert_fahrenheit_to_celsius(60)
>>> 15.6
>>> convert_fahrenheit_to_celsius(32)
>>> 0
'''
degree_celsius = (num - 32) * (5/9)
print(round(degree_celsius, 2))
def sub_menu(num):
'''routes the user from the main menu to a sub menu based on
their first selection'''
if user_input == '1':
print('_1)Kilometers\n' '_2)Meters\n' '_3)Centimeters\n' '_4)Millimeters\n'
'_5)Mile\n' '_6)Yard\n' '_7)Foot\n' '_8)Inch\n' '_9)Nautical Mile\n')
ask = input('Make a selection (starting unit)')
return
if user_input == '2':
print('_1)Fahrenheit\n' '_2)Celsius\n' '_3)Kelvin\n')
ask = input('Make a selection (starting unit)')
return
When you do:
user_input = input("Make a selection: ")
Inside the ask_user() function, you can only access user_input inside that function. It is a local variable, contained only in that scope.
If you want to access it elsewhere, you can globalise it:
global user_input
user_input = input("Make a selection: ")
I think what you were trying was to return the output and then use it. You kind of got it, but instead of ask_user(), you have to put the returned data into a variable. So:
user_input = ask_user()
THere's no need to globalise the variable (as I showed above) if you use this method.
In your menu function, change the line that says ask_user() to user_input = ask_user().

I keep getting a naming error when i try to run this piece of code (Python)

class game_type(object):
def __init__(self):
select_game = raw_input("Do you want to start the game? ")
if select_game.lower() == "yes":
player1_title = raw_input("What is Player 1's title? ").lower().title()
class dice_roll(object,game_type):
current_turn = 1
current_player = [player1_title,player2_title]
def __init__(self):
while game_won == False and p1_playing == True and p2_playing == True:
if raw_input("Type 'Roll' to start your turn %s" %current_player[current_turn]).lower() == "roll":
I keep getting an error which reads:
NameError: name 'player1_title' is not defined
I understand that title is a function so i did try using player1_name and player1_unam but these also returned the same error :(
can somebody please help
All answers are greatly appreciated
There are a number of things leading to the NameError.
For one, the __init__ method of game_type does not save any data. To assign instance variables you have to specify the class instance with self.. If you don't, you're just assigning local variables.
Secondly, you must explicitly call a parent class's __init__ function with super() if you are creating a new one in a child class and still want the effects of the parent's.
So basically, your code should be
# Class names should be CapCamelCase
class Game(object):
def __init__(self):
select_game = raw_input("Do you want to start the game? ")
if select_game.lower() == "yes":
self.player1_title = raw_input("What is Player 1's title? ").lower().title()
# Maybe you wanted this in DiceRoll?
self.player2_title = raw_input("What is Player 1's title? ").lower().title()
# If Game were a subclass of something, there would be no need to
# Declare DiceRoll a subclass of it as well
class DiceRoll(Game):
def __init__(self):
super(DiceRoll, self).__init__(self)
game_won = False
p1_playing = p2_playing = True
current_turn = 1
current_players = [self.player1_title, self.player2_title]
while game_won == False and p1_playing == True and p2_playing == True:
if raw_input("Type 'Roll' to start your turn %s" % current_players[current_turn]).lower() == "roll":
pass

Categories