"Can't assign to function call" Python error - python

import sys
import os.path
class Juvenile(object):
def createJuv(self, pop, rate):
self.pop = pop
self.rate = rate
def displayJuvpop(self):
return self.pop
def displayjuvRate(self):
return self.rate
class Adult(object):
def createAd(self, pop, rate, brate):
self.pop = pop
self.rate = rate
self.brate = brate
def displayAdpop(self):
return self.pop
def displayAdRate(self):
return self.rate
def displayBirthrate(self):
return self.brate
class Senile(object):
def createSe(self, pop, rate):
self.pop = pop
self.rate = rate
def displaySepop(self):
return self.pop
def displaySerate(self):
return self.rate
a = Juvenile()
b = Adult()
c = Senile()
`enter code here`pop_model = raw_input("Enter the number of generations: ")
`enter code here`pop_model = int(pop_model)
newjuv = 0
newsen = 0
newadu = 0
def menu():
This = True
while This == True:
print("1) Enter Generation 0 values")
print("2) Display Generation 0 values")
print("3) Run the model")
print("4) Export data")
print("5) Quit")
decision = raw_input("")
if decision == "1":
Gen0values()
elif decision == "2":
display()
elif decision == "3":
run()
elif decision == "4":
export()
elif decision == "5":
sys.exit()
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
def Gen0values():
a.createJuv(float(raw_input("Enter the juvenile population: ")), float(raw_input("Enter the Juvenile survival rate: ")))
b.createAd(float(raw_input("Enter the Adult population: ")), float(raw_input("Enter the Adult survival rate: ")), float(raw_input("Enter the birth rate: ")))
c.createSe(float(raw_input("Enter the Senile population: ")), float(raw_input("Enter the Senile survival rate: ")))
menu()
The error is coming up here:
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
The error comes up with "Can't assign to function call, line 60". Due to stack overflow's code to text limit, I've removed parts of the program that are irrelevant, like exporting the data and displaying the values.
Ps: This isn't an indentation error, copying and pasting somewhat disrupted it.

Your display*pop() functions return a value, not a variable. You can't assign to that function result. Just assign directly to the attributes:
a.pop = newjuv
b.pop = newsen
c.pop = newadu

Related

How can I change a working python program so that it runs as python flask program

I have a python program, an expert system, it runs ok as a purely python program. but I now want to run it as a python flask program so that it can appear as on a browser and maybe be integrated as a whatsapp or sms chatbot.
the change from just python to make the code into sort of a chatbot is what I am looking for.
# from pyknow import *
from experta import *
from flask import Flask
# import os
app = Flask(__name__)
# print(os.getcwd())
diseases_list = []
diseases_symptoms = []
symptom_map = {}
d_desc_map = {}
d_treatment_map = {}
def preprocess():
global diseases_list,diseases_symptoms,symptom_map,d_desc_map,d_treatment_map
diseases = open("diseases.txt")
diseases_t = diseases.read()
diseases_list = diseases_t.split("\n")
diseases.close()
for disease in diseases_list:
#symptoms=os.path.dirname("symptoms/"+ disease + ".txt")
disease_s_file = open("Dsymptoms/"+ disease + ".txt")
disease_s_data = disease_s_file.read()
s_list = disease_s_data.split("\n")
diseases_symptoms.append(s_list)
symptom_map[str(s_list)] = disease
disease_s_file.close()
disease_s_file = open("Ddescriptions/" + disease + ".txt")
disease_s_data = disease_s_file.read()
d_desc_map[disease] = disease_s_data
disease_s_file.close()
disease_s_file = open("Dtreatments/" + disease + ".txt")
disease_s_data = disease_s_file.read()
d_treatment_map[disease] = disease_s_data
disease_s_file.close()
def identify_disease(*arguments):
symptom_list = []
for symptom in arguments:
symptom_list.append(symptom)
# Handle key error
return symptom_map[str(symptom_list)]
def get_details(disease):
return d_desc_map[disease]
def get_treatments(disease):
return d_treatment_map[disease]
def if_not_matched(disease):
print("")
id_disease = disease
disease_details = get_details(id_disease)
treatments = get_treatments(id_disease)
print("")
print("The most probable disease that you have is %s\n" %(id_disease))
print("A short description of the disease is given below :\n")
print(disease_details+"\n")
print("The common nutritional treatments recommended by doctors, nurses and nutrionists are \n")
print(treatments+"\n")
def identify_disease(*arguments):
symptom_list = []
for symptom in arguments:
symptom_list.append(symptom)
# Handle key error
return symptom_map[str(symptom_list)]
def get_details(disease):
return d_desc_map[disease]
def get_treatments(disease):
return d_treatment_map[disease]
def if_not_matched(disease):
print("")
id_disease = disease
disease_details = get_details(id_disease)
treatments = get_treatments(id_disease)
print("")
print("The most probable disease that you have is %s\n" %(id_disease))
print("A short description of the disease is given below :\n")
print(disease_details+"\n")
print("The common nutritional treatments recommended by doctors, nurses and nutrionists are: \n")
print(treatments+"\n")
# #my_decorator is just a way of saying just_some_function = my_decorator(just_some_function)
#def identify_disease(bloated_stomach, thin_limbs,reddish hair, swollen face):
#app.route('/')
class Greetings(KnowledgeEngine):
#DefFacts()
def _initial_action(self):
print("")
print("Hi! I am Dr.Jephtah, I am here to help your child's health better.")
print("Firstly I am are assuming that the child is under the age of 6 as this system works best for those childeren ")
print("For that you'll have to answer a few questions about your conditions")
print("Do you feel any of the following symptoms:")
print("")
yield Fact(action="find_disease")
#Rule(Fact(action='find_disease'), NOT(Fact(slight_hair=W())),salience = 1)
def symptom_0(self):
self.declare(Fact(slight_hair=input("slight hair: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(reddish_hair=W())),salience = 1)
def symptom_1(self):
self.declare(Fact(reddish_hair=input("reddish hair: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(hair_falling=W())),salience = 1)
def symptom_2(self):
self.declare(Fact(hair_falling=input("hair falling easily: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(abnormal_skin=W())),salience = 1)
def symptom_3(self):
self.declare(Fact(abnormal_skin=input("abnormal skin (eg skin shedding, lessions, skin ulcers): ")))
#Rule(Fact(action='find_disease'), NOT(Fact(swollen_face=W())),salience = 1)
def symptom_4(self):
self.declare(Fact(swollen_face=input("Swollen Face: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(glazed_eyes=W())),salience = 1)
def symptom_5(self):
self.declare(Fact(glazed_eyes=input("glazed eyes: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(apathetic=W())),salience = 1)
def symptom_6(self):
self.declare(Fact(apathetic=input("child is apathetic: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(smaller_muscles=W())),salience = 1)
def symptom_7(self):
self.declare(Fact(smaller_muscles=input("smaller muscles: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(anaemic=W())),salience = 1)
def symptom_8(self):
self.declare(Fact(anaemic=input("anaemic (weak/tired): ")))
#Rule(Fact(action='find_disease'), NOT(Fact(diarrhoea=W())),salience = 1)
def symptom_9(self):
self.declare(Fact(diarrhoea=input("diarrhoea: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(bloated_stomach=W())),salience = 1)
def symptom_10(self):
self.declare(Fact(bloated_stomach=input("bloated stomach: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(thin_body=W())),salience = 1)
def symptom_11(self):
self.declare(Fact(thin_body=input("thin body: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(older_face=W())),salience = 1)
def symptom_12(self):
self.declare(Fact(older_face=input("Face looks older: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(cranky_child=W())),salience = 1)
def symptom_13(self):
self.declare(Fact(cranky_child=input("cranky child: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(wrinkled_skin=W())),salience = 1)
def symptom_14(self):
self.declare(Fact(wrinkled_skin=input("Wrinkled skin: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(little_fattie_tissue=W())),salience = 1)
def symptom_15(self):
self.declare(Fact(little_fattie_tissue=input("Liitle fattie tissue on hips and others: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(converse_stomach_rib_prominent=W())),salience = 1)
def symptom_16(self):
self.declare(Fact(converse_stomach_rib_prominent=input("converse stoamch rib prominent: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(chronic_infections=W())),salience = 1)
def symptom_17(self):
self.declare(Fact(chronic_infections=input("repeated chronic infections: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(skin_reddish_purging=W())),salience = 1)
def symptom_18(self):
self.declare(Fact(skin_reddish_purging=input("Skin reddish or purging: ")))
#Rule(Fact(action='find_disease'), NOT(Fact(age=W())),salience = 20)
def symptom_19(self):
self.declare(Fact(age=input("Is age below 2 years: ")))
#Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="no"),Fact(bloated_stomach="yes"),Fact(thin_body="no"),Fact(older_face="no"),Fact(child_cranky="no"),Fact(wrinkled_skin="no"),Fact(little_fattie_tissue="no"),Fact(converse_stomach_rib_prominent="no"),Fact(chronic_infections="no"),Fact(skin_reddish_purging="no"),Fact(age="no"))
def disease_0(self):
self.declare(Fact(disease="Kwashiorkor"))
#Rule(Fact(action='find_disease'),Fact(slight_hair="no"),Fact(reddish_hair="no"),Fact(hair_falling="no"),Fact(abnormal_skin="yes"),Fact(swollen_face="no"),Fact(glazed_eyes="no"),Fact(apathetic="no"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="no"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="no"))
def disease_1(self):
self.declare(Fact(disease="Marasmus"))
#Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="yes"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="no"))
def disease_2(self):
self.declare(Fact(disease="Marasmus-Kwashiorkor"))
#Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="no"),Fact(bloated_stomach="yes"),Fact(thin_body="no"),Fact(older_face="no"),Fact(child_cranky="no"),Fact(wrinkled_skin="no"),Fact(little_fattie_tissue="no"),Fact(converse_stomach_rib_prominent="no"),Fact(chronic_infections="no"),Fact(skin_reddish_purging="no"),Fact(age="yes"))
def disease_3(self):
self.declare(Fact(disease="Kwashiorkor_"))
#Rule(Fact(action='find_disease'),Fact(slight_hair="no"),Fact(reddish_hair="no"),Fact(hair_falling="no"),Fact(abnormal_skin="yes"),Fact(swollen_face="no"),Fact(glazed_eyes="no"),Fact(apathetic="no"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="no"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="yes"))
def disease_4(self):
self.declare(Fact(disease="Marasmus_"))
#Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="yes"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="yes"))
def disease_5(self):
self.declare(Fact(disease="Marasmus-Kwashiorkor_"))
#Rule(Fact(action='find_disease'),Fact(disease=MATCH.disease),salience = -998)
def disease(self, disease):
print("")
id_disease = disease
disease_details = get_details(id_disease)
treatments = get_treatments(id_disease)
print("")
print("The most probable disease that you have is %s\n" %(id_disease))
print("A short description of the disease is given below :\n")
print(disease_details+"\n")
print("The common treatments recommended by experts are: \n")
print(treatments+"\n")
#Rule(Fact(action='find_disease'),
Fact(slight_hair=MATCH.slight_hair),
Fact(reddish_hair=MATCH.reddish_hair),
Fact(hair_falling=MATCH.hair_falling),
Fact(abnormal_skin=MATCH.abnormal_skin),
Fact(swollen_face=MATCH.swollen_face),
Fact(glazed_eyes=MATCH.glazed_eyes),
Fact(apathetic=MATCH.apathetic),
Fact(smaller_muscles=MATCH.smaller_muscles),
Fact(anaemic=MATCH.anaemic),
Fact(diarrhoea=MATCH.diarrhoea),
Fact(bloated_stomach=MATCH.bloated_stomach),
Fact(thin_body=MATCH.thin_body),
Fact(older_face=MATCH.older_face),
Fact(cranky_child=MATCH.cranky_child),
Fact(wrinkled_skin=MATCH.wrinkled_skin),
Fact(little_fattie_tissue=MATCH.little_fattie_tissue),
Fact(converse_stomach_rib_prominent=MATCH.converse_stomach_rib_prominent),
Fact(chronic_infections=MATCH.chronic_infections),
Fact(skin_reddish_purging=MATCH.skin_reddish_purging),
Fact(age=MATCH.age),NOT(Fact(disease=MATCH.disease)),salience = -999)
# Fact(age=MATCH.age),
def not_matched(self,slight_hair, reddish_hair, hair_falling, abnormal_skin, swollen_face, glazed_eyes, apathetic, smaller_muscles, anaemic ,diarrhoea ,bloated_stomach ,thin_body ,older_face, cranky_child ,wrinkled_skin ,little_fattie_tissue ,converse_stomach_rib_prominent ,chronic_infections, skin_reddish_purging, age):
print("\nDid not find any disease that matches your exact symptoms")
lis = [slight_hair, reddish_hair, hair_falling, abnormal_skin, swollen_face, glazed_eyes, apathetic, smaller_muscles,anaemic ,diarrhoea ,bloated_stomach ,thin_body ,older_face, wrinkled_skin, cranky_child, little_fattie_tissue, converse_stomach_rib_prominent, chronic_infections, skin_reddish_purging, age]
max_count = 0
max_disease = ""
for key,val in symptom_map.items():
count = 0
temp_list = eval(key)
for j in range(0,len(lis)):
if(temp_list[j] == lis[j] and lis[j] == "yes"):
count = count + 1
if count > max_count:
max_count = count
max_disease = val
if_not_matched(max_disease)
if __name__ == "__main__":
preprocess()
engine = Greetings()
while(1):
engine.reset() # Prepare the engine for the execution.
engine.run() # Run it!
print("Would you like to diagnose some other symptoms?")
if input() == "no":
exit()
#print(engine.facts)
`
You need to follow the steps in a Flask tutorial. Take a look at this one

finding the highest hour in a list

class volunteerList:
def __init__ (self, groupName):
self.__vList = []
self.__groupName = groupName
def setGroupName (self, newGroupName):
self.__groupName = newGroupName
def getGroupName (self):
return self.__groupName
def getvList (self):
return self.__vList
def addVolunteer (self, volunteer):
self.getvList().append(volunteer)
def highestHour (self):
details = ""
highestHourList = []
highest = self.__vList[0].getHourContribution()
for volunteer in self.__vList:
hour = volunteer.getHourContribution()
if hour == highest:
highestHourList.append(hour)
elif hour > highest:
highestHourList = [hour]
highest = hour
#highestHourList.append(hour)
if volunteer.getType().lower() == "f":
details = details + "{} - {} years old - flood volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "p":
details = details + "{} - {} years old - pandemic volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "e":
details = details + "{} - {} years old - earthquake volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "t":
details = details + "{} - {} years old - tsunami volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
return details
def main ():
groupName = input("Enter your group name: ")
newGroup = volunteerList(groupName)
print ("\n")
choice = menu()
while choice != "0":
if choice == "1":
name = input("Name of volunteer? ")
age = int(input("Age? "))
volunteerType = input("Type of volunteer ('F/P/E/T'): ")
volunteerType = volunteerType.lower()
while volunteerType not in "fpet":
print ("Invalid type! Please enter again!")
volunteerType = input("Type of volunteer ('F/P/E/T'): ")
volunteerType = volunteerType.lower()
hourCont = int(input("Contribution hour? "))
while hourCont <= 0:
print ("Invalid value! Please enter again!")
hourCont = int(input("Contribution hour? "))
newGroup.addVolunteer(volunteer(name, age, volunteerType, hourCont))
print ("... Volunteer has been added successfully.")
print ("\n")
choice = menu()
elif choice == "6":
print ("Volunteer with highest contribution hour:")
print (newGroup.highestHour())
print ("\n)
I'm not sure the code on highestHour() correct or wrong. I was planning to find the highest hour of the volunteer(s). If there are more than 1 highest hour of volunteer (same hour), display everything. My output was only one highest hour of volunteer or display 2 same line of statement instead of the example before.
Wondering how to display all volunteer that are highest hour?
The display sample will be:
a - 36 years old - pandemic volunteer
b - 25 years old - flood volunteer
Here you go:
class volunteer:
def __init__ (self, name, age, type, hourContribution):
self.__name = name
self.__age = age
self.__type = type
self.__hourContribution = hourContribution
def getHourContribution (self):
return self.__hourContribution
class volunteerList:
def __init__ (self, groupName):
self.vList = []
self.__groupName = groupName
def highestHour (self):
highHourList = []
hourList = []
for volunteer in self.vList:
hourList.append(volunteer.getHourContribution())
highest = max(hourList)
for hour in hourList:
if hour == highest:
highHourList.append(hour)
print(highHourList)
new = volunteerList("one")
vol1 = volunteer("", 1, "", 5)
vol2 = volunteer("", 1, "", 10)
vol3 = volunteer("", 1, "", 10)
vol4 = volunteer("", 1, "", 10)
vol5 = volunteer("", 1, "", 1)
new.vList = [vol1, vol2, vol3, vol4, vol5]
new.highestHour()
Alternative highestHour function
def highestHour (self):
highHourList = []
largest = self.vList[0].getHourContribution()
for volunteer in self.vList:
hour = volunteer.getHourContribution()
if hour == largest:
highHourList.append(hour)
elif hour > largest:
highHourList = [hour]
largest = hour
print(highHourList)
Needs some cleaning up, but you get the idea.

Python - passing a class through a function resulting in error

I have been programming a piece of code to try and carry through a class from one function to another (the code is also broken in other ways but those aren't the important ones). The major problem if you define a class in the enter function it then gives the error:
exec("""print({}.Show())""".format(x))
File "<string>", line 1, in <module>
NameError: name (whatever I have called the class title) is not defined
in the tr function.
import pickle
import traceback
import sys
classtitles = []
class Customer(object):
def __init__(self):
try:
self.load()
print(self.customer)
except:
None
def init2(self,customer_name,home_address,telephone_number):
self.customer = customer_name
self.address = home_address
self.phone = telephone_number
print(self.customer)
classtitles.append(self.customer)
def carpet_amounts(self, carpet_type, grippers_bool):
self.type = carpet_type
self.grippers = grippers_bool
def price(self, size, perimeter):
self.size = size
self.perimeter = perimeter
self.price = 0
if self.type == "First":
self.price = float(5.99) * self.size
if self.type == "Monarch":
self.price = float(7.99) * self.size
if self.type == "Royal":
self.price = int(60) * self.size
price_add = float(22.5) * self.size
if self.grippers == True:
price_add += self.perimeter * float(1.10)
hours = 0
while size >= 16:
hours += 1
size -= 16
self.hours = hours
price_add += hours * 65
self.price += price_add
def Show(self):
print("show")
if self.grippers == True:
grips = "with"
else:
grips = "without"
return ("the size is {}m^2 and with a {} undercarpet and {} grippers, totalling more than {} hours of work is {}".format(self.size,self.type,grips,self.hours,self.price))
def save(self):
"""save class as self.name.txt"""
file = open('ClassSave.txt','wb')
file.write(pickle.dumps(self.__dict__))
file.close()
def load(self):
"""try load self.name.txt"""
file = open('ClassSave.txt','r')
datapickle = file.read()
file.close()
self.__dict__ = pickle.loads(dataPickle)
def loadf():
f = open('classnames.txt','r')
mylist = f.read().splitlines()
for x in mylist:
exec("""{} = Customer()""".format(mylist[0]))
customs()
def customs():
try1 = input("Would you like to 1. Enter a new customer. 2. View all the customers. 3. Delete an old customer")
if try1 == '1':
enter()
elif try1 == 'q':
sys.exit()
else:
tr()
def enter():
name = input("What is thr customers name (no space i.e. 'JoeBloggs')? ")
address = input("What is their address")
phonenumber = str("What is their phone number")
exec("""{} = Customer()""".format(name))
exec("""{}.init2("{}","{}","{}")""".format(name,name,address,phonenumber))
print(classtitles)
carpet_type = input("What type of carpet would they like ('First','Monarch','Royal')? ")
grips = str(input("Would they like grips (1 = yes, 2 = no)? "))
if grips == '1':
grips = True
else:
grips = False
exec("""{}.carpet_amounts("{}",{})""".format(name,carpet_type,grips))
size = int(input("What is the m^2 size of their carpet? "))
perimeter = int(input("What is the m perimeter of their carpet? "))
exec("""{}.price({},{})""".format(name,size,perimeter))
exec("print({}.Show())".format(name))
file2 = open('classnames.txt','w')
for x in classtitles:
file2.write(x)
file2.close()
exec("{}.save()".format(name))
customs()
def tr():
x = input("name")
print(x)
exec("""print({}.Show())""".format(x))
customs()
loadf()

AttributeError: 'str' object has no attribute (function)

I'm trying to write an object-oriented program that allows me to enter and store monthly income and bills, and view all data as needed. I can successfully store an object, but when I try to use my view_all function, I get this error:
in view_all print(item.get_month())
AttributeError: 'str' object has no attribute 'get_month'
If you could help me track down this problem I'd be grateful!
# Create a month class
class Month:
# Use __init__ method to initialize the attributes
def __init__(self, month, income, tds, pnm, zia, water):
self.__month = month
self.__income = income
self.__tds = tds
self.__pnm = pnm
self.__zia = zia
self.__water = water
# The set methods accept arguments:
def set_month(self, month):
self.__month = month
def set_income(self, income):
self.__income = income
def set_tds(self, tds):
self.__tds = tds
def set_pnm(self, pnm):
self.__pnm = pnm
def set_zia(self, zia):
self.__zia = zia
def set_water(self, water):
self.__water = water
# The get methods return the data:
def get_month(self):
return self.__month
def get_income(self):
return self.__income
def get_tds(self):
return self.__tds
def get_pnm(self):
return self.__pnm
def get_zia(self):
return self.__zia
def get_water(self):
return self.__water
# The __str__ method return's the object's state as a string
def __str__(self):
return "Month: " + self.__month + \
"\nIncome: " + self.__income + \
"\nTDS: " + self.__tds + \
"\nPNM: " + self.__PNM + \
"\nZia: " + self.__zia + \
"\nWater: " + self.__water
And the main program:
import Month_Class
import pickle
ADD_MONTH = 1
VIEW_ALL = 2
QUIT = 3
FILENAME = 'ruidoso.dat'
def main():
months = load_months()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == ADD_MONTH:
add_month(months)
elif choice == VIEW_ALL:
view_all(months)
save_months(months)
def load_months():
try:
input_file = open(FILENAME, 'rb')
months_dct = pickle.load(input_file)
input_file.close
except IOError:
month_dct = {}
return month_dct
def get_menu_choice():
print()
print('Menu')
print('------------------')
print("1. Add data for a new month")
print("2. View data for all months")
print('Any other number saves and quits the program!')
print()
choice = int(input('Enter your choice: '))
while choice < ADD_MONTH or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def add_month(months):
month = input('Enter the name of the month: ')
income = input('Total income for this month: ')
tds = input('TDS Broadband bill total: ')
pnm = input('PNM bill total: ')
zia = input('Zia Natural Gas bill total: ')
water = input('City of Ruidoso bill total: ')
entry = Month_Class.Month(month, income, tds, pnm, zia, water)
if month not in months:
months[month] = entry
print('The entry has been added')
else:
print('That month already exists!')
def save_months(months):
output_file = open(FILENAME, 'wb')
pickle.dump(months, output_file)
output_file.close()
def view_all(months):
for item in months:
print(item.get_month())
print(item.get_income())
print(item.get_tds())
print(item.get_pnm())
print(item.get_zia())
print(item.get_water())
main()
You need to iterate over the dictionary differently
for month, item in months.items():
print(item.get_month())
...
In the view_all method, you must to iterate over dictionary:
for key, item in months.iteritems():
print(item.get_month())
and you got other error in __str__ method of Month class:
"\nPNM: " + self.__PNM + \
the correct is:
"\nPNM: " + self.__pnm + \

Recording a win or loss in a game of craps

So I have to create a game of craps that takes into account bets for an assignment. So far, my code works in that the dice rolls are correct and other little tidbits the assignment called for. But now I don't know how to record each game as a win / lose for the player or computer so that the pot can be added to the winner's money. I realize that my code is half doe, isn't finished, and doesn't run as is, but I just seriously need some help from someone. Please and thank you. Here are more specific directions on my assignment:
http://www.ics.uci.edu/~kay/courses/i42/hw/labA.html
import random
def craps():
print("Welcome to Sky Masterson's Craps Game")
handle_commands()
def handle_commands(): # Collection -> Collection (plus interaction)
""" Display menu to user, accept and process commands
"""
playerInitial = 500
compInitial = 500
MENU = "How much would you like to bet?: "
while True:
bet = float(input(MENU))
if bet <= playerInitial:
human_game()
elif bet > playerInitial:
print("Sorry, you can't bet more than you have")
def handle_commands2():
MENU2 = "Would you like to play again? (y or n): "
while True:
response = input (MENU2)
if response=="y":
counter = counter + multipleGames()
elif response=="n":
while ( counter < 2000):
roll = random.randint(1, 6) + random.randint(1,6)
updateCount(roll)
counter += 1
print ("Thank you for playing." + "\n" + "\n" + "Distribution of dice rolls: " + "\n")
return
else:
invalid_command(response)
def invalid_command(reponse):
"""print message for invalid menu command.
"""
print("Sorry; '" + response + "' isn't a valid command. Please try again.")
def play_game():
"""prints shooters roll results
"""
diceRoll = 0
roll = random.randint(1, 6) + random.randint(1, 6)
updateCount(roll)
diceRoll = diceRoll + 1
point = 0
print("The roll is " + str(roll))
response = (roll)
if response== 7 or response== 11:
print("Natural; shooter wins" + "\n" + "Thank you for playing")
handle_commands2()
elif response== 2 or response== 3 or response== 12:
print("Crapped out; shooter loses" + "\n" + "Thank you for playing")
handle_commands2()
else:
print("The point is " + str(roll))
point = roll
secondRoll = 0
handle_commands()
while (secondRoll !=point) and (secondRoll != 7):
secondRoll = random.randint(1, 6) + random.randint(1, 6)
updateCount(secondRoll)
diceRoll += 1
print("The roll is " + str(secondRoll))
handle_commands()
if secondRoll== point:
print ("Made the point; shooter wins." + "\n" + "Thank you for playing")
handle_commands2()
elif (secondRoll == 7):
print ("Crapped out; shooter loses." + "\n" + "Thank you for playing")
handle_commands2()
return diceRoll
def multipleGames():
gameCounter = 0
while (gameCounter <= 2000):
print("Your game: ")
gameCounter += play_game()
print("\n")
print("Computer's game: ")
gameCounter += play_game()
print( "\n")
return gameCounter
def updateCount(point):
count =List[point] + 1
List[point] = count
List = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
def human_game():
playerInitial = 500
compInitial = 500
while True:
play_game()
if
playerInitial += bet
compInitial += bet
counter = 0
counter = counter + multipleGames()
playerInitial -= bet
craps()
for point in List:
print("%2d" %(point) + ": " + "%3d" %(List[point]) + " " + "(" + ("%2d" % (int((List[point])/2000*100)))+ "%" + ")" + " " + ("*" *(int((List[point])/2000*100))))
Use classes:
import random
class Human:
def __init__(self):
self.name = 'Human'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Computer:
def __init__(self):
self.name = 'Computer'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Game:
def __init__(self):
self.rolls = []
self.currentPlayer = None
def roll(self):
self.rolls.append(random.randint(1, 6))
if __name__ == '__main__':
human = Human()
computer = Computer()
game = Game()
game.roll()
print games.rolls
I won't code all of it for you, but using classes will make things much simpler.

Categories