【问题标题】:Seeking assistacne with an on online Python course exercise please请寻求在线 Python 课程练习的帮助
【发布时间】:2023-02-07 02:43:36
【问题描述】:

我一直在学习在线 Python 课程,最后的练习是检查电子邮件地址列表中的无效地址。

代码是

def has_invalid_characters(string):
    valid = "abcdefghijklmnopqrstuvwxyz0123456789."
    
    # your code here
    for i in string:
        if i not in valid:
            return True
        else:
            return False

def is_valid(email):
    
    if email.count("@") != 1:
        return False
    prefix, domain = email.split("@")
    if len(prefix) == 0:
        return False
    if domain.count(".") != 1:
        return False
    domain_name, extension = domain.split(".")
    if len(domain_name) == 0 or len(extension) == 0:
        return False
    if has_invalid_characters(prefix) == True:
        return False
    if  has_invalid_characters(domain) == True:
        return False
    else:
        return True

emails = [
    "test@example.com",
    "valid@gmail.com",
    "invalid@gmail",
    "invalid",
    "not an email",
    "invalid@email",
    "!@/",
    "test@@example.com",
    "test@.com",
    "test@site.",
    "@example.com",
    "an.example@test",
    "te#st@example.com",
    "test@exam!ple.com"
]
for i in emails:
    is_valid(i)
    if i == True:
        print(i + " is valid")
    else:
        print(i + " is invalid")

当我运行它时,我被告知应该报告为有效的前两个电子邮件地址无效,但我不知道为什么。我已经检查了几次,看不出逻辑上的错误。我也在我的笔记本电脑上运行它,我得到了相同的结果。

在课程中,这段代码是分步编写的,最后一步是将 for 循环从简单地打印电子邮件地址更改为验证它们,并且在我修改 for 之前的所有内容都被标记为正确。

如果有人能向我指出这段代码的问题,我将不胜感激。

【问题讨论】:

  • 你的测试应该是:if is_valid(i): print("good") else: print("bad")
  • 您的函数 has_invalid_characters 将只查看您传入的字符串的第一个字符,因为在 for 循环的第一次迭代期间,您将返回 True 或 False。 return 终止函数,在这种情况下过早。您只想在查看每个字符并确认每个字符都有效后返回 False。
  • all()函数在has_invalid_characters()中会有用。

标签: python


【解决方案1】:

我发现了问题。我对 is_valid() 函数的调用不正确。

它应该是

for i in emails:
    result = is_valid(i)
    if result == True:
    .....

很抱歉给您带来麻烦。

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多