我剛剛寫了一個猜測隨機數的快速腳本。 雖然劇本的最後一行'恭喜你贏了'等不在運行。 同樣在一些解釋器中,它給出了一個錯誤'運行腳本失敗'。簡單的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)
如果初始'guess'是正確的,循環條件是立即虛假,不執行循環。 – DyZ
else行永遠不會執行,因爲while循環條件在正確的猜測中得到驗證並退出循環。你可以刪除else和un-indent那一行,這樣它在顯示後顯示 – iffy
將最後一行移出while循環 – chowsai