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 trialThananjaya Chakravarthy
4,672 Pointshow to calculate if the string lenght is more than 5?
I have enclosed list(name). Is this one correct to find the length of an string?
def just_right(name):
na=list(name)
if len(na) > 5:
print("Your string is too long")
else:
print("Your string is too short")
1 Answer
jacksonpranica
17,610 PointsHey Thananjaya,
The answer I came up with will be posted below. Feel free to scroll down, but don't scroll if you don't want to see it.
--Tips--
First off, the length function can actually be used with a string, so there is no need to convert the string to a list. len(string) will give you the length of the string, so you can use len(name) in place of len(na)
Secondly, your function needs to address three things, not two.
(1) if the length is greater than 5 (2) if the length is less than 5 (3) Otherwise return true
You addressed the first two but think about using an if, elif, and else to address all three.
--Answer--
def just_right(name):
if len(name)<5:
return "Your string is too short"
elif len(name)>5:
return "Your string is too long"
else:
return True
Thananjaya Chakravarthy
4,672 PointsThananjaya Chakravarthy
4,672 PointsThanks Jackson Pranica