0

I'm trying to do something like this:

if (a == ("A" or "U")):
 do something

but it only tests against "A" when I introduce the input in the console

but it works if I do this:

if (a == "A" or a == "U")):
 do something

is it possible to achieve the second with a simpler line like the first one? thanks!

ToBeFrank
  • 53
  • 4

3 Answers3

1

Use in: This will be simpler

if a in ('A', 'U'):
    #do something 

Understanding your code.

if (a == ("A" or "U")):
   # do something

Python checks for "A" or "U" which "A" is return because of how truthfulness works. If the first is true, then the or is not evaluated. Since only empty string is False, the first none empty string will be selected and there your code is equivalent to:

if (a == "A"):
   # do something
Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57
1

You can't check both the conditions using (a == ("A" or "U")) because when you execute "A" or "U" in python interpreter you will get "A" (the first truthy value) similarly when you execute "A" and "U" you will get "U" (the last truthy value).

If you want simplified expression, you can use,

if a in ("A", "U"):
    # TODO: perform a task
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
0

It's not related to python. You can't further simplify the 2nd equation.

a == "A" is one boolean -> x a == "U" is one boolean -> y

x || y -> simplified version.

Also, you can't apply distributive law to equality Operators(==, <, >).

You can use the membership operator in check achieve above.

if a in ["A", "U"]:
  do_something()
thuva4
  • 1,185
  • 8
  • 13