python - 我想要一个输出,如果用户输入 [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'
解决方案
更正:
- 应该是
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)
推荐阅读
- docker - 如何在引导程序上配置 Graylog 插件(非交互式)?
- ruby-on-rails - Heroku 上 Sidekiq dyno 的提前时间
- vuejs2 - Vue 组合 API 在 v-for 中没有反应性?
- c++ - 将 QSettings 与存储在 QByteArray 或 QIODevice 中的数据一起使用?
- flutter - 如何将背景过滤器应用于整个屏幕,但在颤动中减少特定的小部件?
- javascript - 两个组件分别管理自己的状态和道具
- python - 如何在 Python 中编码/解码 JIS X 208、JIS X 212 和 JIS X 213 kuten 字符代码?
- c++ - 结构定义中的 VS2019 alignas 推翻了 pragma pack
- c++ - 为什么我的代码需要这么长时间才能运行,为什么它的运行时会有很大的变化?
- azure - 我看到在诊断和解决我的 Azure 应用服务中报告了 502 错误