简体   繁体   English

Python For Loop无法运行

[英]Python For Loop Won't Run

I'm trying to run a for loop inside of a while loop, but for some reason it's not being run at all. 我试图运行for一个内部循环while循环,但由于某种原因它没有被运行在所有。

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. 我把print(4)测试为for循环,它没有出现。

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. 谢谢。

input() waits until the user has entered something, so your print(4) is executed after the user presses enter. input()一直等到用户输入了某些内容,因此在用户按Enter键之后将执行print(4) 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). 在while循环内的for循环可能找不到任何内容,因为您之前已经遍历了文件内容(并且阅读器已经位于文件末尾)。 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. 您可能希望将文件内容保存在本地变量中(以解析的形式),以便在文件不太大的情况下更轻松地进行搜索。

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. 在第一个循环之后尝试在其上调用next()方法将导致StopIteration错误,但是尝试在下一个for循环中对其进行迭代将不会做任何事情,因为该操作已经为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM