Home > Back-end >  How could I use a function thats inside a for loop in python
How could I use a function thats inside a for loop in python

Time:02-15

I have a function that prints out the students that has passed an exam. But if I do the function like this:

csv_dict_reader = csv.reader(
    read_obj,
    delimiter=";",
)
next(csv_dict_reader)
for row in csv_dict_reader:

    if row[11]:
        #     allPassedStudents.append(row[0])
        passedDate = datetime.strptime(row[11], "%d-%m-%Y %H:%M")

    if passedDate:

        if passedDate < end_date:
            fastStudent.append(row[0])
            print(fastStudent)

I get a print like this:`

['1']
['1', '2']
['1', '2', '3']
['1', '2', '3', '41']
['1', '2', '3', '41', '49']

these numbers are studentnumbers! How could I get it so it shows everystudent just once. student is row[0] in my function and row[11] is the date they passed

CodePudding user response:

What about this :

csv_dict_reader = csv.reader(read_obj, delimiter=';',)
    next(csv_dict_reader)
    for row in csv_dict_reader:
        
        if row[11]:
        #     allPassedStudents.append(row[0])
            passedDate = datetime.strptime(row[11], '%d-%m-%Y %H:%M') 
    
        if passedDate:

            if passedDate < end_date:
                fastStudent.append(row[0])
    print(fastStudent)

I don't have your dataset to test it. But now it should work I guess.

CodePudding user response:

Either:

  • only do print(fastStudent) after the loop (since fastStudent is the list you're gathering those ids into), or
  • do print(row[0]) in the loop (so you only print the ID you just appended).
  • Related