Home > Mobile >  beginner troubles
beginner troubles

Time:12-03

making guessing game. I keep getting an attribute error trying to append my guess to the guesses list. following along in a course. I was prompted to say getting warmer if the current guess was closer than the last guess. i set guesses = 0 and and within the while loop i tried to append with (guesses.append(cg)) cg = current guess

import random

correct = random.randint(1,100)
print(correct)
guesses = 0
cg = int(input('Welcome to GUESSER guess here: '))

while True:
    if cg > 100 or cg < 0:
        print('out of bounds')
        continue
    if cg == correct:
        print(f'It took {len(guesses)} to guess right. nice.')
        break
    if abs(cg - correct) <= 10: #first guess
        print('warm.')
        
    else:
        print('cold.')
    
    guesses.append(cg)
   
    if guesses[-2]: #after first guess
        if abs(correct - guesses[-2]) > abs(correct - cg):
            print('warmer')
            guesses.append(cg)
        else:
            print ('colder')
            guesses.append(cg)
    pass

CodePudding user response:

You assign an integer to guesses here:

guesses = 0

So the interpreter is right saying you CANNOT append to int. Define it as a list:

guesses = []

But there's more:

  • You ask for input BEFORE the loop, so it happens only once, later the loop is infinite, cause no new input is ever provided
  • If you need only current and previous value you don't need a list at all, rather 3 integers (current, previous, counter - to print number of guesses if you wish to do that)
  • If you want to stick to the list you'll get an IndexError next, since there is no guesses[-2] element during 1st iteration (and you don't check the length of the list before trying to access that)
  • Do NOT call variables like "cg" it means nothing, abbreviations depend on a context (which you might have or might not have), now it's a simple program and you can instantly see that it's probably "current_guess", but that's not the case in general, the IDE should make your life easier and give you possibility to auto insert once defined name, so if somebody says it's time consuming they are plainly wrong

CodePudding user response:


while True:
    guess = int(input("Enter Guess Here: \n"))
    
    if guess < 1 or guess > 100:
        print('OOB, try again: ')
        continue
        
    # compare player guess to number
    if guess == win_num:
        print(f'you did it in {len(guess_list)} congrats')
        break
        
    #if guess is wrong add to guess to list
    guess_list.append(guess)
    
    #
    if guess_list[-2]:
        if abs(win_num - guess) < abs(win_num - guess_list[-2]):
            print('warmer')
        else:
            print('colder')
            
            
    else:
        if abs(win_num - guess) <= 10:
            print('warm')
        else:
            print('cold')
        
    

  • Related