I've got a class Person
which has attributes like name
, age
, weight
, and height
. I'm trying to add a function now which reads a CSV file that has these attributes for each person so it can print it out in the end, but I'm struggling to figure out how I can link those two.
So far I've written my read_people
function at the bottom, but I don't know where to go from there. How can I link each part of each line to name
, age
, weight
, and height
?
"""File for creating Person objects"""
class Person:
"""Defines a Person class, suitable for use in a hospital context.
Data attributes: name of type str
age of type int
weight (kg) of type float
height (metres) of type float
Methods: bmi()
status()
"""
def __init__(self, name, age, weight, height):
"""Creates a new Person object with a specified name, age, weight, and
height."""
self.name = name
self.age = age
self.weight = weight
self.height = height
def bmi(self):
"""Returns the body mass index of the person"""
return self.weight / (self.height * self.height)
def status(self):
if self.bmi() < 18.5:
return "Underweight"
if self.bmi() >= 18.5 and self.bmi() < 25:
return "Normal"
if self.bmi() >= 25 and self.bmi() < 30:
return "Overweight"
if self.bmi() >= 30:
return "Obese"
def __str__(self):
"""Returns the formatted string represent of the Person object"""
name = self.name
age = self.age
bmi = self.bmi()
status = self.status()
template = "{0} ({1}) has a bmi of {2:3.2f}. Their status is {3}."
return template.format(name, age, bmi, status)
def read_people(csv_filename):
file = open(csv_filename, "r")
for line in file:
line = line.split(",")
bods = read_people("people1.csv")
for bod in bods:
print(bod)
Example of the csv file:
Peter Piper,23,89.4,1.82
Polly Perkins,47,148.8,1.67
Griselda Gribble,92,48,1.45
Ivan Ng,19,59,2.0
Lucy Lovelorn,14,50,1.6
Leslie McWhatsit,70,59.2,1.65