+ 1
I copied a working code of comparing ages over internet but I am unable to understand the 7 th line of this code pls explain me
4 Réponses
+ 2
txt=['younger than', 'the same age as', 'older than'][(self.age <= other.age) + (self.age < other.age)]
It is simple indexing
Let's assume it was txt=['younger than','the same age','older than'][0] would have returned the first element ,if it was [1] second element would have been returned, [2] would have returned third element
Let's take this part
[(self.age <= other.age) + (self.age < other.age)]
if self.age is <=other. age then it will result in true which is implicitly converted to integer value 1 and self.age <other.age will return return 1 as well so 1+1 =2 , therefore it will return other. person is "older than" self.person which is right
Like this if it was self.age<=other age results in false and self.age<other.age results in false
You will get 0+0=>0 and it will return other.person is "younger than" self.person which again is right
And if both had same age then
self.age<=others.age will return 1 and self.age<others.age will return 0 so 1+0 =>1 and you will get same age which is right
+ 2
(self.age <= other.age) + (self.age < other.age) = (10 <= 1) + (10 < 1) = False + False = 0 + 0 = 0
So it will return the first element of txt.
This is because python has an implicit conversion between type bool and type int when the interpreter sees the '+' sign.
+ 1
Abhay thanks now I got it
0
QTWizard
I can't understand what you said
Could you pls explain me in an easier way