【问题标题】:Resolving while loop issue解决while循环问题
【发布时间】: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(),因此您只需检查yyesnno
  • @RadLexus 感谢您的提示!

标签: python input while-loop


【解决方案1】:

您是否打算一直循环直到用户按下“是”或“退出”?

如果是,则需要将输入放入循环中。

将 while 语句更改为 while True,因为您仍然没有确认变量。

while True:
    confirmation = input("\nSo the subject of your note is" + " '" + subject_dict[x] + "'" + "?\n> ")
    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

编辑:

根据您在 cmets 中的问题。

这与不足无关。

你可以这样做:

confirmation = 'no'
while confirmation in ['no', 'No', 'n', 'NO']:
...

虽然,它很丑:)

【讨论】:

  • 是的,这就是我的意图。你能解释一下为什么while confirmation in ['no', 'No', 'n', 'NO']: 不足以满足我的需要吗?
  • 我已将解释添加到答案@seeker
猜你喜欢
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 2011-06-19
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多