首页 > 解决方案 > 我想要一个输出,如果用户输入 [1],他将能够在现有列表中插入一个新单词。如果 [2] 程序将关闭

问题描述

我正在尝试输入[1]并输入一个新单词以将现有单词附加到列表“单词”中以随机播放模式。

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)

例如输入1 Enter a new word: lemon

输出 'orange', 'banana', 'lime', 'apple', 'lemon','coconut', 'strawberry'

标签: pythonlistloops

解决方案


更正:

  • 应该是int(input('Press [1] to continue [2] to exit: '))。您的条件永远不会为真,因为input返回一个字符串,但您将它与一个整数进行比较。

另外,是old_word存储新词的列表吗?如果是,那么您只需要添加元素。不要将整个列表添加到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)

推荐阅读