Python: 用字符串长度验证输入
好的,我需要确保电话号码的长度是正确的。我想了一个办法,但出现了语法错误。
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)
2 个回答
2
你可以试试这样做,让用户一直输入手机号码,直到输入正确为止:
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)
2
你不能这样写
if:
else:
因为这个 else
是在第一个 if
里面的,所以它没有对应的 if
。
应该这样写:
if:
this
else:
that