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
Gabriel Mafra
871 PointsGetting "NameError: name 'age' is not defined" when trying to replicate number_game try: clause
Hello guys!
I have tried to add a try: clause to my code below based on the number_game example, however, if i enter a letter to force it, i get a NameError: name 'age' is not defined even though it actually works if i insert only numbers. Could anyone help me identify what i'm doing wrong? thanks in advance!
ages = []
while len(ages) < 5:
try:
age = int(input("Type your age:"))
except ValueError:
print("{} is not a number, type a number!".format(age))
else:
ages.append(age)
avg = sum(ages) / 5
print("The average is: {}".format(avg))
1 Answer
Jennifer Nordell
Treehouse TeacherHi there! So when trying to enter an age and convert it to an int, if it works the result gets assigned to age. When you enter something that can't be converted to an integer the assignment never happens. So in the ValueError exception, you have a string that tries to use the age variable to format the string. But remember, that assignment failed. The variable age does not exist if the assignment didn't happen.
Try replacing the error message with something without the age variable such as print("Sorry. You must enter a valid number.").
Hope this helps!
Gabriel Mafra
871 PointsGabriel Mafra
871 PointsHi Jennifer,
Thanks for your comment! It was spot on!