5

It consists in creating a function def(,) that searches for the name of the kid in the CSV file and gives his age.

The CSV file is structured as this:

Nicholas,12
Matthew,6
Lorna,12
Michael,8
Sebastian,8
Joseph,10
Ahmed,15 

while the code that I tried is this:

def fetchcolvalue(kids_agefile, kidname):

    import csv

    file = open(kids_agefile, 'r')
    ct = 0

    for row in csv.reader(file):
        while True:
            print(row[0])
            if row[ct] == kidname:
                break

The frustrating thing is that it doesn't give me any error, but an infinite loop: I think that's what I'm doing wrong.

So far, what I learnt from the book is only loops (while and for) and if-elif-else cycles, besides CSV and file basic manipulation operations, so I can't really figure out how can I solve the problem with only those tools.

Please notice that the function would have to work with a generic 2-columns CSV file and not only the kids' one.

1
  • Another note, you should move the import line out of the function. Imports should be, with very few exceptions, at the top of the script. Imports take time and importing csv every time you call the function will slow it down. Commented Dec 3, 2016 at 20:10

2 Answers 2

7

the while True in your loop is going to make you loop forever (no variables are changed within the loop). Just remove it:

for row in csv.reader(file):
    if row[ct] == kidname:
        break
else:
   print("{} not found".format(kidname))

the csv file is iterated upon, and as soon as row[ct] equals kidname it breaks.

I would add an else statement so you know if the file has been completely scanned without finding the kid's name (just to expose some little-known usage of else after a for loop: if no break encountered, goes into else branch.)

EDIT: you could do it in one line using any and a generator comprehension:

any(kidname == row[ct] for row in csv.reader(file))

will return True if any first cell matches, probably faster too.

Sign up to request clarification or add additional context in comments.

Comments

2

This should work, in your example the for loop sets row to the first row of the file, then starts the while loop. The while loop never updates row so it is infinite. Just remove the while loop:

def fetchcolvalue(kids_agefile, kidname):

    import csv

    file = open(kids_agefile, 'r')
    ct = 0

    for row in csv.reader(file):
        if row[ct] == kidname:
            print(row[1])

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.