2.3 Class counter

You have two parallel arrays: one stores the names of pupils and the other stores the class they are in. Your task is to ask the user for the name of a class (for example, “1A” or “1B”). The program should then count how many pupils are in that class and display the total. It should also list the names of all pupils who are in the chosen class, keeping the data linked by position in the arrays.

names = ["Jane", "John", "Jess", "Ava", "Liam", "Mia"]
classes = ["1A", "1B", "1A", "1A", "1B", "1B"]
Enter class to count: 1A

Pupils in class 1A:
Jane
Jess
Ava
Number of pupils in class 1A: 3
set names to ["Jane", "John", "Jess", "Ava", "Liam", "Mia"]
set classes to ["1A", "1B", "1A", "1A", "1B", "1B"]

ask user to enter class to count and store in target_class

print blank line

set count to 0

print "Pupils in class", target_class

loop for length of names array
    if class at current position is equal to target_class
        set count to count + 1
        print name at current position

print "Number of pupils in class", target_class, ":", count
names = ["Jane", "John", "Jess", "Ava", "Liam", "Mia"]
classes = ["1A", "1B", "1A", "1A", "1B", "1B"]

target_class = input("Enter class to count: ")

print()  # blank line

count = 0

print("Pupils in class " + target_class + ":")
for i in range(len(names)):
    if classes[i] == target_class:
        count = count + 1
        print(names[i])

print("Number of pupils in class " + target_class + ":", count)
# Array storing pupil names
names = ["Jane", "John", "Jess", "Ava", "Liam", "Mia"]

# Parallel array storing each pupil's class
classes = ["1A", "1B", "1A", "1A", "1B", "1B"]

# Ask the user which class to count
target_class = input("Enter class to count: ")

# Blank line for clearer output
print()

# Counter for how many pupils are in the chosen class
count = 0

# Display heading for pupil list
print("Pupils in class " + target_class + ":")

# Loop through all pupils
for i in range(len(names)):
    # If the class at current position matches the chosen class
    if classes[i] == target_class:
        # Increase the counter by 1
        count = count + 1
        # Print the pupil's name from the same position
        print(names[i])

# Show the total number of pupils in the chosen class
print("Number of pupils in class " + target_class + ":", count)

Extension

Update the program so that the class entered by the user must be exactly two characters long (for example, “1A” or “2B”).

If the user enters a class name that is shorter or longer, the program should display an error message and ask again until they give an input with exactly two characters.

Enter class to count: 1
Invalid class name. Must be 2 characters long.
Enter class to count: 12B
Invalid class name. Must be 2 characters long.
Enter class to count: 1A

Pupils in class 1A:
Jane
Jess
Ava
Number of pupils in class 1A: 3