我是初學者,需要一些幫助。我怎樣才能確保用戶的輸入只有3位數字。我知道如何確保它是否數字,但需要的是隻有3個。這是我到目前爲止有:如何檢查raw_input是否包含3位數字?
while not (area_code.isdigit()):
# do something here
我想「.isdigit()」是3個位數。
我是初學者,需要一些幫助。我怎樣才能確保用戶的輸入只有3位數字。我知道如何確保它是否數字,但需要的是隻有3個。這是我到目前爲止有:如何檢查raw_input是否包含3位數字?
while not (area_code.isdigit()):
# do something here
我想「.isdigit()」是3個位數。
while not len(area_code) == 3:
# Do stuff
你需要明確地測試字符串的長度也:
while not (area_code.isdigit() and len(area_code) == 3):
str.isdigit()
如果有至少一個字符,所有字符是數字是唯一的真實。剩下的就是對長度的測試。
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(area_code.isdigit()和len(area_code)== 3)' – 2014-08-28 17:35:08
@PadraicCunningham:否,while循環應該繼續,直到找到正確的'area_code'。 OP有'while not area_code.isdigit()',我只是增加了長度要求。 – 2014-08-28 17:36:43
但是如何在while循環中未定義'while while area_code.isdigit()和len(area_code)== 3)'循環永遠循環? – 2014-08-28 17:39:08