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 trialKAZUYA NAKAJIMA
8,851 PointsIs using number out of range recommended practice?
Hello, I modified Ken's code as below. change point is: To accept un-valid input as '-1' and keep the loop going on. and this works fine for this challenge. But I am thinking to use -1 such as dummy number is recommended practice? Is this kind of practice not recommended as normal process or it's fine as long as code functioning properly? I just thought and if you have insight for this, please coach me.
import random
rand_num = random.randint(1,10)
guessed_nums = []
allowed_guesses = 5
while len(guessed_nums) < allowed_guesses:
guess = input('Guess a number betweeen 1 and 10: ')
try:
player_num = int(guess)
except:
print('That is not a whole number!')
guessed_nums.append(-1)
continue
if not player_num > 0 or not player_num < 11:
print('That number is not in a right range!')
guessed_nums.append(-1)
continue
guessed_nums.append(player_num)
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))
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThere is nothing magical or customary in using "-1".
In this code example, the dummy number is appended to the guessed_nums[]
list so the length of this list is the total number of valid and invalid guesses. Since lists can contain anything and only the length of the list matters in this context, the dummy item could be anything: a string, some object, what is convenient. "-1" isn't a convention, it's just convenient. One could certainly have used "X", making the invalid guesses stand out when printing guessed_nums[]
KAZUYA NAKAJIMA
8,851 PointsKAZUYA NAKAJIMA
8,851 PointsHello, thank you for your reply. I understood what matters is length of list, so whatever input will do.