0

After finding these two lines online, I don't understand how the first line works to have the same effect as the second line

current = letter >= prev_letter and current + letter or letter

current = current + letter if letter >= prev_letter else letter

1 Answers1

0

The result of an and expression is either the first falsy operand or the second operand. The result of an or expression is either the first truthy operand or the second operand. It's also worth nothing that the first statement is equivalent to:

current = (letter >= prev_letter and current + letter) or letter

This means that letter >= prev_letter and current + letter will either evaluate to False if the condition is False, or current + letter. This result is then the left-hand side of the or expression. If False, the or expression will then evaluate to letter. Otherwise, it will stay as current + letter.

However, these two expressions may not be equivalent depending on the values of the variables. For example, suppose current is -1, letter is 1, and prev_letter is 0. Then the and expression evaluates to 0. This means the result of the or expression will be letter, which is 1. For these same values, the second expression would set current to 0.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113