Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Number Game App Number Game Refinement

Michał Borowiecki
Michał Borowiecki
14,097 Points

Why use a list's length to count the number of attempts?

Is there any reason why a list's length is used as a counter in the loop instead of an integer? My code works fine, but I'm wondering whether in some other cases this approach might fail. Maybe there's a bigger picture that I don't see yet. Right now, for me what Kenneth is doing in this video feels like using a pot to make pancakes. Of course you can do it and it works, but why not a pan?

import random
def game():
    secret_num = random.randint(1,10)
    counter = 5
    while counter > 0:
        try:
            guess = int(input("You have {} chances. Guess a number between 1 and 10: ".format(counter)))
        except ValueError:
            print("{} is not a number".format(guess))
            break
        else:
            if guess == secret_num:
                print("You got it! My number was {}".format(secret_num))
                break
            elif guess < secret_num:
                print("Too small")
            else:
                print("Too big")
        counter -=1
    else:
        print("The number was {}".format(secret_num))

    play_again = input("Enter 'y' to play again " ).lower()
    if play_again != 'y':
        print("Bye!")       
    else:
        game()           
game()

2 Answers

Ryan Cross
Ryan Cross
5,742 Points

He will track the guesses and use it in a later video I believe.

It's more common to use a counter like you did. I suspect he just want's to show that a list can be used as well by utilising the len() and .append functions. He is just stretching the students' brains.