Python try/except … function always returns false

允我心安 提交于 2019-12-06 02:40:16

You haven't included a return statement for the positive case... Also, when a function doesn't include a return statement, the caller receives None instead...

def add(self):

    #1 -- VALIDATE EMAIL ADDRESS
    #Check that e-mail has been completed
    try:
        #Validate if e-mail address is in correct format
        if (isAddressValid(self.email) == 0):
            self.errors['email'] = 'You have entered an invalid e-mail address';
            return False

    except NameError:
        self.errors['email'] = 'Please enter your e-mail'
        return False

    return True

Actually you have two values.

  • 0
  • None

If you print the value instead of using it in an if-statement, you'll see the two conditions. Consider adding print statements to see what the value actually is.

if (isAddressValid(self.email) == 0):

If this is True, you get 0.

If this is False, you'll get None.

And the exception give 0.

If I were re-writing this code, I would go for something like this:

def add(self):
    try:
        if not isAddressValid(self.email):
            self.errors['email'] = 'You have entered an invalid e-mail address';
    except NameError:
        self.errors['email'] = 'Please enter your e-mail'
    return 'email' not in self.errors

Im not sure what problem you are talking about , but you are always returning 0

Try adding an else clause for the case of the Valid Email (which you are currently not considering)

def add(self):

#1 -- VALIDATE EMAIL ADDRESS
#Check that e-mail has been completed
try:
    #Validate if e-mail address is in correct format
    if (isAddressValid(self.email) == 0):
        self.errors['email'] = 'You have entered an invalid e-mail address';
        return 0
    else
        return 1

except NameError:
    self.errors['email'] = 'Please enter your e-mail'
    return 0

You said isAddressValid is a method, right? Since add is also a method, perhaps you have to prepend a self.:

if (self.isAddressValid(self.email) == 0):

This most probably will deal with your NameError.

After that, add an else clause when the check succeeds:

    …
    self.errors['email'] = 'You have entered an invalid e-mail address'
    return 0
else:
    return 1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!