2013-08-06 55 views
0

我正在查看我的一些代碼的執行流程,我想知道下面是否會起作用。如果'if'條件已經運行,Python會跳過讀'else'條件嗎?

具體來說,我正在查看此條件樹中的else子句。如果在內存中沒有指定配置路徑,我會得到一個將配置路徑作爲輸入的函數。假設我給出正確的輸入。在declareConfPath()之後,計算機沒有理由運行嵌入條件,該條件檢查在運行declareConfPath()時是否指定了任何內容。

我的問題是,如果該程序會跳過該else情況下,或者如果它讀取else情況下,將採取由declareConfPath()第一if情況下,在樹中指定的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); 
+7

'else'沒有條件。使用'else:'或'elif condition:'。 – Hyperboreus

回答

5

只有在elif之後,您才能在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條件不匹配。

if statement documentation引用:

它選擇恰好一個通過評估由一個直到一個表達式之一套房被發現爲真[...];然後執行該套件(並且沒有其他部分的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條件被完全忽略;如果不是,則會引發例外。