'Why does python print two answers?

    if number > 2 and  number < 100:
        print ("yay")
    else:
        print ("boo")

print(test(394))

why does the code give me two different answers? boo and None.



Solution 1:[1]

Your function does not return a value, so printing the result of test(x) will always return None. However in the function, it prints the result, so there's no reason to wrap your test() in a print statement.

For example, either:

def test(x):
    if x > 2 and x < 100:
        return "yay"
    else:
        return "boo"

print(test(394))

or

def test(x):
    if x > 2 and x < 100:
        print("yay")
    else:
        print("boo")

test(394)

Solution 2:[2]

If we assume that your function is something like,

def test(number):
    if number > 2 and  number < 100:
        print ("yay")
    else:
        print ("boo")

print(test(394))

Then you are getting two outputs because you have written a print statement inside the function and then are printing the function output itself.

This way you would be getting

boo
None

To fix this either just type test(394) instead of print(test(394)) or do

def test(number):
    if number > 2 and  number < 100:
        return "yay"
    else:
        return "boo"

print(test(394))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Zero