2017-09-08 99 views
0

我剛剛寫了一個猜測隨機數的快速腳本。 雖然劇本的最後一行'恭喜你贏了'等不在運行。 同樣在一些解釋器中,它給出了一個錯誤'運行腳本失敗'。簡單的Python隨機數猜測器

import random 
attempts = 0 
secret_number = random.randint(1,100) 
isCorrect = False 
guess = int(input("Take a guess: ")) 

while secret_number != guess: 
    if guess < secret_number: 
     print("Higher...") 
     guess = int(input("Take a guess: ")) 
     attempts+= 1 
    elif guess > secret_number: 
     print("Lower...") 
     guess = int(input("Take a guess: ")) 
     attempts+= 1 
    else: 
     print("\nYou guessed it! The number was " ,secret_number) 
+0

如果初始'guess'是正確的,循環條件是立即虛假,不執行循環。 – DyZ

+0

else行永遠不會執行,因爲while循環條件在正確的猜測中得到驗證並退出循環。你可以刪除else和un-indent那一行,這樣它在顯示後顯示 – iffy

+0

將最後一行移出while循環 – chowsai

回答

0

你應該在while循環中打印出來,因爲當secret_number == guess時你的循環將會中斷。

while ...: 
    if: 
     ... 
    elif: 
     ... 

print "You guessed it! The number was {0}".format(secret_number) 
1

我對腳本做了一些修改。需要注意的是其功能是通過執行流程,沒有什麼特別的控制語句(如continuebreak)或明確的干預調控是必要的,使得它在邏輯上是一致的:

import random 


secret_number = random.randint(1, 100) 
guess = None 
attempts = 0 

while secret_number != guess: 
    guess = int(input("Take a guess: ")) 
    attempts += 1 

    if secret_number == guess: 
     print("\nYou guessed it! The number was ", secret_number) 
    elif guess < secret_number: 
     print("Higher...") 
    elif guess > secret_number: 
     print("Lower...") 

我改變:

  1. isCorrect變量。我刪除了它,因爲它沒有被使用;
  2. 變量初始化的方式guess。 while語句前爲None;
  3. while循環內的條件語句;
  4. 在while循環內從用戶讀取輸入的順序。

我建議直觀瞭解腳本的工作原理。

我試圖運行它,並收到了以下的輸出:

[email protected]:~$ python3.6 ./test.py 
Take a guess: 70 
Higher... 
Take a guess: 80 
Higher... 
Take a guess: 90 
Higher... 
Take a guess: 95 
Lower... 
Take a guess: 94 
Lower... 
Take a guess: 93 
Lower... 
Take a guess: 92 
Lower... 
Take a guess: 91 

You guessed it! The number was 91