1

This is a tutorial question: Use these lists in nested loops to find out which students are enrolled in both classes and count the total number of students. Your output should look like the following:

Student: Audrey is enrolled in both classes Student: Ben is enrolled in both classes Student: Julia is enrolled in both classes Student: Paul is enrolled in both classes Student: Sue is enrolled in both classes Student: Mark is enrolled in both classes 6 students are enrolled in Computer Science and Maths

I have tried count, split (was desperate) and other ways to try and get it to count how many students but having no luck. Can someone please suggest a way to get this or direct me to the correct section in the documentation?

for i in mathStudents:
    both = ""
    #ele = 0
    for i in csStudents:
        if i in mathStudents and i in csStudents:
            both = i
            #ele +=1

            print("Student: ", both, "is enrolled in both classes \n there is", #ele.count(i) 
            )

    break

Thanks in advance

1 Answer 1

1

Personally I would just be lazy and use set():

print("Total number is: ", len(set(mathStudents) | set(csStudents))

If you want to use for loops to get the total number:

both = 0
for x in mathStudents: #don't use the same variable for each loop
    for y in csStudents: #they overwrite each other
        if x == y: #same student
            both +=1 #both is increased
            print(x, "is in both classes")

total_students = len(mathStudents) + len(csStudents) - both #total = math + cs - overlap
print(total_students)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.