Python Forum
I need help with this please.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I need help with this please.
#1
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
Reply
#2
You could try using sorted() for your list.

https://docs.python.org/3/howto/sorting.html
Reply
#3
(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! :)
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
(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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020