0

I'm trying to run a for loop inside of a while loop, but for some reason it's not being run at all.

Here's the code:

with open("Nominees_18.csv") as nominees:
    reader = csv.reader(nominees)
    next(reader)
    for c, row in enumerate(reader):
        print(row[0], row[1], c)
    while True:
        name = input("chose a number")
        print(4)
        for c, row in enumerate(reader):
            print(4)
            if str(c) in name:
                print(len([i for i in row if row[i] == "y"]))
        if input("chose another?") == ("no" or "No"):
            break

The script asks you for a number, then asks if you want to choose another number. I put print(4) to test the for loop and it doesn't come up.

There's further code above this but I haven't included it as I don't think it's relevant, but if you want it, then let me know.

I have no idea why this could be happening.

Thanks.

baduker
  • 19,152
  • 9
  • 33
  • 56
  • 8
    What's `reader`? – Thomas Mar 18 '18 at 18:24
  • 1
    `("no" or "No")` will always be True, by the way. https://stackoverflow.com/questions/15112125/how-do-i-test-multiple-variables-against-a-value/30430962 – OneCricketeer Mar 18 '18 at 18:27
  • Ah sorry - reader is an opened csv file. –  Mar 18 '18 at 18:31
  • I just added the rest of the code as realised that actually would be important, my bad –  Mar 18 '18 at 18:33
  • 2
    You already read until the end of the file in the first `for` loop. – Matthias Mar 18 '18 at 18:34
  • 2
    once you iterate over reader and reach the end, the iterator is exhausted and will not yield anything else. You need to reinitialize the reader or read it into a list, which can be iterated over multiple times – avigil Mar 18 '18 at 18:35
  • 2
    Possible duplicate of [Loop over rows of csv.DictReader more than once](https://stackoverflow.com/questions/31323150/loop-over-rows-of-csv-dictreader-more-than-once) – Aran-Fey Mar 18 '18 at 18:35

2 Answers2

0

input() waits until the user has entered something, so your print(4) is executed after the user presses enter. Your for loop inside of the while loop might not find anything because you have already iterated over your file contents before (and the reader is at the end of the file already). You might want to save your file content in a local variable (in a parsed form) so that you can search through it more easily, if the file is not too large.

nspo
  • 1,488
  • 16
  • 21
0

The generator is already exhausted once it was enumerated in the first loop. Trying to call the next() method on it after the first loop will result in StopIteration error, but trying to iterate over it in the next for loop won't just do anything as it is already empty.