+ 1

Python: the "OR" logical operator question

b="abc" func1 = (lambda s:s[1:]) func2 = (lambda s:s[:-1]) func3 = (lambda s:s[1:]) or (lambda s:s[:-1]) print (func1 (b)) #outputs bc print (func2 (b)) #outputs ab print (func3 (b)) #outputs bc --> From what I understand, this is the same as: "bc" or "ab" --> or is a logical operator... so why isn't the output a true/false type? --> what does "bc" or "ab" evaluate to bc?

15th Sep 2020, 8:42 PM
Solus
Solus - avatar
5 Respostas
+ 3
Or is a logical operator, which checks for the first value. If the first value is true/truthy then it will return the first value If the first value is false/falsey then it will return the second value! 'Or' operator can return anything 🙌 It is not bound to return only true or false Falsey values are => 0, "", [], (), (,), {}, None Truthy are all the values accept the above mentioned values! Since the function returning "bc" is truthy then it will not allow the or operator to go for the second value! And hence the first value i.e. "bc" is returned! More to know: Try this: func3 = (lambda s: s[1:1]) or (lambda s: s[:-1])
15th Sep 2020, 9:02 PM
Namit Jain
Namit Jain - avatar
+ 1
Solus Ya, that's why I added it in 'more to know' (lambda s:s[1:1]) is not any string, it is a function! And function is not there in the falsey list! Hence, the first function will be considered! No matter what it is returning! I guess, I confused you in my first answer! 😅 (Edited it)
15th Sep 2020, 10:12 PM
Namit Jain
Namit Jain - avatar
0
Any thing other than None, zero, empty string, empty list, empty dictionary and so on is true and in or operator if the first expression equal true then no need to check the rest for example 2 or 3 = 2, 'a' or 'b' = a But "" or 'b' = b since empty string is false so it needs to check the second expression which is b 0 or 3 = 3 because 0 is false
15th Sep 2020, 9:00 PM
Ruba Kh
Ruba Kh - avatar
0
Namit Jain b="abc" func1 = (lambda s:s[1:1]) func2 = (lambda s:s[:-1]) func3 = (lambda s: s[1:1]) or (lambda s: s[:-1]) print (func1 (b)) #outputs empty string --> falsey print (func2 (b)) #outputs ab --> truthy print (func3 (b)) # (lambda s:s[1:1]) outputs an empty string (the first value) This follows the opposite rule as you've mentioned: " If the first value is true/truthy then it will return the second value If the first value is false/falsey then it will return the first value! " How come?
15th Sep 2020, 10:00 PM
Solus
Solus - avatar
0
Ruba Kh How would you explain this then? b="abc" func1 = (lambda s:s[1:1]) func2 = (lambda s:s[:-1]) func3 = (lambda s: s[1:1]) or (lambda s: s[:-1]) print (func1 (b)) #outputs empty string --> false print (func2 (b)) #outputs ab --> true print (func3 (b)) # (lambda s:s[1:1]) outputs an empty string (the first value)
15th Sep 2020, 10:09 PM
Solus
Solus - avatar