Python:使用字符串长度进行输入验证

Python:使用字符串长度进行输入验证,python,validation,input,Python,Validation,Input,好的,所以我需要确保电话号码的长度是正确的。我想出了这个,但得到了一个语法错误 phone = int(input("Please enter the customer's Phone Number.")) if len(str(phone)) == 11: else: phone = int(input("Please enter the customer's Phone Number.")) phonumber.append(phone) 您可以尝试此方法来询问电话号码,直到正确为

好的,所以我需要确保电话号码的长度是正确的。我想出了这个,但得到了一个语法错误

phone = int(input("Please enter the customer's Phone Number."))
if len(str(phone)) == 11:
    else: phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)

您可以尝试此方法来询问电话号码,直到正确为止:

phone = ""
while len(str(phone)) != 11:
    phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
如果还要检查输入是否为数字而不是文本,则还应捕获由
int
引发的异常,例如:

phone = ""
while len(str(phone)) != 11:
    try:
        phone = int(input("Please enter the customer's Phone Number."))
    except ValueError:
        phone = ""
phonumber.append(phone)
你不可能

if:
    else:
因为位于第一个
if
块内的
else
没有相应的
if

应该是:

if:
    this
else:
    that 

您可以将第一行写为
phone='
。因为您不会对电话号码进行数学运算,所以将其转换为整数是合适的。这是一个准确的答案,但老实说,OP似乎不知道最基本的Python语法。OP的知识水平和这个答案的复杂性之间的差异使得这个问答对imo毫无帮助。答案不是用来为人们编写代码的。出于这个原因,@jornsharpe的答案可能实际上更多地是关于这个问题的主题。我以为你已经解决了这个问题,我正试图编辑它:)但这是你的代码真正的错误。