+ 2

Explain please how the next code works

I didn't get how "a" or "b" works https://code.sololearn.com/coLCIglQOFcf/?ref=app

7th Jul 2022, 4:28 AM
kuzantiv
kuzantiv - avatar
6 Respuestas
+ 6
Hi Anton You have to laborate with ‘and’ and ‘or’ a bit to understand it. Try using parantheses around: (a and b) or c respective: a and (b or c) Set a, b and c to True or False and test different cases. You can even try bool("a") will give a True value, while bool("") gives a False value. So in your case you tests it will works like this: >>> x = 5 >>> print(("a" and x < 7) or "b") True >>> x = 5 >>> print((x < 7 and "a") or "b") a >>> x = 10 >>> print((x < 7 and "a") or "b") b
7th Jul 2022, 5:46 AM
Per Bratthammar
Per Bratthammar - avatar
+ 3
Thanks for such a detailed answer
7th Jul 2022, 5:55 AM
kuzantiv
kuzantiv - avatar
+ 3
Every value in Python are either falsy or truthy. For example 0, set(), (), {}, [], 0.0 is falsy. 1, 5, -2.5, (1, 3), [1, 2, 3] etc is truthy. (Test them whit bool().) When you use ’and’ or ’or, the first value that satisfy the expression vill be returned. If it is a value that return False or True that will be delivered. But if it is an other value, for example a number (how also can be false or true, it return its value. So 4 and True vill retern True, True and 4 vill return 4. 4 or True vill return 4 (because 4 is a truthy value and ’or’ gives that if on value is true, the hole expression is true (it reads from left to right and stop reading when satisfied)). Try!
7th Jul 2022, 7:32 AM
Per Bratthammar
Per Bratthammar - avatar
+ 3
Very interesting question and answer! Thanks Anton and Per Bratthammar for the insight!
7th Jul 2022, 5:46 PM
Emerson Prado
Emerson Prado - avatar
+ 1
Now it is clearer for me )
7th Jul 2022, 7:34 AM
kuzantiv
kuzantiv - avatar
0
Wait a second, I understand the boolean logic But in this code we compare the bool value to a string. How so? We get: 7>5 and "a" or "b" True and string or string
7th Jul 2022, 6:40 AM
kuzantiv
kuzantiv - avatar