Python闪卡程序问题:如何随机切换键与值的显示顺序
闪卡程序功能修改问题
需求:实现一个闪卡程序,从字典中随机选择条目,随机决定先显示键(如Test-n)还是对应的值(如Definition-n),按下回车键后显示对应的另一半。当前代码每次只能先显示键再显示值,需要调整实现随机切换显示顺序的功能。
示例效果:
- Test-1(按回车键)→ Definition-1
- Definition-4(按回车键)→ Test-4
- Definition-2(按回车键)→ Test-2
- Test-3(按回车键)→ Definition-3 ...
原代码
from random import * def flashcard(): random_key = choice(list(dictionary)) print('Define: ', random_key) input('Press return to see the definition') print(dictionary[random_key]) dictionary = {'Test-1':'Definition-1', 'Test-2':'Definition-2', 'Test-3':'Definition-3', 'Test-4':'Definition-4'} exit = False while not exit: user_input = input('Enter s to show a flashcard and q to quit: ') if user_input == 'q': exit = True elif user_input == 's': flashcard() else: print('You need to enter either q or s.')
修改方案
核心是在选择随机条目后,新增随机逻辑控制显示顺序,同时修正原代码的语法错误:
修改后的完整代码
from random import choice def flashcard(): # 随机选择一个字典条目 random_key = choice(list(dictionary)) value = dictionary[random_key] # 随机决定先显示键还是值 show_key_first = choice([True, False]) if show_key_first: print(f"请回忆对应内容: {random_key}") input("按回车键查看答案") print(value) else: print(f"请回忆对应内容: {value}") input("按回车键查看答案") print(random_key) dictionary = {'Test-1':'Definition-1', 'Test-2':'Definition-2', 'Test-3':'Definition-3', 'Test-4':'Definition-4'} exit = False while not exit: user_input = input('输入s显示闪卡,输入q退出: ') if user_input == 'q': exit = True elif user_input == 's': flashcard() else: print('请输入q或s')
关键修改点
- 新增
show_key_first变量:通过choice([True, False])生成随机布尔值,控制先显示键还是值 - 分支处理两种显示逻辑:分别实现"先键后值"和"先值后键"的交互流程
- 修正语法错误:将原代码中
exit = False while not exit:拆分为两行,符合Python语法规范 - 优化提示文本:将英文提示改为中文,让交互更直观
内容的提问来源于stack exchange,提问作者therules
相关产品推荐
相关产品推荐

