如果“if”条件已经运行,Python是否会跳过读取“else”条件?

2024-10-02 12:27:14 发布

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

我正在查看我的一些代码的执行流程,我想知道下面的方法是否有效。在

具体地说,我正在查看这个条件树中的else子句。如果没有在内存中指定配置路径,我将得到一个将配置路径作为输入的函数。假设我给出了正确的输入。计算机没有理由运行在declareConfPath()之后嵌入的条件,该条件检查在declareConfPath()运行时是否指定了任何内容。在

我的问题是程序是否跳过else大小写,或者它读取else大小写并将采用树上第一个if中由declareConfPath()指定的新值confPath。如果它没有跳过,那么我已经解决了所有必要的条件条件,而不是一个涉及另一棵树的替代方案。如果没有,那么我需要复制几行代码。这不贵,但也不优雅。在

也可能是使用elif代替if可能会得到我想要的结果,但我不知道。在

confPath = None; # or if the file when opened is empty?
_ec2UserData = None;
localFile = False;

# As we are dealing with user input and I am still experimenting with what information counts for a case, going to use try/except.

# Checks if any configuration file is specified
if confPath == None: #or open(newConfPath) == False:
    # Ask if the user wants to specify a path
    # newConfPath.close(); <- better way to do this?
    confPath = declareConfPath();
    # If no path was specified after asking, default to getting values from the server.
    if confPath == None:
        # Get userData from server and end conditional to parsing.
        _ec2UserData = userData(self);
    # If a new path was specified, attempt to read configuration file
    # Does the flow of execution work such that when the var is changed, it will check the else case?

else confPath != None:
    localFile = True;
    fileUserData = open(confPath);

Tags: orthetopath代码路径noneif
1条回答
网友
1楼 · 发布于 2024-10-02 12:27:14

不能在else之后使用条件,只能在elif之后使用条件。^如果前面的ifelif条件与不匹配,则只对进行检查。在

演示:

>>> foo = 'bar'
>>> if foo == 'bar':
...     print 'foo-ed the bar'
...     foo = 'baz'
... elif foo == 'baz':
...     print 'uhoh, bazzed the foo'
... 
foo-ed the bar

即使在第一个块中foo被设置为baz,但是elif条件不匹配。在

引用^{} statement documentation

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true [...]; then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause, if present, is executed.

强调我的。在

事实上,这也适用于其他情况:

^{2}$

请注意,elif条件是如何被完全忽略的;如果没有,则会引发异常。在

相关问题 更多 >

    热门问题