-2

python 3.7

Hello.
I know that None is the result of nothing being returned, however I can't understand why I am getting None returned at the end of this code. I can't see anything left unfinished.

def test(a, b):
    if a == True and b == True:
        return False
    elif a == True or b == True:
        return True
    elif a == False and b == False:
        return False
    else:
        print("error... :(")

print(test(True, True))
print(test(True, False))
print(test(False, True))
print(test(False, False))
print(test(None, False))

When I run this code I get:

False
True
True
False
error... :(
None

I have also tried altering the else: statement to actually return the printed object hoping that my code was simply asking for a redundent return, but the output is the same.

    else:
        error = print("error... :(")
    return error

Can anyone shed some light on where the None is coming from?

Ivan Vinogradov
  • 4,269
  • 6
  • 29
  • 39
Cory
  • 49
  • 6
  • 3
    If you reach the end of a function without hitting a `return` then your function returns `None`. Also, `print` returns `None`. So both in both versions, your function returns `None` in that particular case. If you want it to return something different, figure out what and `return` it. – khelwood Oct 22 '18 at 14:58
  • The final `else` doesn't return anything, therefore it returns `None`. – John Gordon Oct 22 '18 at 15:02
  • Thank you Mike Scotty. I was sure someone else had asked this question before but couldn't find it. Sorry for the double up :) – Cory Oct 22 '18 at 15:04

1 Answers1

1

Your else statement prints out the line "error... :(", however you also attempt to print out the results of the function. Either let the function handle printing and return nothing (remove print statements from main body), or have the function return the string you want to print instead of printing it from the function (seen below).

def test(a, b):
if a == True and b == True:
    return False
elif a == True or b == True:
    return True
elif a == False and b == False:
    return False
else:
    return "error... :("

print(test(True, True))
print(test(True, False))
print(test(False, True))
print(test(False, False))
print(test(None, False))
bhooks
  • 409
  • 5
  • 16