Answer to Question #329330 in Python for xxx

Question #329330

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



1
Expert's answer
2022-04-16T06:48:05-0400
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()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS