Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the logical xor of two variables in Python?

How do you get the logical xor of two variables in Python?

For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):

str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2):     print "ok" else:     print "bad" 

The ^ operator seems to be bitwise, and not defined on all objects:

>>> 1 ^ 1 0 >>> 2 ^ 1 3 >>> "abc" ^ "" Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ^: 'str' and 'str' 
like image 911
Zach Hirsch Avatar asked Jan 11 '09 12:01

Zach Hirsch


People also ask

How do you get XOR 2 numbers in Python?

The Bitwise XOR sets the input bits to 1 if either, but not both, of the analogous bits in the two operands is 1. Use the XOR operator ^ between two values to perform bitwise “exclusive or” on their binary representations. For example, when used between two integers, the XOR operator returns an integer.

Is there a logical XOR?

The logical XOR operator is not present in C++ because it is simply an equivalent, not equal to operator with Boolean values. So a general syntax would be: A and B are Boolean values. If we look at the truth table of XOR , we know that XOR is nothing but an inequality checker for boolean values.

What is XOR logical operator?

Exclusive or (XOR, EOR or EXOR) is a logical operator which results true when either of the operands are true (one is true and the other one is false) but both are not true and both are not false. In logical condition making, the simple "or" is a bit ambiguous when both operands are true.


1 Answers

If you're already normalizing the inputs to booleans, then != is xor.

bool(a) != bool(b) 
like image 78
A. Coady Avatar answered Sep 29 '22 12:09

A. Coady