Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 399
Thsise Faek Avatar asked Mar 21 '15 08:03

Thsise Faek


1 Answers

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

like image 174
jeromej Avatar answered Nov 09 '22 16:11

jeromej