要在Python中显示的有效错误消息

2024-05-23 19:02:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下python代码用于验证电话号码。 现在,这个程序返回True或False。 当结果为False时,应为错误msgs,例如:

  1. 国家代码是错误的
  2. 已通过国家/地区的电话格式错误
  3. 给定国家/地区的有效格式如下

有人能帮我修改一下下面的代码吗

import phonenumbers


def is_valid(number,country):

    try:
        pn = phonenumbers.parse(number,country)
        if phonenumbers.is_possible_number(pn) and phonenumbers.is_valid_number(pn):
            return True
    except:
            return False
    return False

def validNumber(phone_number,country):

    try: 
        parsed = phonenumbers.format_number(phonenumbers.parse(phone_number,country),
                                            phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    except:
        parsed = str(None)
        print(parsed)
    return parsed

def main():
    while True:
        phone_number=input('Enter your telephone number: ')
        country=input('Enter your country: ')

        phone_number = phone_number.replace('+', '', 1)
    
        parsed = validNumber(phone_number,country)
        valid_value = is_valid(parsed,country)
        
        if valid_value:
            print('{} is a valid entry.'.format(phone_number))
            break
        else:
            print('{} is a not valid entry, please try again.'.format(phone_number))
main()

Tags: 代码falsetruenumberreturnisdef错误
1条回答
网友
1楼 · 发布于 2024-05-23 19:02:26

您可以在每个验证函数中打印除块之外的错误消息。 比如说,

error_msg = "The phone format for passed country is wrong" 
def is_valid(number,country):
    try:
        pn = phonenumbers.parse(number,country)
        if phonenumbers.is_possible_number(pn) and phonenumbers.is_valid_number(pn):
            return True
    except phonenumbers.NumberParseException as e:
        print(e, error_msg)
    return False

有关详细信息,请查看此链接:https://www.programcreek.com/python/example/104093/phonenumbers.NumberParseException

相关问题 更多 >