0

我希望程序删除 () 和 - 当有人进入他们的电话时可能会输入的。如果不产生循环,我还想确保它是 10 个数字字符长。

p = raw_input("Please enter your 10 digit Phone Number")
def only_numerics(p):
    seq_type= type(p)
    return seq_type().join(filter(seq_type.isdigit, p))
p = only_numerics(p)

valid_phone = False
while not valid_phone:

    if p > "0000000000" and p < "9999999999" and len(p) == 10 :
        print "You have entered " + p
        valid_phone=True
    else:
        print "You have entered an invalid choice"

如果我输入少于 10 个数字,我会重复 else 打印命令。我希望它返回原始输入(“请输入您的 10 位电话号码”)。有没有办法做到这一点?

4

5 回答 5

2

除了像 James 指出的那样在循环内设置“raw_input”之外,您可能对使用正则表达式感兴趣并使您的代码更漂亮:

import re
phone_re = re.compile(r'\d{10}$')

def only_numerics(p):
    seq_type= type(p)
    return seq_type().join(filter(seq_type.isdigit, p))

valid_phone = False
while not valid_phone:
    p = raw_input("Please enter your 10 digit Phone Number: ")
    p = only_numerics(p)
    if phone_re.match(p):
        print "You have entered " + p
        valid_phone=True
    else:
        print "You have entered an invalid choice"
于 2013-04-20T23:03:18.257 回答
1

它循环回到 print 语句,因为您在 while 循环之外定义了 p 。更改此设置将解决循环问题:

valid_phone = False
while not valid_phone:

    p = raw_input("Please enter your 10 digit Phone Number")
    def only_numerics(p):
        seq_type= type(p)
        return seq_type().join(filter(seq_type.isdigit, p))
    p = only_numerics(p)


    if p > "0000000000" and p < "9999999999" and len(p) == 10 :
        print "You have entered " + p
        valid_phone=True
    else:
        print "You have entered an invalid choice"
于 2013-04-20T22:53:28.790 回答
0

def val_number(input_num):

valid_num=re.findall(r'\d+',input_num)
if len(valid_num[0])>10:
    print('You have entered more than 10 digits')
else:
    return(valid_num)
于 2015-08-03T12:29:36.263 回答
0

此 python 代码验证 11 位手机号码:

valid = True
mobile_number = str(input("What is your mobile number? "))
while len(mobile_number) != 11 or mobile_number[0] != "0" or mobile_number[1:].isdigit() == False:
    mobile_number = str(input("Please enter a valid mobile number: "))
    valid = False
print("Your mobile number is valid")
于 2016-05-27T10:59:58.270 回答
0

而(真):

try:
    phone_number=int(input("please enter the phone number:no spaces in between: \n"))
except ValueError:
    print("mismatch")
    continue
else:
    phone=str(phone_number)
    if(len(phone)==10):
        break
    else:
        print("10 digits please ")
        continue
于 2017-03-27T15:16:15.880 回答