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
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 a python class that called student.py where it contains attributes and methods one of these method is called addStudent(self,name,age). it takes 2 arguments.
the problem is this function display the name and the age of the new student using the setter method.
but the console display this :
None is a new student and he/she has None years old
where None MUST BE THE NAME AND THE AGE
student.py
class student():
def __init__(self,name,age, grade):
self.stdName=name
self.stdAge = age
self.stdGrade = grade
def getName(self):
print("the student name {}".format(self.stdName))
def setName(self,Name):
self.stdName = Name
def getAge(self):
print("the student age :{}".format(self.stdAge))
def setAge(self, Age):
self.stdAge = Age
def getGrade(self):
print("the student {0}, have a grade {1}".format(self.stdName,self.stdGrade))
if self.stdGrade<2.5:
print("you failed")
elif self.stdGrade>2.5:
print("good job continue")
elif self.stdGrade == 5.0:
print("you are a honor student")
def setGrade(self,Grade):
self.stdGrade = Grade
def getTheAVG(self,initial,*grades):
value = initial
for item in grades:
value+=float(item)
return value/(len(grades)+1)
print("Average of the student is " + str((grades)))
def addStudent(self,name,age):
print("{0} is a new student and he/she has {1} years old"
.format(self.setName(name),self.setAge(age)))
std1 = student("georges", 17, 3.4)
std1.getName()
std1.getAge()
std1.getGrade()
std1.addStudent("jiji",12)
std1.getTheAVG(2.4,5.0,4.6,2.2,1.2)
You function is not returning a value hence it is getting None. You can do this.
def setAge(self, Age):
self.stdAge = Age
return self.stdAge
But, Having said it is a setter method from a design point of view you won't expect a setter function to return any value
Your print relies on the return values of two methods that don't return anything. Either have thesetName and setAge methods return the value they set, or just use the attribute values.
If you want your setter method to return something, do something like this
class Student:
def setName(self,Name):
self.stdName = Name
return self.stdName
def setAge(self, Age):
self.stdAge = Age
return self.stdAge
check this:
class student():
def __init__(self,name,age, grade):
self.stdName=name
self.stdAge = age
self.stdGrade = grade
def getName(self):
print("the student name {}".format(self.stdName))
def setName(self,Name):
self.stdName = Name
return self.stdName
def getAge(self):
print("the student age :{}".format(self.stdAge))
def setAge(self, Age):
self.stdAge = Age
return self.stdAge
def getGrade(self):
print("the student {0}, have a grade {1}".format(self.stdName,self.stdGrade))
if self.stdGrade<2.5:
print("you failed")
elif self.stdGrade>2.5:
print("good job continue")
elif self.stdGrade == 5.0:
print("you are a honor student")
def setGrade(self,Grade):
self.stdGrade = Grade
def getTheAVG(self,initial,*grades):
value = initial
for item in grades:
value+=float(item)
return value/(len(grades)+1)
print("Average of the student is " + str((grades)))
def addStudent(self, name, age):
print("{0} is a new student and he/she has {1} years old"
.format(self.setName(name), self.setAge(age)))
std1 = student("georges", 17, 3.4)
std1.getName()
std1.getAge()
std1.getGrade()
std1.addStudent("jiji",12)
std1.getTheAVG(2.4,5.0,4.6,2.2,1.2)
This will give you your desired output.
Note: Your function is not returning a value thats way it give you None but from a design point of view as your method is a setter method and setter methods don't return a value.
class Square(object):
def __init__(self, height="0", width="0"):
self.height = height
self.width = width
#property #This is a getter which allows us to refer to our fields inside of our __init__ method
def height(self):
print("Retrieving the height")
return self.__height #__height: __ to be a private field and protect our data
#height.setter #This is our setter to prevent us from putting bad data into our Square()
def height(self, value): #making sure that the value passed in is a digit
if value.isdigit(): #can use isfloat() for better results, but I'm using isdigit() anyway
self.__height = value
else: #if the value is NOT a digit
print("Please only enter a digit")
#Now we do the same for our width...
#property
def width(self, value):
print("Retrieving the width")
return self.__width
#width.setter
def width(self, value):
if value.isdigit():
self.__width = value
else:
print("Please enter a digit")
def getArea(self):
return int(self.__width) * int(self.__height)
def main():
UserSquare = Square() #My empty square object which I have to define as the user's square (UserSquare)
height = raw_input("Enter Height : ")
width = raw_input("Enter Width : ")
#Now I use the getters (#property) and setters to set everything
UserSquare.height = height #calling the user Square Object to set the heght
UserSquare.width = width # calling the user Square Object to set the width
print("Height :", UserSquare.height)
print("Height :", UserSquare.width)
print("Therefore, The area is :", UserSquare.getArea())
main()
#The reason I used getters and setters was so that I can just refer to my height method and width method as height and width
#If I didn't have those getters and setters, I would have to refer to them as height() and width()
The program asks the user to input a height and width, and then it calculates and shows the area of their 'square' (actually rectangle)
But it comes up with the TypeError in my title when I enter my width.
Can someone please tell me how I can fix this problem?
I am using PYTHON 2.7
class Square(object):
def __init__(self, height="0", width="0"):
self.height = height
self.width = width
#property #This is a getter which allows us to refer to our fields inside of our __init__ method
def height(self):
print("Retrieving the height")
return self.__height #__height: __ to be a private field and protect our data
#height.setter #This is our setter to prevent us from putting bad data into our Square()
def height(self, value): #making sure that the value passed in is a digit
if value.isdigit(): #can use isfloat() for better results, but I'm using isdigit() anyway
self.__height = value
else: #if the value is NOT a digit
print("Please only enter a digit")
#Now we do the same for our width...
#property
def width(self):
print("Retrieving the width")
return self.__width
#width.setter
def width(self, value):
if value.isdigit():
self.__width = value
else:
print("Please enter a digit")
def getArea(self):
return int(self.__width) * int(self.__height)
def main():
UserSquare = Square() #My empty square object which I have to define as the user's square (UserSquare)
height = raw_input("Enter Height : ")
width = raw_input("Enter Width : ")
#Now I use the getters (#property) and setters to set everything
UserSquare.height = height #calling the user Square Object to set the heght
UserSquare.width = width # calling the user Square Object to set the width
print("Height :", UserSquare.height)
print("Height :", UserSquare.width)
print("Therefore, The area is :", UserSquare.getArea())
main()
I had to make my def width(self, value) into def width under #property.
thanks everyone
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.