I want an output where if the user inputs [1] he will be able to insert a new word to the existing list. If [2] the program will shutdown

Question:

I am trying to input [1] and enter a new word to append the existing words at list ”’words”’ in shuffle pattern.

import random

words = ['apple', 'banana', 'orange', 'coconut', 'strawberry', 'lime']
old_word = []

while True:
    choice = int(input('Press [1] to continue [2] to exit: '))
    if choice == 2:
        break
    
    elif choice == 1:
        new_word = input('Enter a new word: ')
        old_word.append(new_word)
        words.append(old_word)
        if new_word in words:
            random.shuffle(words)
            print(words)

e.g
input 1
Enter a new word: lemon

output 'orange', 'banana', 'lime', 'apple', 'lemon','coconut', 'strawberry'

Asked By: user16555888

||

Answers:

Correction:

  • It should be int(input('Press [1] to continue [2] to exit: ')). Your condition is never true because input returns a string, but you compare it with an integer.

Also, is old_word list for storing the new words? If yes, then you just need to add the element. Don’t add the whole list to words

import random

words = ['apple', 'banana', 'orange', 'coconut', 'strawberry', 'lime']
old_word = []

while True:
    choice = int(input('Press [1] to continue [2] to exit: '))
    if choice == 2:
        break
    
    elif choice == 1:
        new_word = input('Enter a new word: ')
        old_word.append(new_word)
        words.append(new_word)
        if new_word in words:
            random.shuffle(words)
            print(words)
Answered By: user15801675
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.