From Python:
>>> 1 and 2
2
>>> 1 and 2 and 3
3
>>> 3 and 2 and 1
1
>>> 'a' and 'b'
'b'
Why Python returns these result? What is the logic for that when dealing with pure numbers or strings?
From Python:
>>> 1 and 2
2
>>> 1 and 2 and 3
3
>>> 3 and 2 and 1
1
>>> 'a' and 'b'
'b'
Why Python returns these result? What is the logic for that when dealing with pure numbers or strings?
When two expressions have 'and' keyword between them, the interpreter first checks the first expression. If the first expression is false, it doesn't even check the second one. This is the case for all programming languages. If there are multiple expressions, it goes from left to right. The order is important as it is a good practice to write computationally expensive operations to the end of the 'and' expression.
In your first example python evaluates 1 as true and goes to the next expression and returns the result of last expression. If you had a case something like
'a' and False and 'b'
it would return False
, because the interpreter will stop after a statement which is false.