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

Python Python Basics (2015) Number Game App String length

Alexandra Montgomery
Alexandra Montgomery
520 Points

Create a new function named just_right that takes a single argument, a string.

Unsure as how to properly write this.

strlen.py
def just_right(string):
  if string < 5:
    print("Your string is too short.")
  if strint > 5:
    print("Your string is too long.")
  else:
    return True

2 Answers

Matthew Rigdon
Matthew Rigdon
8,223 Points

You are very close. See below:

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

The only modifications I made were making the the (1) second "if" an "else if" statement and (2) making the print statements "return." I changed (1) because of common convention. If you have multiple if statements, many of them can be run. For example:

x = 5

if x <= 5:
  print("Yes.")
if x = 5:
  print("Yes, duh.)

In this case, it will print both responses. Using an elif statement will only allow the first true statement to be returned, and it will skip all of the other branching code below, which is more efficient.

(2) You want each answer to be "returned" from the function, not printed. Functions will typically have a response, which is why you use return. Think of a function like a machine: you put a bunch of ingredients into it (parameters), and it produces and spits out a product (return ... answer).

Onur Salman
Onur Salman
3,612 Points

Don't forget to do

len(string) > 5 # to get the length of the string that was entered

otherwise you cannot compare a string to a number.

Matthew Rigdon
Matthew Rigdon
8,223 Points

That is a good point! Updated code.