我有一项我无法完成的任务。我是编程的初学者,我想更好地理解我的课程。有人能帮我吗?我真的不明白。
这是作业:
BMI定义为体重/长度2。体重指数在18,5和25之间是理想的,并认为BMI健康的人。 该计划接收由两个人组成的输入,其名称,性别,长度和体重。
Jack Johnson M 1.78 83
Maria Miller V 1.69 60
将此输入处理为结构化数据。要实现这一点,请使用一个有用的类和有用的方法来增强程序的结构。使用此结构化数据为每个人打印:适当的地址,姓氏,BMI以及是否认为这是健康的声明。
示例:
Mr. Johnson’s BMI is 26.2 and is unhealthy.
Mrs. Miller’s BMI is 21.0 and is healthy.
这就是我所拥有的:
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)
BMI输入是:
Jack Johnson M 1.78 83
Maria Miller V 1.69 60
答案 0 :(得分:0)
将参数添加到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
然后解压缩列表:
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)
关于int,float的评论问题更多是你需要的:
只是为了解决这个问题,这不是干净的,也不是正确的方法,但它会起作用: 在init里面
self.length = float(length) if type(length) != float else length
self.weight = float(weight) if type(weight) != float else weight
我要做的是:
details_person1 = invoer[0].split()
details_person1[3] = float(details_person1[3])
details_person1[4] = float(details_person1[4])
与details_person2相同的事情