Python - 虽然循环不会停止

时间:2015-10-02 00:03:26

标签: python while-loop infinite-loop

我的代码似乎在WHILE循环之前就行了。这个想法是让计算机通过从先前猜测的最低和最高数量中挑选一个中间数来尝试猜测玩家1输入的数字(' P1')。我无法弄清楚为什么它会继续循环!

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 个答案:

答案 0 :(得分:3)

因为你正在使用while True并且True总是等于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等于False,则此循环将终止。

答案 1 :(得分: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。这些不是唯一的问题,但它们应该让您进入下一阶段的调试。请考虑添加打印语句以跟踪程序的进度,包括程序的进度和计算的数据。

答案 2 :(得分:1)

您需要在计算机猜到答案后插入break语句。

while True: # is always true

因为它总是正确的,所以循环永远不会结束,直到你强制它使用break。

编辑:你也可以创建一个条件,如另一个答案所示。