返回None,不打印函数外的任何内容

2024-05-23 22:21:37 发布

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

我正在尝试返回None,并且不打印函数之外的任何内容。例如,一旦我调用了doAtest函数,如果返回True,我将打印“有效信息”。如果它返回False,我将打印“Error Invalid Letter”。你知道吗

然而,我在这里试图实现的是,一旦它进入doAtest函数中的else块,我只希望它只打印“Error:Invalid Format”。你知道吗

现在它打印“Error:Invalid Format”和“Error:Invalid Letter”,尽管我不返回任何内容。有没有一种方法可以让我返回一个空函数,这样它就不会打印出函数中的任何内容?你知道吗

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

Tags: 函数falsetrueformat内容returniferror
1条回答
网友
1楼 · 发布于 2024-05-23 22:21:37

你的问题

正如@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()的调用组合在一起,方法是添加一个else子句来处理None,而不是在doAtest()函数中处理它。你知道吗

result = doAtest(user_raw)

if result is True:
    print("Valid Information")
elif result is not None:
    print("Error: Invalid Letter")
#else:
#    print("Error: Invalid Format")

相关问题 更多 >