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 trialJade Newbury
Courses Plus Student 10,564 PointsThis method won't work with None types - can anyone please explain?
The code I used for the num_courses challenge below will work on strings and integers, however, when I tested in a workspace and included a None as one of the values (spanish_inqisition=None), then I got an error: TypeError: object of type 'NoneType' has no len()
So how would I be able to counter this error for dictionaries that contain None types and still be able to count the total values?
# The dictionary will look something like:
# {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Each key will be a Teacher and the value will be a list of courses.
#
# Your code goes below here.
def num_teachers(dict):
return(len(dict.keys())) #number of teachers
def num_courses(dict):
total = 0
for x in dict.values():
total += len(x)
return total
1 Answer
Steven Parker
231,269 PointsThis would not likely be something you'd need in a practical situation. In this example, if a teacher had no courses, their key would either be omitted entirely from the dictionary, or the associated value would be an empty list instead of "None". Either way, the code would function as expected.
In the unlikely event that a dictionary might legitimately contain a mix of lists and "None", you would just need to specifically test for "None" before performing any operation that assumes the value contains a list.
Jade Newbury
Courses Plus Student 10,564 PointsJade Newbury
Courses Plus Student 10,564 PointsOkay, I see, so I'd have to test the dictionary for any None values and then maybe remove them before I can perform any such operations like the one in the challenge(totaling the values)?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsYou might not want to alter the dictionary, but by detecting the "None" in the loop, you can handle it differently (perhaps just ignoring it) to avoid the error.
Jade Newbury
Courses Plus Student 10,564 PointsJade Newbury
Courses Plus Student 10,564 PointsYes, I just wanted to know what the best practice would be in this scenario. Thanks for your answer...iut was really helpful :)
Steven Parker
231,269 PointsSteven Parker
231,269 PointsJade Newbury — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!