Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,740 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.