Python: check the second variable if the first variable is True?

I have a script that checks bools through if statements and then executes the code. I try to 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:

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

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

+4
source share
2 answers
if not a or (a and b):
    print('foo')

Let's talk about it step by step: When is it done print('foo')?

  • When aand bare True.
  • When elseis it done, what is it else? The opposite of the previous ifso not a.

, 'foo' .

EDIT: , :

.. , , ! , . ! !;)

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

not a True, a True ( or), a and b b ( , a True, a and b True and b, ).

+13

JeromeJ , :

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

, "foo".

, , :

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

'' - , .

0

All Articles