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

Number Guessing Game - code from vid doesnt run!?

I'm trying to run the script from the video but it's not working. The error seems to be for line 7 which is "while len(guessed_nums) < allowed_guesses". Can anyone one tell me what's wrong?

random_num = random.randint(1, 10)

guessed_nums = [] guessed_nums.append(player_num) allowed_guesses = 5

while len(guessed_nums) < allowed_guesses guess = input(“Guess a number between 1 and 10:”)

try:
    player_num = int(guess)
except:
    print (“That’s not a whole number!”)
    break

if not player_num > 0 or not player_num < 11:
    print (“Thats too high a number!”)
    break

if player_num == rand_num: print (“ You win! My number was {}.”.format(rand_num)) print (“ It took you {} tries.”.format(len(guessed_nums))) break

else: if rand_num > player_num: print (“Nope! My number is higher than {}. Guess #{}.”.format(player_num, len(guessed_nums))

else:
    if rand_num < player_num:
        print (“Nope! My number is lower than {}. Guess #{}.”.format(player_num, len(guessed_nums)))
    continue

if not rand_num in guessed_nums: print (“Sorry! My number was {}.”.format(rand_num))

ignore how the code is chopped up by the windows! I just pasted the whole script in so not sure why it's displaying like this!

3 Answers

Add a : after your while loop.

while len(guessed_nums) < allowed_guesses:

guess = input(“Guess a number between 1 and 10:”)

It think my problem is to do with the indents for the else part. Hate tabs so much! I've taken them out and put them back in so many times! Error message is saying line 30 which is the 2nd else. Ive tried it aligned with the else above and indented further than the else above, neither seems to run.

if player_num == rand_num: print ("You win! My number was {}.".format(rand_num)) print ("It took you {} tries.".format(len(guessed_nums))) break

else:
    if rand_num > player_num:
        print ("Nope! My number is higher than {}. Guess #{}.".format(player_num, len(guessed_nums))
    else:
        print ("Nope! My number is lower than {}. Guess #{}.".format(player_num, len(guessed_nums)))
continue

if not rand_num in guessed_nums: print ("Sorry! My number was {}.".format(rand_num))

The "if rand_num > player_num" condition is missing a closing parenthesis.