Search code examples
pythonif-statementlogical-operators

A basic question regarding or operator in python


I get confused why the message always pops up like 'Welcome xxx' no matter what a user types.

username = input('Please enter your username: ')

if username == 'admin' or 'Admin' or 'ADMIN':
    print(f'Welcome {username}')

Sorry I know it seems a silly question but hopefully it helps beginners like me understand or operator in python better.

Thank you for your help.


Solution

  • What is going on here is treating Python like it's a spoken language.

    What you intend with:

    if username == 'admin' or 'Admin' or 'ADMIN':
        # stuff
    

    Is to mean:

    if <condition>:
    

    The "condition" being if username is 'admin', 'Admin', or 'ADMIN'.

    But that's not how python works. Python reads

    if username == 'admin' or 'Admin' or 'ADMIN':
        # code
    

    as

    if <condition 1> or <condition 2> or <condition 3>: 
        # code
    

    --

    Condition 1: username == 'admin' is FALSE.

    --

    Condition 2: 'Admin' is TRUE. This is because 'Admin' is a string literal object, which exists, and is non-zero, not null, and not empty, and therefore true.

    This is like going

    myString = "any string"
    
    if myString:
        # code is executed because myString is not empty.
    

    But instead you're doing

    if 'my string': 
        # this code would run.
    

    --

    Condition 3: 'ADMIN' is TRUE, for the same reason Condition 2 is TRUE.

    --

    What you have going on here is that the if condition is always true, no matter was is typed. Because

    if username == 'admin' or 'Admin' or 'ADMIN':
        # code
    

    Evaluates to

    if FALSE or TRUE or TRUE:
        # code
    

    And, therefore, will always evaluate to true and print whatever is in the username variable, even if it's not 'admin'.