【发布时间】:2017-01-22 12:00:04
【问题描述】:
以下是我在修补 Python 时编写的基本脚本的一部分。我打算让这个脚本做的是提示我输入笔记的主题,然后要求我确认我的选择。如果出于某种原因我选择了错误的主题,我会合并一个 while 循环,该循环会重复,直到我的选择正确为止。脚本的结果是它会返回确认的主题。
执行脚本时出现的问题是,当我回复“否”(或任何其他表明我不确认这是正确选择的内容)时,终端输出会反复向我发送主题列表.终止它的唯一方法是通过 KeyboardInterrupt。
我该如何解决这个问题? 我觉得这可能与while循环中的迭代语句有关,或者break语句放置不当。
感谢您的帮助。
def subject():
subject_dict = {1: 'Mathematics', 2: 'Computer Science', 3: 'English Literature & Language', 4: 'Philosophy', 5: 'Linguistics', 6: 'Art & Design'}
subject_prompt = ("\nSelect the subject of your note.\n")
print(subject_prompt)
for i in subject_dict:
subject_choices = str(i) + ". " + subject_dict[i]
print(subject_choices)
subject_prompt_input = input("\n> ")
x = int(subject_prompt_input)
confirmation = input("\nSo the subject of your note is" + " '" + subject_dict[x] + "'" + "?\n> ")
while confirmation in ['no', 'No', 'n', 'NO']:
print(subject_prompt)
for i in subject_dict:
subject_choices = str(i) + ". " + subject_dict[i]
print(subject_choices)
subject_prompt_input
confirmation
if confirmation in ['quit', 'stop', 'exit']:
quit()
if confirmation in ['Yes', 'YES', 'yes', 'y', 'Y']:
break
if confirmation in ['yes', 'y', 'YES', 'Y']:
selection = subject_dict[x]
return selection
【问题讨论】:
-
您必须重新要求用户在循环内更新
confirmation。 -
至于您对可能输入的测试:使用
confirmation.lower(),因此您只需检查y或yes和n或no。 -
@RadLexus 感谢您的提示!
标签: python input while-loop