Unable to Execute Python Methods - python

Despite my best attempt, I am unable to make a dent into getting the required output. I have provided my progress so far (after the question).
Write a class named Patient that has the following data attributes:
name ( type string), height (type float), has_hair (type
Boolean)
The Patient class should have an __init__ method (i.e., an initializer) that accepts the Patient’s name, height, and has_hair as arguments. These values should be assigned to the object's name, height, and has_hair data attributes. By default, let has_hair = 0
Each Patient should start with 0 tablets, stored in an attribute tablets.
A collect_tablets(number) method adds the given number of tablets to the Patient's number. This function should also be able to be called as collect_tablets() which just adds one barange to the total number.
An eat() method consumes one tablet from the Patient's total, but increases the height of the Patient by 0.1m. If the Patient does not have any baranges, the method should print
"I don't have any tablets to eat!."
A 'feast()' method consumes five tablets from the Patient's total. If the Patient is not hairy when he feasts, he grows hair. If the Patient is already hairy when he feasts, he grows by 50% instead (for example: a 2 m Patient grows to 3 m).
A bald Patient that feasts, only grows hair, he does not grow in height unless he feasts later. If the Patient does not have enough tablets for a feast, the method should print
“I don't have enough tablets to feast!.”
TEST CASE:
hungry_patient = Patient("Jack", 1.89)
hungry_patient.collect_tablets()
hungry_patient.eat()
print(hungry_patient)
OUTPUT
Jack is a 1.99 m tall blork!
My Code is :
class Patient:
def __init__(self, name, height, tablets = 0, has_hair=False):
"""Blork constructor"""
self.name = name
self.height = height
self.tablets = tablets
self.has_hair = has_hair
def collect_tablets(self):
self.tablets = self.tablets + 1
def eat(self):
if self.tablets == 0:
print(“I don't have enough to eat”)
else:
self.tablets = self.tablets - 1
self.height = self.height + 0.1
def feast(self):
if self.tablets >= 5:
if self.has_hair == True:
self.height = self.height + 0.5 * (self.height)
if self.has_hair == False:
self.has_hair = True
else:
print("I don't have enough baranges to feast!")
hungry_patient = Patient("Jack", 1.89)
hungry_patient.collect_tablets()
hungry_patient.eat()
print(hungry_patient)
I am not able to get the program to execute.
Please help and advise me as to what I am doing wrong.

First, there are invalid characters in your code. On line 14:
print(“I don't have enough to eat”)
change the special opening and closing quotes to standard double quotes:
print("I don't have enough to eat")
After fixing the above and some indentation issues, the code runs, but the output is just a raw string representation of the object instance you're printing.
<__main__.Patient instance at 0x7f17180af3b0>
In order to define a custom string representation, you need to define an __str__ and/or __repr__ method on your class. Have a look at the Python documentation
def __str__(self):
return "%s is a %s m tall blork!" % (self.name, self.height)
Full working code:
class Patient:
def __init__(self, name, height, tablets = 0, has_hair=False):
"""Blork constructor"""
self.name = name
self.height = height
self.tablets = tablets
self.has_hair = has_hair
def collect_tablets(self):
self.tablets = self.tablets + 1
def eat(self):
if self.tablets == 0:
print("I don't have enough to eat")
else:
self.tablets = self.tablets - 1
self.height = self.height + 0.1
def feast(self):
if self.tablets >= 5:
if self.has_hair == True:
self.height = self.height + 0.5 * (self.height)
if self.has_hair == False:
self.has_hair = True
else:
print("I don't have enough baranges to feast!")
def __str__(self):
return "%s is a %s m tall blork!" % (self.name, self.height)
hungry_patient = Patient("Jack", 1.89)
hungry_patient.collect_tablets()
hungry_patient.eat()
print(hungry_patient)

Related

Python Inheritance error (with private variables)

I'm a beginner at coding and tried looking up the error but could not find why it showed up. Could someone please explain it to me?
My code as follows is:
class Automobile:
__material = None
__height = None
__width = None
__engine_size = None
def set_values(self, mat, height, width, engsz="M"):
self.__material = mat
self.__height = height
self.__width = width
self.__engine_size = engsz
def getMat(self):
return self.__material
def getHeight(self):
return self.__height
def getWidth(self):
return self.__width
def getEngineSize(self):
return self.__engine_size
class Car(Automobile):
__pricePU = None
def __findPricePerUnit(self):
return priceDict[self.getMat]
def price(self):
return self.getWidth * self.getHeight * self.__findPricePerUnit
print("A new car is being made")
print("What are the dimensions wanted for the new car in")
mat = input("Enter material: ")
height = input("Enter height: ")
width = input("Enter width: ")
car1 = Car()
car1.set_values(mat, height, width)
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price)
My input for this is:
iron=10,steel=20,gold=50,diamond=100
gold
1.5
5
The OUTPUT shown at the end is:
A new car has been made!
The price of this new car is:
<bound method Car.price of <__main__.Car object at 0x0000025DE7E84C70>>
I am not exactly sure why this is coming up, could someone please explain this to me!
There are several errors in the code, some of which are as follows:
On the last line, you should execute the price function like this car1.price()
In the price function, you should execute the functions instead of multiplying the pointers of the functions, like this:
def price(self):
return self.getWidth() * self.getHeight() * self.__findPricePerUnit()
There is no priceDict, so there will be an error in __findPricePerUnit as well.
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price())
Because price() is a method.

my method returns an address at the link of a value

This is an exercise that is not part of the training on the site, I do not understand why when I want to display the return value of the energy method of my satellite class, I receive an address on the console.
Zoe satellite speed = 40.0m / s.
<bound method Satellite.energie of <__ main __. Satellite object at 0x01A5E610 >>
Zoe satellite speed = 70.0m / s.
<bound method Satellite.energie of <__ main __. Satellite object at 0x01A5E610 >>
This is my code:
class Satellite (object):
"" "Satellite for instantiating objects simulating satellites
artificial launched into space, around the earth. "" "
def __init __ (self, name, mass = 100, speed = 0):
self.name = name
self.mass = mass
speed choke = speed
def impulse (self, force, duration):
"" "will vary the speed of the satellite." ""
speed self = speed self + (force * duration) / mass self
def energy (self):
"" "will refer to the program calling the kinetic energy value of the satellite" ""
return_val = self.mass * self.speed ** 2/2
return return_val
def display_speed (self):
"" "will display the name of the satellite and its current speed." ""
print ("satellite speed {0} = {1} m / s.". format (self.name, self.speed))
s1 = Satellite ('Zoe', mass = 250, speed = 10)
s1.pulse (500, 15)
s1.display_speed ()
print (s1.energy)
s1.pulse (500, 15)
s1.display_speed ()
print (s1.energy)
Your energy method is wrong, and it should have given a syntax error:
def energy (self):
"" "will refer to the program calling the kinetic energy value of the satellite" ""
return_val = self.mass * self.speed ** 2/2
return return_val
Not to mention, you need to invoke the energy method as well:
s1.pulse (500, 15)
s1.display_speed ()
print(s1.energy())
s1.pulse (500, 15)
s1.display_speed ()
print(s1.energy())
You are trying to overwrite the return statement and use it as a variable, which is just WRONG. There are other mistypings/issues in your code as well, but this one definitely seems to be main issue.
Rather than calling the function Satellite.energy(), you're trying to access the property Satellite.energy - if you change it to print(s1.energy()), it should display correctly!
As a note, some of your code has been formatted wrong here so it doesn't run - this works for me:
class Satellite (object):
"" "Satellite for instantiating objects simulating satellites artificial launched into space, around the earth. "" "
def __init__ (self, name, mass = 100, speed = 0):
self.name = name
self.mass = mass
self.speed = speed
def impulse (self, force, duration):
"" "will vary the speed of the satellite." ""
return self.speed + (force * duration) / self.mass
def energy (self):
"" "will refer to the program calling the kinetic energy value of the satellite" ""
return self.mass * self.speed ** 2/2
def display_speed (self):
"" "will display the name of the satellite and its current speed." ""
print ("satellite speed {0} = {1} m / s.". format (self.name, self.speed))
s1 = Satellite ('Zoe', mass = 250, speed = 10)
s1.impulse (500, 15)
s1.display_speed ()
print (s1.energy())
s1.impulse (500, 15)
s1.display_speed ()
print (s1.energy())

BMI in Python with file input

I have an assignment which I can't get through. I'm a beginner at programming and I want to understand it better for my course. Can someone help me? I really don't understand it.
This is the assignment:
The BMI is defined as weight/length2. A BMI between 18,5 and 25 as ideal and considers people with such a BMI healthy.
The program receives input consisting of two persons with their name, sex, length and weight.
Jack Johnson M 1.78 83
Maria Miller V 1.69 60
Process this input into structured data. To achieve this, use an useful class with useful methods to enhance the structure of the program. Use this structured data to print for each person: an appropriate style of address, surname, the BMI and a statement whether this is considered healthy or not.
Example:
Mr. Johnson’s BMI is 26.2 and is unhealthy.
Mrs. Miller’s BMI is 21.0 and is healthy.
This is what I have:
class Person(object):
def __init__(self):
self.first_name = first_name
self.last_name = last_name
self.sex = sex
self.length = length #m
self.weight = weight #kg
def bmi(self):
return self.weight / self.length ** 2
def healthy(self):
if BODYMASSINDEX <25 and BODYMASSINDEX>18.5:
person = healthy
else:
person = unhealthy
return person
from person import Person
file = open("BMIInput.txt")
invoer = file.read().splitlines()
details_person1 = invoer[0].split()
details_person2 = invoer[1].split()
person1 = Person(details_person1)
person2 = Person(details_person2)
print "%s's BMI is %.1f and is %s" %(person1.name, person1.bmi, person1.healthy)
The BMI Input is:
Jack Johnson M 1.78 83
Maria Miller V 1.69 60
Add the arguments to the init
class Person(object):
def __init__(self, first_name, last_name, sex, length, weight):
self.first_name = first_name
self.last_name = last_name
self.sex = sex
self.length = length #m
self.weight = weight #kg
def bmi(self):
return self.weight / self.length ** 2
def healthy(self):
if BODYMASSINDEX <25 and BODYMASSINDEX>18.5:
person = healthy
else:
person = unhealthy
return person
Then unpack the list:
from person import Person
file = open("BMIInput.txt")
invoer = file.read().splitlines()
details_person1 = invoer[0].split()
details_person2 = invoer[1].split()
person1 = Person(*details_person1)
person2 = Person(*details_person2)
print "%s's BMI is %.1f and is %s" %(person1.name, person1.bmi, person1.healthy)
Comment question about int, float is more what you need:
Just to solve the issue this is not clean nor the right way but it will work:
Inside the init
self.length = float(length) if type(length) != float else length
self.weight = float(weight) if type(weight) != float else weight
What I'd do is :
details_person1 = invoer[0].split()
details_person1[3] = float(details_person1[3])
details_person1[4] = float(details_person1[4])
The same thing with details_person2

Testing Python classes

class BMI():
def __init__(self,name=str,age=int,weight=float,height=float):
self.__name=name
self.__age=age
self.__weight=weight
self.__height=height
def get__BMI(self):
return self.__BMI
def get__Status(self):
return self.__Status
def get__Name(self):
return self.__Name
def get__Age(self):
return self.__Age
def get__Weight(self):
return self.__Weight
def get__Height(self):
return self.__Height
I was wondering if anyone could help with this, the problem is when I try to test it displays an error of "takes 0 positional arguments but 4 were given ":
from BMI import BMI
def main():
bmil=BMI("Odeh",18,140,72)
print(bmil.get__Name(),"is",bmil.get__BMI(),bmil.get__Status())
main()
this is the code from which I am getting the calculations:
def BMI(name,age,height,weight):
Weight=float(input("Enter your weight in pounds: "))
Height=float(input("Enter your heigh in inches: "))
bmi=(703*Weight)/(Height*Height)
if bmi <= 18.5:
print('Your BMI is', bmi,'which is underweight.')
elif bmi > 18.5 and bmi < 25:
print('Your BMI is', bmi,' which is normal.')
elif bmi > 25 and bmi < 30:
print('your BMI is', bmi,'overweight.')
elif bmi > 30:
print('Your BMI is', bmi,'which is close to obese.')
well, you have declared both:
class BMI():
and a function BMI:
def BMI(name,age,height,weight):
and it is very difficult to tell from the way you have posted the question which is being called. Based on the error message, I would guess the class definition is getting called when you want to call the function.
You defined both a class BMI and a function BMI.
Because you definend the function after the Class, BMI referes now to the function.
Also you class definition is very odd for python code.
I guess with the name=str you want to define a type for this variable. This is not what it does. It is setting the default for name to the function str.
Also you would not use these getters. Use plain member variables:
class BMI():
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
The actual bmi is a prime example for a property:
class BMI():
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
#property
def bmi(self):
return self.weight / self.height**2
Then BMI.bmi is always the currrent value for given weight and height.
This makes me think, that this class would probably better be called Person or Patient.
You should rename the function to avaoid the collision. Functions in python should be named as actions and in lowercase / underscore scheme:
def calc_bmi(weight_pounds, height_inches):
return 0.454 * weight_pounds / (height_inches / 2.54)**2

Error in BMI calculator

I am trying to calculator using classes in python. I tried to solve in this way:
class Person(object):
def __init__(self,name,age,weight,height):
self.name = name
self.age = age
self.weight = float(weight)
self.height = float(height)
def get_bmi_result(self):
bmi = (self.weight)/float((self.height*30.48)*(self.height*30.48))
print bmi
if bmi <= 18.5:
return "underweight"
elif bmi>18.5 and bmi<25:
return "normal"
elif bmi>30:
return "obese"
pass
when I call the constructor:p = Person("hari", "25", "6", "30") and p.get_bmi_result
it was returning <bound method Person.get_bmi_result of <Person object at 0x00DAEED0>>
.
I entered weight in kilograms and height in foots and in the calculation I tried to convert foot to centimeters.
You simply forgot to call your method:
p.get_bmi_result()
Note those () parenthesis. You only dereferenced the bound method object.
With the call, your code runs just fine:
>>> class Person(object):
... def __init__(self,name,age,weight,height):
... self.name = name
... self.age = age
... self.weight = float(weight)
... self.height = float(height)
... def get_bmi_result(self):
... bmi = (self.weight)/float((self.height*30.48)*(self.height*30.48))
... print bmi
... if bmi <= 18.5:
... return "underweight"
... elif bmi>18.5 and bmi<25:
... return "normal"
... elif bmi>30:
... return "obese"
...
>>> p = Person("hari", "25", "6", "30")
>>> p.get_bmi_result()
7.17594027781e-06
'underweight'
Clearly your formula needs adjusting still, a BMI of 0.000007 is radically underweight for someone weighing 6 stone, even if only 30 inches(?) small.
Depending on what your weight and height unit sizes are, you may need to consult the BMI formula and adjust your method a little.

Categories

Resources