"Build an Interactive Website" was retired on September 11, 2014. You are now viewing the recommended replacement.

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

In Python Basics, why won't my Numbers Game work in Workspace?

In Python Basics, why won't my Numbers Game work in Workspace? I'm copying the code shown in the course, but for some reason the game won't work on my Workspace even though it's working in the lesson version.

What am I missing?

Code Below:

import random

# generate a random number between 1 and 10
secret_num = random.randint(1, 10)

while True:

# get a number guess from the player

  guess = int(input("Guess a number between 1 and 10: "))

# compare guess to secret number

if guess == secret_num: 
    print("You got it! My number was {}" .format(secret_num))
break
else:
    print("That's not it!")

 # print hit/miss 

1 Answer

indentation is important in python to demarcate blocks of code. here you have a while loop and an if statement, but they are separate blocks of code because they are at the same level of indentation (none). consequently, the while loop is not including the conditional, and thus runs infinitely. it only asks for an integer as input and has no way to stop or break. to fix, indent your if statement block to the same level as the guess, so it is inside the while loop. inside the if statement block, you also need to move the break statement over to the same level as the print call above it.

Perfect, thanks for your help James.