Populating a list with iterations not working

As you’ll see, I’m VERY new to programming and Python. I’m trying to write a simple function to get the number of students in a class from the user, and then ask for a student name which will iterate and populate an empty list. I though this would work because the condition would check to see if the length of the list is equal to the class size and keep running until it is, but that isn’t the case. Instead, I get this error:
"line 5, in setup_class
_ if len(students) < class_size:_
TypeError: ‘<’ not supported between instances of ‘int’ and ‘str’"

when I used a variable like this to check length L = len(students) and printed L, I got an integer, and when I printed out class_size, I would get whatever the input number was, so I thought I was checking a number against a number so I’m confused by the “int and 'str” error.
Here is the code:

def setup_class():
    
    students = []
    class_size = input("how many students in class?: ")
    if len(students) < class_size:
        
        student_names = input("Enter student name and press Enter: ")
        students.append(student_names)
    
                          
    print(students)
    
setup_class()

Thanks
~Mark

@psufilm2002 You need to convert the user’s input from a string to an integer, even though it looks like an integer to you. You could either do that when you ask for input, or inside the if statement, but to convert it all you need to do is wrap it in int(...):

class_size = "20"

print(int(class_size) + 10) # 30
print(class_size + 10) # error

I knew it was something stupidly simple, thank you. Now I have to get it to loop properly, but that’s another problem.
edit
changed the if loop to a while loop and now it works!

1 Like