Quick question about string method exercise (X length)

Hello, I am on this exercise below:
Python Strings | Codecademy

finally decided to look at the solution and I have two questions referring to their solution.

First question: Why does the solution not use an else statement for the return False

Second question: In my eyes, my solution should yield the same exact result as the solution but it doesnt! look at the code below to see the difference between my code and the solution. It is the same thing but just switched around

Codecademy Solution:

def x_length_words(sentence, x):
  words = sentence.split(" ")
  for word in words:
    if len(word) < x:
      return False
  return True

MY Solution:

def x_length_words(sentence, x):
  split_sen = sentence.split() 
  for words in split_sen:
    if len(words) > x: 
      return True
    else:
      return False

As you can see, I have if len(words)> x return True and they have if len(words) < x return false
Why is this not the same thing??

I’m going to answer your second question first, as it leads to the first question.

In this exercise, we want to check if every word in sentence is longer or equal in length compared to x number of characters. Codecademy’s len(word) < x checks if the word is longer or equal in length, but your len(words) > x only checks if the word is longer.

More importantly, remember that after executing a return, the function will be exited. This means that your function will exit no matter what after the first word is evaluated. We want to check if all the words are longer or equal in length compared to x.


This leads to your first question. We don’t want our function to exit until either, a) we find that a word is not longer or equal in length compared to x in which case we return False, or b) we find that all the words are longer or equal in length compared to x in which case we return True.

In Codecademy’s provided solution, the if statement will return False if the above condition a) is met (that a word is not longer or equal in length compared to x). Outside of the for loop, there is a return True statement. This is because if we have iterated through every single word and the function has not exited (meaning that the return False statement was never executed), we know that all of the words are longer or equal in length compared to x, and therefore we can return True.

3 Likes