2016-11-24 15 views
0

我發現這是爲了生成隨機數。雖然沒有表達和布爾理解

def main(): 
    randomNumber = randint(1,100) 
    found = False 
    while not found: 
     userGuess = input("") 
     if userGuess == randomNumber: 
      print "You win." 
      found = True 
     elif 
      ..... 
     else 
      ..... 

所以我的問題是'雖然沒有找到',我不覺得這是本能的。 更多的本能,但不工作應該是這樣的:

found = False 
while found 

- >環路工作時發現是假的

有人能解釋一下嗎?

+0

然後你應該寫'while found == false',這是你的文本的直譯,「發現是錯誤的」。 –

+1

修復您的縮進; 'while found'表示'while found found == True','while not found'表示'while found == False' –

回答

1

A while循環將執行,而給定的表達式是True。在你的情況下,給定的表達式是not found。由於found開始爲False,not found當然是True,因此該循環執行並將繼續執行,直到found設置爲True,此時not found將是False

我的建議是不要重寫這個 - 它實際上是非常可讀的。你是說你有不是發現東西,繼續找。

0

如果while not found看起來很不直觀,那麼您應該只是習慣它。這是一種常見的Python成語,並且在一段時間後會顯得很直觀(雙關語意)。

如果你想更可讀的代碼,但是,我會擺脫found變量的完全和使用break終止循環:

def main(): 
    randomNumber = randint(1,100) 
    while True: 
     userGuess = input("") 
     if userGuess == randomNumber: 
      print "You win." 
      break 
     # Code here will run only if the break isn't executed. 
     # You don't need the elif any more. 

這是個人喜好的問題:有些人喜歡用一個標誌變量來終止循環;我更喜歡像這樣的代碼中的明確中斷的簡單性。