Unclear output from a function

Question:

I am new to coding and I was trying to play around with tools that I learnt during these days. The first thing that I want to ask is why when I put a number that it is x the output is always “good”. What do I do wrong? Secondly, when I tried to put return instead of print e.g. return Y the output is blank, why is that?

if anything is unclear let me know. Thank you.

def championships_won(x):
    if (championships_won == x):
        print("bad")
    else:
        print("good")

x = 5

championships_won(5)
Asked By: Kovacic95

||

Answers:

why when I put a number that it is x the output is always “good”?

championships_won is a function object, not a number. championships_won == x will never be true unless x = championships_won. I’m not sure what you’re trying to do there.

when I tried to put return instead of print e.g. return Y the output is blank, why is that?

Because you’re not printing anything, and nothing is ever printed implicitly in Python. If you want to print the return value, just do it like this:

print(championships_won(5))
Answered By: wjandrea

The reason for getting always “good” is that you compare championships_won, which is function, with the function parameter which in your case is integer. This would be always False and that’s why the output will be always “good”.

Try to change your code to:

def championships_won(x):
    if (x == 5):
        print("bad")
    else:
        print("good")

championships_won(5) # output: bad

Secondly, output and return value are 2 different things. The returned value of a function won’t appear as an output unless you print it.

def championships_won(x):
    if (x == 5):
        return "bad"
    else:
        return "good"

print(championships_won(5)) # output: bad
Answered By: Gabio
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.