0

I'm having some trouble understanding why is there a Traceback for this line of code when it works if the sequence is switched.

The line of codes are : 1)if words[0] != "From" or len(words) < 1 :(line 9, left file, gives Traceback)

2)if len(words) < 1 or words[0] != "From" :(line 10, right file, works)

pic of the two files

I tried replacing the one on the left with the 'working' line which works. So I'm just curious why is there a need to be specific in the sequence.

Poii
  • 1
  • 1

2 Answers2

0

This happens because when you call: if len(words) < 1 or words[0] != "From"

The expression is evaluated in the order it appears, first len(words) < 1 then words[0] != "From". As the code is evaluating a or expression when the first is evaluated as true, the interpreter is not going to evaluate the second one, because it does not matter anything that comes will output true.

When you call if words[0] != "From" or len(words) < 1 the interpreter will evaluate the expression words[0] != "From" when the words is an empty list you are going to receive an Index Error, because the index 0 does not exist on your array.

By the way you could resume your expression to if not words or words[0] != "From"

Rubico
  • 374
  • 2
  • 12
0

In the first case, you're accessing the first item in the words list (words[0]), but if the list is empty then the index is out of bounds, which generates an error in Python.

In the seconds case (the line that works), you're first checking if the list is empty (has fewer than 1 item). In Python, the boolean "and" and "or" are short0circuit operators. This means if the condition before the "or" is true, it won't evaluate the condition after the "or". Therefore it doesn't try to access an out-of-bounds index.

Josh Segall
  • 4,183
  • 4
  • 31
  • 28