Python Forum
I need help with this please. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: I need help with this please. (/thread-14179.html)



I need help with this please. - pythonlearnery - Nov-18-2018

Write a function called userWords() that repeatedly asks the user to enter words until they enter the word "stop!". Every word the user enters should be stored in a nested list arranged by word-length such that all the 3-letter words are stored in a list at index 3 (for example). Return the nested list when complete. You may assume no word is larger than 9 letters.


This is what I have so far, but it will not work.

def userWords():
    words = []
    while True:
        word = str(input("Enter a word: "))
        if word == "stop!":
            break
        else:
            words.append(word)
    print(words)
userWords()
Thanks


RE: I need help with this please. - koolinka - Nov-18-2018

You could try using sorted() for your list.

https://docs.python.org/3/howto/sorting.html


RE: I need help with this please. - pythonlearnery - Nov-18-2018

(Nov-18-2018, 04:41 PM)koolinka Wrote: You could try using sorted() for your list.

https://docs.python.org/3/howto/sorting.html

The problem is the code will not even run, it gives me an error: name is not defined. I seriously don't see anything wrong with it, thought maybe another set of eyes could spot something! :)


RE: I need help with this please. - ichabod801 - Nov-18-2018

Are you running this in Python 2.7 or Python 3.x? The input function works differently in the different versions of Python. The code you have is Python 3.x code (which is good, you should be learning Python 3.x). If you run it in Python 2.7 it will probably give you a NameError, though.


RE: I need help with this please. - pythonlearnery - Nov-18-2018

(Nov-18-2018, 04:55 PM)ichabod801 Wrote: Are you running this in Python 2.7 or Python 3.x? The input function works differently in the different versions of Python. The code you have is Python 3.x code (which is good, you should be learning Python 3.x). If you run it in Python 2.7 it will probably give you a NameError, though.

Yes, you are absolutely right!, that is very strange, I would have never guessed what is happening. I was typing python instead of python3 before the filename in terminal but usually python 3 is python by default if you know what I mean

I was missing one part, a nested list for every number of letters. Then append it to the corresponding list. Here is the corrected:

def userWordsx(): #solution
    word = ""
    wordList = [[],[],[],[],[],[],[],[],[],[]]
    while word!="stop!":
        word = input("Enter a word (stop!) to stop: ")
        wordList[len(word)].append(word)
    print(wordList)
userWordsx()
Thank you for everyone's input! This is a great community, will for sure be posting again.