10. Finding Column Indexes

Screen Link:

My Code:

from csv import reader
def find_col_index(csv_filename, col_name):
    opened_file = open(csv_filename)
    read_file = reader(opened_file)
    csv_filename = list(read_file)
    col_index = -1
    for i in csv_filename[0]:
        for j in range(len(csv_filename[0])):
            if i == col_name:
                col_index = j
    return col_index
                
print(find_col_index('users.csv', 'name'))
print(find_col_index('users.csv', 'id'))
print(find_col_index('users.csv', 'age'))

My output when code is ran:

3
3
-1

My output when Submit answer is clicked:

"Your function returned an incorrect answer. Input: ['test.csv', 'h1'] Your answer: 5 Expected answer: 0"

How come the structure of my code is incorrect? Am i missing an indent? Please clarify

@TravisBob: you will need to call your function after defining it.

print(find_col_index('users.csv', 'name'))
print(find_col_index('users.csv', 'id'))
print(find_col_index('users.csv', 'age'))

Not calling your function is as good as not writing the function itself.

Like mentioned above you will need to call the functions to get the results.

But you will also need to have a look at your nested loop. The inner loop runs through all the values even after i==col_name. If you add print(j) inside this loop, you will see how many times the loop gets executed and what values it finally returns from the function.

So the question to consider here is that do you really need a nested loop? Can you get the answer with just one loop? Can you take advantage of the index of the list itself?

1 Like

yea, i updated now, forgot to add that. See above