Thsise Faek
Thsise Faek

Reputation: 311

Python: Check second variable if first variable is True?

I have a script that checks bools through if statements and then executes code. What I am trying to do is make it so that:

if variable a is True, check if b is True and execute code
if variable a is False, execute the same code mentioned before

A simplified version of what I currently have is this:

if a:
    if b:
        print('foo')
else:
    print('foo')

Is there a better way to do this that doesn't require me to write print('foo') twice?

Upvotes: 5

Views: 5583

Answers (2)

kmonsoor
kmonsoor

Reputation: 8109

While JeromeJ's answer is correct, an alternative can be:

print("foo" if ((not a) or (a and b)) else '')

It will print a blank line if not printing "foo", though.

If you don't want that to happen, you could exploit it like this:

print("foo") if ((not a) or (a and b)) else ''

'' or anything else could be used as it will be thrown away in the nature.

Upvotes: 0

jeromej
jeromej

Reputation: 11588

if not a or (a and b):
    print('foo')

Let's talk this step by step: When is print('foo') executed?

  1. When a and b are both True.
  2. When else is executed, what is else? The opposite of the previous if so not a.

Finally you wish to display 'foo' in one case or the other.

EDIT: Alternatively, by simplifying the logic equation:

NOTE: You might want to avoid this unless you know what you are doing! Clarity is often way better than shortness. Trust my advice! I've been through there! ;)

if not a or b: 
   print('foo')

Because if not a is not True, then a must be True (the second part of or), so the a and b can be simplified in just b (because we do know as a fact that a is True in this situation, so a and b is the same as True and b so we can drop the first part safely).

Upvotes: 14

Related Questions