返回None并且不打印任何功能异常

时间:2018-07-25 12:14:05

标签: python

我试图返回None,并且不在函数外打印任何内容。例如,一旦我调用了doAtest函数,如果返回True,我将打印“有效信息”。如果返回False,我将打印“错误无效字母”。

但是,我要在这里实现的是一旦它进入else函数中的doAtest块,我只希望它仅打印“错误:无效格式”。

现在,尽管我返回“无”,但它仍会打印“错误:格式无效”和“错误:字母无效”。我有什么办法可以返回一个Null函数,使它不会在函数中输出任何内容?

def doAtest(user):
    #Do some calculations       

    if(some condition):          
        if(some condition):                                                
            return True
        else:
            return False

    elif(some condition):     
        if (some condition):
            return True
        else:
            return False

    else:
        print("Error: Invalid Format")
        return None  


user_raw = input("Enter your employee code :")

if doAtest(user_raw):                   # Here prints True condition
    print("Valid Information")

else:
    print("Error: Invalid Letter")      # Here prints False condition

1 个答案:

答案 0 :(得分:0)

您的问题

正如@Patrick Haugh在评论中解释的那样,None被认为是“虚假的”。因此,使用以下代码,如果doAtest()返回None,则将执行else块:

if doAtest(user_raw):
    print("Valid Information")
else:
    print("Error: Invalid Letter")

解决方案

您可以检查结果是否is True,然后检查是否is not None,而不使用else

此外,您可能希望通过添加将处理print()的{​​{1}}子句来组合对else的所有调用,而不是在None函数中处理它

doAtest()
相关问题