【问题标题】:Loop does not break循环不中断
【发布时间】:2019-11-24 00:43:15
【问题描述】:

这是我的一段代码,由于某种原因,即使我输入正确的上午或下午,它也会继续

while True:
    user_in = input('Please enter the time in the following 12Hour format HH:MM AM|PM : ')

    time_in = user_in.split()
    time_input = time_in[0].split(':')
    latin_input = time_in[1]

    if (latin_input != 'AM' and latin_input != 'PM'):
        continue
    else:
        break

【问题讨论】:

  • hmmm 对我来说似乎工作正常。您能提供您使用的输入吗?
  • 试试'AM' not in latin_input and 'PM' not in latin_input

标签: python python-3.x loops user-input


【解决方案1】:

我不确定您为什么会遇到这个问题。我试过你的代码,它可以工作。

我建议在拆分并开始索引之前先检查是否有时间和 latin_input,因此当您使用索引时,它不会破坏您的代码。先验证后处理。像这样的:

while True:
    user_in = input('Please enter the time in the following 12Hour format HH:MM AM|PM : ')

    if len(user_in.split()) != 2 and not user_in.endswith(('AM', 'PM')):
        continue

    time_in, latin_input = user_in.split()

    break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2021-01-30
    • 2013-11-01
    相关资源
    最近更新 更多