【发布时间】:2014-08-28 17:24:37
【问题描述】:
我是初学者,需要一些帮助。我怎样才能确保用户的输入只有 3 位数字。我知道如何确定它是否是数字,但只需要 3。这就是我到目前为止所拥有的:
while not (area_code.isdigit()):
# do something here
我希望“.isdigit()”为 3 位数。
【问题讨论】:
标签: python python-2.7
我是初学者,需要一些帮助。我怎样才能确保用户的输入只有 3 位数字。我知道如何确定它是否是数字,但只需要 3。这就是我到目前为止所拥有的:
while not (area_code.isdigit()):
# do something here
我希望“.isdigit()”为 3 位数。
【问题讨论】:
标签: python python-2.7
您还需要明确测试字符串的长度:
while not (area_code.isdigit() and len(area_code) == 3):
str.isdigit() 只有在至少有一个字符且所有字符都是数字时才为真。那么剩下的就是对长度的测试了。
【讨论】:
while (area_code.isdigit() and len(area_code) == 3)
while 循环应该继续,直到找到正确的area_code。 OP 有while not area_code.isdigit(),我只是添加了长度要求。
while not area_code.isdigit() and len(area_code) == 3) 没有在循环内定义,它如何永远循环?
( 的开场白。 while 循环的主体在这里完全脱离上下文,但如果主体中的area_code = '123' 将结束循环。
while True:
inp = raw_input()
if len(inp) == 3 and inp.isdigit():
break
如果你想接受多个输入,你需要在你的循环中接受输入
使用您的示例:
area_code = raw_input()
while len(area_code) != 3 or not area_code.isdigit():
area_code = raw_input()
【讨论】:
while not len(area_code) == 3:
# Do stuff
【讨论】: