Skip to main content
 首页 » 编程设计

Python if/else 循环不起作用

2025年05月04日19davidwang456

我有一个 csv 文件所在的目录。代码读取文件并根据文件中的数据创建直方图。

但是,我试图做到这一点,以便在命令行中,我可以在 csv 文件中输入其中一个列标题,并且代码只会生成指定命令的图形。示例:python histogram_maker.py "C:/Folder"区域。

我能够做到这一点,但我想添加一个部分,该部分会在用户输入 csv 文件中未指定的命令时创建错误消息。示例:周边不存在。我的代码有什么问题?即使某些东西存在,我在命令提示符下出现 20 次“不存在”,但它仍然会生成我需要的所有文件。我如何停止这种重复并使它只有在 csv 文件中没有某些内容时才会出现错误。

        for column in df: 
            os.chdir(directory) 
            if len(sys.argv)>2: 
                for x in arguments: 
                    if x.endswith(column): 
                       #code for histogram 
                    else:  
                        print "does not exist" 

请您参考如下方法:

您正在测试所有 参数,即使只有一个匹配。对于每个不匹配的参数,您打印错误消息。

使用any()函数查看是否有任何匹配:

if len(sys.argv)>2: 
    if any(x.endswith(column) for x in arguments): 
        #code for histogram 
    else:  
        print "does not exist" 

或者反转测试;使用 not 并尽早退出:

if len(sys.argv)>2: 
    if not any(x.endswith(column) for x in arguments): 
        print "does not exist" 
        sys.exit(1) 
 
    #code for histogram 

如果带有生成器表达式的 any() 有点难以理解,你仍然可以使用 for 循环,但你需要使用 break 提前结束循环和一个 else: 套件,它将在 for 循环不提前退出时执行:

for x in arguments: 
    if x.endswidth(column): 
        break  # found a match 
else: 
    # `for` loop was not exited, so no match found 
    print "does not exist" 
    sys.exit(1)