程序中跳过Python for循环

2024-04-29 05:43:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python程序来发送问题并检查答案。它有一个while-True循环,当接收到应答时,该循环被中断。文件“播放器.txt“只包含一个数字,这个数字是当前可以回答问题的玩家数量。我遇到的问题是这里代码中的for循环:

while True:
    myfile = open("players.txt","r")
    print("File: players.txt OPENED")
    for i in range(int(myfile.read())):
        print("For Loop STARTED")
        ftp.retrbinary("RETR answer"+str(i+1)+".txt",open("answer"+str(i+1)+".txt","wb").write)
        myfile = open("answer"+str(i+1)+".txt")
        print("File: answer"+str(i+1)+".txt OPENED")
        if answer == myfile.read():
            scores[i] = scores[i] + 1
            print("Player",str(i+1),"got the correct answer first.")
            correctanswerfound = True

        print("No answer from player",str(i+1),"yet.")
    if correctanswerfound == True:
        correctanswerfound = False
        break

        print("No answer from player",str(i+1),"yet.")
    if correctanswerfound == True:
        correctanswerfound = False
        break

正在跳过。有人知道为什么要跳过它吗?有没有什么可以修正的。在


Tags: answertxttrueforif数字openmyfile
3条回答

据我所知,你的输出是:

>> File: players.txt OPENED

但不是:

^{pr2}$

这意味着range(int(myfile.read()))实际上是一个空列表。如果我是你,我会检查我的文件和我的阅读方法。在

“的”我的文件.read()”无法工作,因为此时已读入整个文件

使用类似的东西

line=1
while(line):
  line = myfile.readline()
  for i in range(int(line)):

.read方法返回字符串中读取的字节。因此,当您尝试int(myfile.read())时,它将为以10为基数的int()提供一个无效的文本(这是通过使用我的文件.read())

相关问题 更多 >