简体   繁体   中英

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

There are somethings to do:

  • Indent the break, so it's inside the 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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