-2

I'm checking length of parameters and if it equals a specific value then it should enter if. If not, it should enter into else.

print(len(sys.argv))
if (
    (len(sys.argv) == 9)
    & (sys.argv[8] == "framework")
):
    employeeId = userid + "frame"
    print("frame")
else:
    employeeId = userid

print("userid")

Now passed len(sys.argv) is 7 and "userid" should print but I got the error

list index out of range

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Shravya Vaggu
  • 41
  • 1
  • 6
  • 1
    `&` is bitwise and doesn't short circuit. You need `and`. See https://stackoverflow.com/questions/8556206/what-does-mean-in-python/42822783 – Peter Wood Mar 15 '21 at 20:02
  • You should make that the answer so she can accept it. – Tim Roberts Mar 15 '21 at 20:03
  • @TimRoberts I've voted to close the question as it's unclear, so I won't be posting an answer. It's unlikely to be helpful to others in future. – Peter Wood Mar 15 '21 at 20:04

2 Answers2

1

The logical "and" operator in Python is and, not &.

& is a bitwise operator which may work similarly for boolean values, but in contrast to and it always evaluates both arguments even if the first one is false.

Therefore if len(sys.argv) is 7 then sys.argv[8] is out of range.

With and, sys.argv[8] would not be evaluated because the condition len(argv) == 9 which you have rightfully put in place is false. This property of the and operator is called "short-circuiting".

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
-1

take a look at this:

(len(sys.args) == 9)
    & (sys.argv[8] == "framework")

you are using &, which is bitwise operator, and not a condition and

This result this:

1 & sys.argv[8] == "framework"

because the first == works, and the if couldn't determ if it should be true, it keep checking and running sys.argv[8], which in your case will be invalid

what you are searching for is and as:

len(sys.args) == 9 and sys.argv[8] == "framework"
Reznik
  • 2,663
  • 1
  • 11
  • 31