user1700890
user1700890

Reputation: 7742

Python conditional evaluation

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')

Upvotes: 0

Views: 141

Answers (2)

Mohd
Mohd

Reputation: 5613

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')

Upvotes: 1

Billy
Billy

Reputation: 5609

& 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'):

Upvotes: 6

Related Questions