0

Why (x and y) == y ? Why (x or y) == x ?

x, y have any types. (x and y) always equals y (except when x==0) (x or y) always equals x (even if y == True) Why?

6th Jul 2020, 10:23 AM
Alex
3 Antworten
+ 2
In Python logical operators won't convert results into booleans, but have certain logics to return either of the operands. Easy way would be to compare them to equivalent ternary operators: A and B: A if not A else B A or B: A if A else B In words: A and B: Returns A, if bool(A) is False, otherwise it returns B. A or B: Returns A, if bool(A) is True, otherwise it returns B.
6th Jul 2020, 11:42 AM
Seb TheS
Seb TheS - avatar
+ 1
Because when comparing x and y (with the "and" operator), you are forcing python to convert them to boolean. Python considers all numbers/characters to be true, except for 0. Therefore, if you compare any two numbers with "and", it will give you true unless one of them is 0/False (that's how "and" works). And when you compare them with "or", it will be enough for one of them to be a number/character in order for the statement to be all true (that's how "or" works"). Good Luck.
6th Jul 2020, 10:32 AM
Mohamad Kamar
Mohamad Kamar - avatar
0
Thanks. Your answer is very logical, but try, please, following: z = "abc" and [1,2] print(z) You'll get [1,2] but not True. Python gives result without conversion to boolean. z = "abc" or True print(z) abc It's really funny, but hard for user's brain
6th Jul 2020, 10:52 AM
Alex