如果'if'条件已经运行,Python是否会跳过阅读'else'条件?

0 python conditional if-statement skip

我正在查看我的一些代码的执行流程,我想知道以下内容是否有效.

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

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

也可能是这样的情况,使用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);
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

你不能使用条件后else,只有后elif.elif是仅如果前面的检查if或elif条件语句并没有匹配.

演示:

>>> foo = 'bar'
>>> if foo == 'bar':
...     print 'foo-ed the bar'
...     foo = 'baz'
... elif foo == 'baz':
...     print 'uhoh, bazzed the foo'
... 
foo-ed the bar
Run Code Online (Sandbox Code Playgroud)

即使foo设置为baz第一个块,elif条件也不匹配.

引用if声明文档:

它通过逐个评估表达式来选择其中一个套件,直到发现一个为真[...]; 然后执行该套件(并且不if执行或评估该语句的其他部分).如果所有表达式都为false else,则执行该子句的套件(如果存在).

强调我的.

实际上,这也扩展到了其他条件:

>>> if True:
...     print "first condition matched"
... elif int("certainly not a number"):
...     print "we won't ever get here, because that's a `ValueError` waiting to happen"
... 
first condition matched
Run Code Online (Sandbox Code Playgroud)

注意如何elif完全忽略条件; 如果不是,则会引发例外.