0

如果输入不是 1 或 2,如何重新提示此输入?

status = eval(input("Are they single(1) or married(2)? \n"))
4

2 回答 2

3

使用循环:

while True:
    status = input("Are they single(1) or married(2)? \n")
    if status in ('1', '2'):
        break

顺便说一句,不要使用eval. 它可以评估任意表达式。如果要将输入字符串转换为 int,请int改用。

于 2013-11-13T03:59:46.370 回答
0

@falsetru,已经用我喜欢的方式回答了。这是您可能会在其他地方看到的几个替代方案

status = input("Are they single(1) or married(2)? \n")
while status not in ('1', '2'):
    status = input("Are they single(1) or married(2)? \n")

由于提示重复,这是不可取的

status = -1 # or 0 or None or some other invalid value
while status not in ('1', '2'):
    status = input("Are they single(1) or married(2)? \n")

我认为这很难看,但有些人不喜欢使用break

我更喜欢@falsetru 版本的一个原因是,for当您想计算/限制重试次数时,很容易转换为循环。

于 2013-11-13T04:08:00.607 回答