1. Given a text file contains the name and gender of students, read the file and store the names and genders in a list.
2. Count how many male and female in the list.
3 Store the names of male and female in two different lists.
text file
name,gender
Alice,f
Bruce,m
Cloud,m
Darren,m
Eidy,f
Flower,f
Guile,m
Honda,m
Ilhamah,f
Judy,f
Kennedy,m
Laisy,f
def read_data(name):
with open(name) as f:
line = f.readline()
students = []
for line in f:
students.append(line.strip().split(','))
return students
def count_male_female(students):
male = 0
female = 0
for name, gender in students:
if gender == 'm':
male += 1
if gender == 'f':
female += 1
return male, female
def separate_male_female(students):
male = []
female = []
for name, gender in students:
if gender == 'm':
male.append(name)
if gender == 'f':
female.append(name)
return male, female
def main():
filename = input('Enter a file name: ')
students = read_data(filename)
male, female = count_male_female(students)
print(f'There are {male} males and {female} females in the file')
male_list, female_list = separate_male_female(students)
print('Males:', male_list)
print('Females:', female_list)
if __name__ == '__main__':
main()
Comments
Leave a comment