0

我正在查看我的一些代码的执行流程,我想知道以下是否可行。

具体来说,我正在查看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);
4

1 回答 1

6

您不能使用条件 after else,只能使用 after elifelif仅在前面的或条件匹配时才检查。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中设置为,条件也不匹配。bazelif

引用if声明文档

它通过逐一评估表达式直到发现其中一个为真[...];然后执行该套件(并且不执行或评估语句的其他部分if)。如果所有表达式都为假,则执行该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

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

于 2013-08-06T21:36:07.117 回答