-1

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.

wr858585
  • 3
  • 2
  • 1
    The `if` condition doesn't work as you think. The correct usage is: `if username == 'admin' or username=='Admin' or username=='ADMIN'`. In Python strings are falsible, therefore it interprets it seperately as `if 'Admin'` which equates to `True` – Ahmet Feb 14 '20 at 09:15

2 Answers2

0

You want to go for:

if username == 'admin' or username == 'Admin' or username =='ADMIN':
Thomas Schillaci
  • 2,348
  • 1
  • 7
  • 19
0

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

NonCreature0714
  • 5,744
  • 10
  • 30
  • 52