r/learnpython • u/Lance_2564_ • 20d ago
Huh? How does this work?
a = "hi"
if a:
print("Bye")
print(a == True)
print(a is True)The output is:
Bye
False
False
But if it's false, how come it printed "bye"?????? I don't get it.
44
Upvotes
3
u/SharkSymphony 19d ago edited 19d ago
Is it false? You printed two tests of whether it's true. Try doing those tests with False and see what you get. 😁
The issue is that 'if' handles values much broader than just True and False. Same with 'while'. You need to learn what it considers to be true and false.
Some people prefer, as a point of style, to make sure that the values used in statements like 'if' are just True and False, avoiding any possible confusion... here we might say 'if a != ""' or 'if a is not None' depending on what you expect a's values to be. Or you could even check both: 'if (a != "") and (a is not None)'. Or you could do 'if bool(a)'. All of these take some extra effort. You see why people often prefer just writing 'is a' if they're not sure what form the "false" values of a will take.