4

I would like to print a message if either a or b is empty.

This was my attempt

a = ""
b = "string"

if (a or b) == "":
    print "Either a or b is empty"

But only when both variables contain an empty string does the message print.

How do I execute the print statement only when either a or b is an empty string?

0

5 Answers 5

6

The more explicit solution would be this:

if a == '' or b == '':
    print('Either a or b is empty')

In this case you could also check for containment within a tuple:

if '' in (a, b):
    print('Either a or b is empty')
Sign up to request clarification or add additional context in comments.

1 Comment

The second one is inefficient because a tuple needs to be created then a search performed in it.
4
if not (a and b):
    print "Either a or b is empty"

Comments

3

You could just do:

if ((not a) or (not b)):
   print ("either a or b is empty")

Since bool('') is False.

Of course, this is equivalent to:

if not (a and b):
   print ("either a or b is empty")

Note that if you want to check if both are empty, you can use operator chaining:

if a == b == '':
   print ("both a and b are empty")

Comments

2
if a == "" and b == "":
    print "a and b are empty"
if a == "" or b == "":
    print "a or b is empty"

Comments

1

Or you can use:

if not any([a, b]):
    print "a and/or b is empty"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.