Search code examples
pythonif-statementreturnlogicoperators

What does the ^ character do in logical operation


I'm practicing code on codingbat and came across this logic question:

Given a number n, return True if n is in the range 1..10, inclusive. Unless outside_mode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.

The solution is:

if n == 1 or n == 10:
    return True
  return (n in range(1,11)) ^ outside_mode

If one googles "python ^ symbol" or "what does the ^ symbol do python" Google returns answers regarding the "@" symbol and the modulo symbol. It is not easy to find what this symbol does. This question should therefor be reopened to provide better chances of an early-stage programmer finding these answers


Solution

  • ^ is the bitwise exclusive or (or XOR)

    >>> True ^ True
    False
    
    >>> True ^ False
    True
    
    >>> False ^ True
    True
    
    >>> False ^ False
    False