循环不会中断

问题描述 投票:-3回答:1

这是我的代码,由于某种原因,即使我输入了正确的AM或PM,它也会继续运行

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
python python-3.x loops user-input
1个回答
0
投票

我不确定您为什么遇到这个问题。我尝试了您的代码,它可以正常工作。

我建议先拆分,然后开始进行索引检查是否有时间和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
© www.soinside.com 2019 - 2024. All rights reserved.