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.
Related
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.
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)
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
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
Not sure if I made sense in the title, but I have created classes and now I need to associate a class with a number. For example 1 would be the penny (object) and with this object I have associated height and weight. I need help asking how to associate this class with the number 1.
I know i need to have it ask the question like something like so
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar"
I need it to then ask me to Enter number:
Than ask how many of that coin of the number you just entered:
Than give me the total weight
Than give me the total height
with that should I include it in that original print statement or should I do another print statement or just keep it like so...
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\nEnter how many coins"
Now witht the last part of enter how many coins how do I associate that with a class I have a class set up for Penny for instance like so
#! /usr/bin/python
# Defining a class
class Coin():
def __init__(slef,weight,height):
self.weight = weight
self.height = height
class Penny(Coin)
def __init__(self)
Coin.__init__(self,2.500,1.52)
Penny = 1
class Nickel(Coin):
def __init__(self):
Coin.__init__(self,5.00,1.95)
Nicke = 5
class Dime(Coin):
def __init__(self):
Coin.__init__(self,2.268,1.35)
Dime = 10
class Quarter(Coin):
def __init__(self):
Coin.__init__(self,5.670,1.75)
Quarter = 25
class HalfDollar(Coin):
def __init__(self):
Coin.__init__(self,11.34,2.15)
HalfDollar = 50
class Dollar(Coin):
def __init__(self):
Coin.__init__(self,8.10,2.00)
Dollar = 100
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\n"
print "Please enter a number:"
If you name it something generic like cents, you can create a lookup table as follows:
lookup_table = {Penny.cents: Penny, Nickle.cents: Nickle, Dime.cents: Dime, ... }
coin = lookup_table[number_user_entered]()
That way you can dynamically create an instance of the proper class based on the user input.
I think what you are trying to do is something like this:
class Coin():
def __init__(self, name, value, weight, height):
self.name = name
self.value = value
self.weight = weight
self.height = height
definitions = [("dollar", 100, 8.1, 2.0), ...] # define the coins
coins = {data[1]: Coin(*data) for data in definitions} # create Coin instances
There is no need for the Dollar to be a sub-class of Coin, you can just make it an instance with appropriate attribute values.
You can now access each Coin instance within coins by value:
dollar = coins[100]
or use it to access the name:
for value in sorted(coins):
print("Enter {0.value} for a {0.name}".format(coins[value]))
coin_value = int(raw_input("Pick a coin: "))
coin = coins[coin_value]
coin_count = int(raw_input("How many {0}: ".format("{0.name}s".format(coin)
if coin.value > 1 else
"pennies")))
The other answers are both good other ways of dealing with your problem. To strictly solve it the way you defined it:
class Coin():
def __init__(self, weight, height):
self.weight = weight
self.height = height
class Penny(Coin):
value = 1
def __init__(self):
Coin.__init__(self, 2.500, 1.52)
class Nickel(Coin):
value=5
def __init__(self):
Coin.__init__(self, 5.00, 1.95)
class Dime(Coin):
value=10
def __init__(self):
Coin.__init__(self, 2.268, 1.35)
class Quarter(Coin):
value=25
def __init__(self):
Coin.__init__(self, 5.670, 1.75)
class HalfDollar(Coin):
value=50
def __init__(self):
Coin.__init__(self, 11.34, 2.15)
class Dollar(Coin):
value=100
def __init__(self):
Coin.__init__(self, 8.10, 2.00)
mycoin = Penny()
print "A penny is worth", mycoin.value
yourcoin = Quarter()
print "A quarter is worth", yourcoin.value
association = {str(class_obj.value): class_obj for class_obj in (Penny, Nickel, Dime, Quarter, HalfDollar, Dollar)}
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\n"
value = raw_input("Please enter a number:")
number = raw_input("How many of that coin:")
if value in association:
mycoin = association[value]()
print "total weight:", mycoin.weight * int(number)
print "total height:", mycoin.height * int(number)
How about storing the coin type and amount of coins into a dictionary of a single multidimensional list:
coins = {1:[Penny,[]], 5:[Nickel,[]], 10:[Dime,[]]} # etc...
Then, when you ask the user for coin type and amount, take that value as the key lookup for the dictionary and append that many coins to its list, instantiating the class in the process:
coin_type = raw_input("Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\n:")
coin_amnt = raw_input("Enter amount: ")
for i in range(coin_amnt):
coins[coin_type][1].append(coins[coin_type][0]())
To check total amount of a coin type:
len(coins[coin_type][1])
To check individual instances of a coin type:
for c in coins[coin_type][1]:
print c.weight, c.height
If you wanted to print a coin's type, you can add a __str__() special method to each of your coin classes, and then print the instance as you loop the list.
Hope this helps.