im asking w input() for user to input "spelling words" for a kids homework, and i want it to append or add the words entered into a list. i got it to ask for user input for the words, but not sure how to make it add them into a list. any ides?? thanx in advance :)

Dani AI

Generated

Short answer: create the list once before the loop and give the loop a clear exit. was correct — putting the list creation inside the loop resets it every time, and you need a break condition so the program can stop. Also fix the shebang if you use one (/usr/bin/python, not /usr/ben/python).

Example (Python 3): this loads any previously saved words, prompts until the user enters a blank line, appends each new word, then writes the full list back to a text file.

try:
    with open('spelling_words.txt') as f:
        spell = [line.strip() for line in f if line.strip()]
except IOError:
    spell = []

print("Enter spelling words. Press Enter on a blank line to finish.")
while True:
    word = input("Word: ").strip()
    if not word:
        break
    if word not in spell:
        spell.append(word)

print("Saved words:", spell)

with open('spelling_words.txt', 'w') as f:
    for w in spell:
        f.write(w + "\n")

Troubleshooting tips: use input() on Python 3 (older Python 2 used raw_input()), call .strip() to avoid empty/whitespace entries, and check for duplicates if needed. If multiple runs must append instead of overwrite, open the file with mode 'a' or load-merge-then-write as shown. For quick reference on builtins and file I/O see the official docs: input() docs and reading and writing files.

Applied to : move your list initialization above the loop and add a clear exit (blank line or a sentinel like "done"), and the list will remember previous entries across iterations as expected.

Recommended Answers

All 3 Replies

ok, heres what i have so far. now it will append the input to a list but it doesnt seem to remember the last thing you enter 'cause it will print the list showing only what word you just entered instaed of showing a growing (appended) list. weird. i need it to save all the words i enter and add the new ones when i enter them as well. heres the code so far:

#!/usr/ben/python
#SpellingWordPractice
from __future__ import print_function

more_words = "y"
while more_words == "y":
   spell = []
   a = raw_input("Please enter all you spelling words? ")
   spell.append(a)
   print(spell)

spell = []
defines an empty list on every pass through the loop. You want it before the while(). Also, your code is an infinite loop, i.e. there is no exit.

awesome, tyvm :) much appreciated

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.