帮我写一个小程序随机循环单词并且可以暂停自定义词库
以下是一个基于Python的小程序,可以随机循环单词并且可以暂停,同时允许自定义词库。
import random
import time
# 自定义词库
words = ['apple', 'banana', 'orange', 'peach', 'pear']
# 选择随机单词
def choose_word():
return random.choice(words)
# 随机循环单词
def random_loop():
while True:
word = choose_word()
print(word)
time.sleep(1)
# 主函数
def main():
print('Press ENTER to pause or resume the loop.')
print('Press Ctrl+C to exit.')
try:
while True:
# 开始循环
print('Starting loop...')
random_loop()
except KeyboardInterrupt:
# 捕获Ctrl+C,退出程序
print('Exiting...')
exit()
if __name__ == '__main__':
main()
使用方法:
- 将以上代码复制到Python环境中,保存为一个Python文件(例如
random_word.py)。 - 在代码中自定义词库,添加或删除单词。
- 运行程序,将会开始随机循环单词。
- 按下回车键可以暂停或恢复循环。
- 按下Ctrl+C可以退出程序
原文地址: https://www.cveoy.top/t/topic/eFre 著作权归作者所有。请勿转载和采集!