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
Dillon Wyatt
5,990 PointsPython: Personal Guessing Game format error
I am attempting to create a guessing game akin to the one in the Python Tutorial however I am running into an odd couple errors.
My code is:
import random
x = random.randint(1,10)
guesses = []
def GuessGame():
global guess
while len(guesses) < 5:
try:
guess = int(input("Guess something. "))
except ValueError:
print("it must be a number! {} is not a number".format(guess))
else:
if guess == x:
print("congrats {} was the number".format(x))
break
elif len(guesses) == 3:
print("The next guess will be your last!")
else:
print("That is not it!")
guesses.append(guess)
else:
print("Your guesses were {} and the correct answer was {}. Better luck next time!".format(guesses, x))
GuessGame()
The game runs fine except for the ValueError section. I want it to insert into the print field the user inputted value. It does not do this per se. If I put in "a" into the field initially, it kicks back an error message with two principal errors -
"ValueError: invalid literal for int() with base 10: 'a'" and "NameError: name 'guess' is not defined"
Isn't the fact that I am using a TRY with EXCEPT VALUE ERROR suppose to solve this first issue?
The Second one appears because something is undefined. It crops up in a non-error way, too. If I type in "12", "13", "a", it will fill in the {} part of the print section NOT with "a" but with "13" - or the immediate prior integer that was valid. How can I get it to print the invalid letter and not just the incorrect but valid integer?
1 Answer
james south
Front End Web Development Techdegree Graduate 33,271 Pointsyour except block is fine, it's the try block that is the problem. you are trying to take input and cast as int in one step. if you enter a letter, it can't cast it as int and throws the error, but since the input process failed, guess has no value. it has never been defined, it threw an error instead. that is why it gives you the nameError, guess not defined. to fix this i moved the input instruction outside of the try. this ensures that guess has a value and is defined. in the try block then you only try to cast as int. if that works, great, the else block will execute. if the int cast fails, the except block will execute, and since guess has the value of whatever you typed in, the error statement will print as intended.