W3docs

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

You can use the ^ operator to get the logical XOR of two variables in Python.

You can use the ^ operator to get the XOR of two variables in Python. It performs a bitwise XOR on integers and a logical XOR on boolean values. Here is an example:

Get the XOR of two variables in Python

a = 5
b = 3
result = a ^ b
print(result)  # Bitwise XOR: 6

x = True
y = False
print(x ^ y)   # Logical XOR: True

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

For boolean values, ^ evaluates to True only when the operands differ, matching the standard logical XOR truth table.