简体   繁体   中英

Python - While loop won't stop

my code seems to work up to the line before WHILE loop. The idea is to have the computer try to guess the number inputted by Player 1('P1') by picking a middle number from the lowest and highest number of previous guesses. I cant figure out why does it keep looping!

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

Because you're using while True and True is always equal to True, so this loop will never stop. You can do something like this:

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

Or just like this:

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

if P1 != cg2 is equal to False, this loop will terminated.

Try this:

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

You will also need to properly update mn & mx within the loop. These are not the only problems, but they should get you to the next stage of debugging. Please consider adding print statements to track the progress of your program, both where it goes and what data it computes.

You need to insert a break statement after the computer has guessed the answer.

while True: # is always true

Because it is always true, the loop will never end until you force it do so using break.

Edit: you could also create a conditional as shown in the other answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM