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 trialMerrel Padernilla
5,687 PointsCode Challenge: String length
Please help me identify what is wrong with my code. Thanks.
def just_right(string): if len(string) < 5: print ("Your string is too short.") elif len(string) > 5: print ("Your string is too long.") else: return True
3 Answers
William Li
Courses Plus Student 26,868 PointsHi Merrel:
You're very closed to the right solution, However
If the length of the string is less than five characters, return "Your string is too short". If the string is longer than five characters, return "Your string is too long". Otherwise, just return True.
This challenge specifically asks you to use return
statement at every turn, thus, the change you need to make to the current code is replacing all the print
statements with return
statements.
def just_right(string):
if len(string) < 5:
return "Your string is too short."
elif len(string) > 5:
return "Your string is too long."
else:
return True
Like such, and your code is good to go. Hope it helps
Merrel Padernilla
5,687 PointsThanks William, I passed the code challenge. However, I am still confused. I tried to run the code through the terminal. Here is my code:
def just_right(string): if str(string) < 5: return "Your string is too short" elif str(string)> 5: return "Your string is too long" else: return True string="abcdefg" x = just_right(string) print (x)
When I run Python, this is what I get:
Merrels-MacBook-Pro:code merrelp$ python3 test.py Traceback (most recent call last): File "test.py", line 16, in <module> x = just_right(string) File "test.py", line 5, in just_right if str(string) < 5: TypeError: unorderable types: str() < int()
Can you help me identify what is wrong with the code?
Thank you,
Merrel
William Li
Courses Plus Student 26,868 PointsHi Merrel. The problem is that you're using str(string)
instead of len(string)
in your version of code.
def just_right(string):
if len(string) < 5: # changed str() to len()
return "Your string is too short"
elif len(string)> 5: # changed str() to len()
return "Your string is too long"
else:
return True
string="abcdefg"
x = just_right(string)
print (x)
Merrel Padernilla
5,687 PointsThanks William, that worked.
I can now go back to my Python track.