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

Python编写邮箱/网址校验程序仅能运行一次报'str'对象不可调用错误

问题原因

  • 报错核心原因是Python内置input()函数被覆盖:遍历待校验字符串列表时,循环变量被命名为input,首次运行后内置的input()函数会被替换为字符串类型变量,第二次运行调用input()获取输入时就会抛出'str' object is not callable错误。
  • 代码存在其他可运行性问题:isValidEmail函数中email_list = email.split("@")一行使用的email变量未定义,运行时会直接抛出NameError。
  • 当前业务逻辑不符合需求:没有区分邮箱和网址的校验规则,只要判定为合法邮箱就会同时给邮箱、网址计数加1,需要后续补充网址校验逻辑。

修复后的代码

def binary_search(item,my_list):
    found=False
    first=0
    last=len(my_list)-1
    while first <= last and found == False:
        midpoint = (first + last) // 2
        if my_list[midpoint] == item:
            found = True
        else:
            if my_list[midpoint] < item:
                first = midpoint + 1
            else:
                last = midpoint - 1
    return found

def isValidEmail(email_str):
    number = ["0","1","2","3","4","5","6","7","8","9"]
    number.sort()
    if email_str.count("@") != 1:
        return False
    # 修正未定义变量问题,使用传入的参数进行分割
    email_parts = email_str.split("@")
    first_part = email_parts[0]
    last_part = email_parts[1]
    if binary_search(first_part[:1], number):
        return False
    if last_part.count(".") == 0:
        return False
    domain_parts = last_part.split(".")
    if domain_parts[0] == "" or domain_parts[-1] == "":
        return False
    return True

# 后续可补充isValidWeb函数实现网址校验逻辑
# def isValidWeb(web_str):
#     pass

n = int(input())
input_list = []
email_count = 0
web_count = 0
for i in range(n):
    input_list.append(input())

# 修正循环变量名,避免覆盖内置input函数
for item in input_list:
    if isValidEmail(item):
        email_count += 1
    # 后续补全网址校验逻辑后放开注释即可
    # elif isValidWeb(item):
    #     web_count +=1

print(f"Email,{email_count}")
print(f"Web,{web_count}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:24:03