Home > Enterprise >  Python IF unexpected behavior when using OR
Python IF unexpected behavior when using OR

Time:02-03

I don't understand why the code below enters the IF statement.

#Cisco XR

print('*Read Channel before')
print(read_channel_password)

print(f'\nHostname: {hostname}')
print(f'Hostname upper: {hostname.upper()}')

if f':{hostname}#' or f':{hostname.upper()}#' in read_channel_password:
    print('\n*Read Channel after')
    print(read_channel_password)
    
    print("\nWhy are you here?")
    break

Console:

*Read Channel before

--- JUNOS 9.5R3.7 built 2009-10-28 16:48:40 UTC
{master}
user01@ed-ra1>

Hostname: ed-ra1
Hostname upper: ED-RA1

*Read Channel after

--- JUNOS 9.5R3.7 built 2009-10-28 16:48:40 UTC
{master}
user01@ed-ra1>

Why are you here?

When I change the IF to IF-ELIF instead of OR. It works normally. Am I missing something here?

CodePudding user response:

Both sides of or need a conditional so instead of:

if f':{hostname}#' or f':{hostname.upper()}#' in read_channel_password:

You need:

if f':{hostname}#' in read_channel_password or f':{hostname.upper()}#' in read_channel_password:

Your current code will always return True as long as f':{hostname}#' is not empty since non-empty strings are truthy.

  •  Tags:  
  • Related