简体   繁体   English

python 中的真循环在不等待条件变为真的情况下中断

[英]While true loop in python breaks without waiting for condition to become true

I am trying to run a while true loop in python to check if the word I want is same as that in a specific cell of the dataframe I have.我正在尝试在 python 中运行一个while true的循环,以检查我想要的单词是否与我拥有的 dataframe 的特定单元格中的单词相同。 I tried in two ways.我尝试了两种方式。 First one is as below:第一个如下:

        while True:
            try:
                df1 = pd.read_csv(io.StringIO(dfs[4].to_csv(index=False)), skiprows=1, header=[0,1])
                c = df1.iat[1,3]
                print(c)
                if (c == "Margaret"):
                    df1.to_csv("break.csv", mode='a', header=False)
                    print("Margaret found")
                break
            except Exception as e:
                print("waiting...")
                continue
        break

But when the value is not available, instead of trying again, it keeps printing "waiting..." endlessly.但是当该值不可用时,它不会再试一次,而是无休止地打印“等待...”。

Then I tried like following:然后我尝试如下:

        while True:
            try:
                df1 = pd.read_csv(io.StringIO(dfs[4].to_csv(index=False)), skiprows=1, header=[0,1])
                c = df1.iat[1,3]
                print(c)
                if (c == "Margaret"):
                    df1.to_csv("break.csv", mode='a', header=False)
                    print("Margaret found")
                break
            except:
                if c:
                    print("waiting...")
                    c = False
                continue

But here, when the value is not available, instead of trying again, it automatically skips to next part of the code without even printing "waiting...".但是在这里,当值不可用时,它不会再次尝试,而是自动跳到代码的下一部分,甚至不打印“等待...”。 Please suggest how I can modify the code.请建议我如何修改代码。 I am a beginner in coding.我是编码的初学者。 So will be very thankful if it is explained in a simple manner.因此,如果以简单的方式解释,将非常感谢。 TIA TIA

There are somethings to do:有一些事情要做:

  • Indent the break, so it's inside the if缩进中断,所以它在 if 里面
  • You're reading the same data over and over again, so remove the while loop since you probably already have one updating the data.您一遍又一遍地读取相同的数据,因此删除 while 循环,因为您可能已经有一个更新数据。

Final code:最终代码:

try:
    df1 = pd.read_csv(io.StringIO(dfs[4].to_csv(index=False)), skiprows=1, header=[0,1])
    c = df1.iat[1,3]
    print(c)
    if (c == "Margaret"):
        df1.to_csv("break.csv", mode='a', header=False)
        print("Margaret found")
        break
except Exception as e:
    print("waiting...")
    continue

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

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