Python - Print only words with less than five characters

definition, python, split

Solution

Yes, because the loop in `writeshort` encounters the return statement when it finds a short word and returns immediately.

If you need all the short words from `writeshort`, you'll need to collect them first in a list, then finally return the list. Maybe like this:

def writeshort(txt):
    wordlist = []
    for item in txt:
        if len(item) > 4:
            continue
        wordlist += [item] # or wordlist.append(item) as in your first snippet
    return wordlist

The whole function could be replaced by a one-liner and more pythonic code:

[word for word in txt if len(word) <= 4]

And you've written `for txt in txt:`, which is weird. It will do what is intended (execute for each item in the original `txt`), but `txt` would be changed to an item of the list in each iteration.

Problem

This question is related to my education, with that said I wish to have any help you provide me with as detailed as possible - I dont want to copy-paste code and hand it in. :) The task is simple - Create a definition called writeshort(txt), take a string of words, print only words that have less than five characters. Now I have completed this, but the thing is that the task specifically sais use a definition. I fail here. Code without a definition, that works: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- string = raw_input(”Write a few lines: ”) txt = string.split() result = [] for words in txt: if len(words) > 4: continue result.append(words) print ', '.join(result), ”have less than five letters!” ``` Now that looks nice, and prints without any nasty [' ']. But what about the definitions? I've tried several things, this is the lastest, but it only prints the first word with less than five letters, and ignores the rest: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- string = raw_input(”Write a few lines: ”) txt = string.split() def writeshort(txt): for txt in txt: if len(txt) > 4: #Yes I know its a 4, but since it counts 0... continue return txt print writeshort(txt), "have fewer letters than five!" ``` I appreciate any help. Thanks for taking time to help me learn Python!

Original source