虽然python中的真循环中断而不等待条件变为真

编程入门 行业动态 更新时间:2024-10-16 22:24:32
本文介绍了虽然python中的真循环中断而不等待条件变为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试在 python 中运行 while 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

但是当值不可用时,它不会再试一次,而是继续打印waiting...";无止境.

But when the value is not available, instead of trying again, it keeps printing "waiting..." endlessly.

然后我尝试如下:

        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

但是在这里,当值不可用时,它不会再试一次,而是自动跳到代码的下一部分,甚至不打印等待...".请建议我如何修改代码.我是编码初学者.因此,如果以简单的方式解释,将非常感激.TIA

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

推荐答案

有些事情要做:

缩进中断,所以它在 if 内您一遍又一遍地读取相同的数据,因此删除 while 循环,因为您可能已经有一个更新数据的循环了.

最终代码:

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

这篇关于虽然python中的真循环中断而不等待条件变为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:31:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128635.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不   条件   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!