You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何.isdigit()校验失效,非法手机号仍可被录入?

手机号校验代码错误修复

问题描述

输入以021开头、长度符合要求但包含字母的手机号时,代码虽会输出错误提示,但仍会将该无效号码录入到details列表中。

原代码

while True:
  print("")
  print("Enter your phone number below.")
  phonenumber = input("")
  # if phonenumber has the right starting digits
  if phonenumber[0] == "+" and phonenumber[1] == "6" and phonenumber[
      2] == "4" or phonenumber[0] == "0" and phonenumber[1] == "2":
    for i in range(1, len(phonenumber)):
      # checks all characters
      if not phonenumber[i].isdigit():
        print("")
        print("Please use the correct phone number.")
        continue

    # checks the phone number length
      if phonenumber[i].isdigit():
        if len(phonenumber) <= 15 and len(phonenumber) >= 10:
          phonenumber = phonenumber.replace(" ", "")
          details.append(phonenumber)
          print("")
          print("Information successfully inputed.")
          print("")
          print("---------------")
          print("")
          break
          
    else:
      print("")
      print("Please use the correct phone number.")
      continue

  # else if it doesn't start right
  else:
    print("Try again, matey.")
    continue

问题根源

  1. 循环逻辑混乱:检测到非数字字符时用continue跳过当前迭代,后续遇到数字字符仍会触发长度校验和录入,导致无效号码被添加。
  2. 校验顺序错误:长度校验嵌套在循环内部,未确保所有字符都是数字就执行录入操作。
  3. 空格处理滞后:在录入前才移除空格,导致校验时的长度和字符判断受空格干扰。

修复后的代码

# 预先定义存储号码的列表
details = []

while True:
    print("\nEnter your phone number below.")
    phonenumber = input().strip()
    # 先移除所有空格,统一格式
    cleaned_phone = phonenumber.replace(" ", "")
    
    # 校验开头格式是否合法
    valid_start = False
    if len(cleaned_phone) >= 3 and cleaned_phone[:3] == "+64":
        valid_start = True
    elif len(cleaned_phone) >= 2 and cleaned_phone[:2] == "02":
        valid_start = True
    
    if not valid_start:
        print("\nTry again, matey.")
        continue
    
    # 校验除合法开头外的所有字符是否为数字
    valid_chars = True
    # 根据开头类型确定校验起始位置
    start_check_index = 3 if cleaned_phone.startswith("+64") else 2
    for char in cleaned_phone[start_check_index:]:
        if not char.isdigit():
            valid_chars = False
            break
    
    if not valid_chars:
        print("\nPlease use the correct phone number.")
        continue
    
    # 校验号码长度是否符合要求
    if 10 <= len(cleaned_phone) <= 15:
        details.append(cleaned_phone)
        print("\nInformation successfully inputed.")
        print("\n---------------")
        # 如需仅录入一个号码,取消下方注释
        # break
    else:
        print("\nPlease use the correct phone number.")

修复说明

  • 提前统一格式:先移除所有空格,避免格式干扰后续校验。
  • 拆分校验步骤:按「开头格式→字符合法性→长度」的顺序依次校验,逻辑清晰,任何一步不通过直接终止后续流程。
  • 严格字符校验:仅跳过合法的开头符号(+),确保剩余部分全为数字,只要有一个非法字符就标记无效,避免错误录入。
  • 校验通过才录入:所有条件满足后才将号码添加到details,从根源杜绝无效数据。

内容的提问来源于stack exchange,提问作者Bastronom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 14:00:29