Reputation: 10077
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?
Upvotes: 4
Views: 748
Reputation: 309919
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")
Upvotes: 3
Reputation: 5087
if a == "" and b == "":
print "a and b are empty"
if a == "" or b == "":
print "a or b is empty"
Upvotes: 2
Reputation: 387657
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')
Upvotes: 6