2015-10-02 130 views
0

我的代碼似乎工作到WHILE循環之前的行。這個想法是讓計算機通過從最低和最高數量的先前猜測中挑選一箇中間數字來猜測玩家1輸入的數字('P1')。我不知道爲什麼它保持循環!Python - 雖然循環不會停止

import random 

P1 = raw_input("The number should be between 0 to 100: \n") 
P1 = int(P1) 
previousguess = [] 
count2 = 0 

for c in range(2): 
    cg2 = random.randint(0,100) 
    print "Computer has guessed: %d" %cg2 
    if P1 != cg2: 
     previousguess.append(cg2) #adding the guess into "Previous Guess" list 
     print previousguess 

mn = min(previousguess) 
mx = max(previousguess) 

while True: 
    if P1 != cg2: 
     cg2 = (mn+mx)/2 #guess based on middle of highest and lowest 
     print "Computer has guessed: %d" %cg2 
     previousguess.append(cg2) 
     count2+=1 

else: 
    print "The Computer has guessed it in %d times" %count2 
+3

你永遠不會終止循環。當計算機獲得正確的猜測時,if條件失敗,程序永遠不會做任何事情。 – Prune

+0

嗨..感謝您的意見..我已經嘗試過給出的每個建議,但我仍然無法停止while循環..它只計算中間一次,並繼續循環無限的結果。 – chwps

+0

正如我在我的回答中所說的,您必須正確更新mn&mx。您的原始代碼根本不會更新它們,並且它使用的更新對二進制搜索算法無效。如果你需要更多的幫助,你必須遵循指導方針 - 最值得注意的是,發佈你的新代碼。 – Prune

回答

2

試試這個:

while P1 != cg2: 
    cg2 = (mn+mx)/2 #guess based on middle of highest and lowest 
    print "Computer has guessed: %d" %cg2 
    previousguess.append(cg2) 
    count2+=1 

您還需要正確地更新內環路MN & MX。這些不是唯一的問題,但它們應該讓您進入下一個調試階段。請考慮添加打印語句來跟蹤程序的進度,無論它發生在哪裏以及它計算的是什麼數據。

1

您需要在計算機猜出答案後插入break語句。

while True: # is always true 

因爲它總是如此,所以直到你強制使用中斷纔會結束循環。

編輯:你也可以創建一個條件,如其他答案所示。

3

因爲您使用的是while TrueTrue總是等於True,所以此循環永遠不會停止。你可以做這樣的事情:

while True: 
    if P1 != cg2: 
     cg2 = (mn+mx)/2 #guess based on middle of highest and lowest 
     print "Computer has guessed: %d" %cg2 
     previousguess.append(cg2) 
     count2+=1 

    else: 
     print "The Computer has guessed it in %d times" %count2 
     break # use break to break the loop 

或者只是這樣的:

while P1 != cg2: 
    cg2 = (mn+mx)/2 #guess based on middle of highest and lowest 
    print "Computer has guessed: %d" %cg2 
    previousguess.append(cg2) 
    count2+=1 

如果P1 != cg2等於假,這個循環就會終止。