0

I expect below code to work properly, since first condition if false, but it throughs IndexError: string index out of range. What am I missing?

 a = False
 sample_strign = 'test'
 if (a == True) & (sample_strign[7] == 's'):
        print('foo')
user1700890
  • 7,144
  • 18
  • 87
  • 183

2 Answers2

6

& is a bit-wise operator. If you want the interpreter to "short-circuit" the logic, use the logical operator and.

if a and (sample_strign[7] == 's'):
Billy
  • 5,179
  • 2
  • 27
  • 53
1

sameple_strign doesn't have a 7th index which will raise an exception, you should use something like:

if a and len(sample_strign) > 7:
    if sample_strign[7] == 's':
        print('foo')
Mohd
  • 5,523
  • 7
  • 19
  • 30