if print("welcome"):
print("heelloo!")
else:
print("bbye!")
This piece of code prints both welcome and bbye. So, is the if condition never executed, or is it something else? Kindly explain as I am fairly new to Python.
There is supposed to be a condition after the word if
. You've put there a print
function call. What the if
statement will do is that it will call the print
function (hence printing your "welcome") and decide whether to execute the if branch or the else branch, by looking at the return value of print
.
print
always returns None
. None
is considered a false value (so is 0 btw), so the else branch executes, printing "bye".
The print function returns None which evaluates to False. Hence both will be printed. You can check the return value of the print function with this,
print(print("welcome")) # prints None which evaluates to False in if
if print("welcome")
?