0

Python XOR operator

Hello! Can you please advice some real use cases of XOR (^) operator in python? Would be grateful if you could mention real problems where it can be applied.

24th Jul 2022, 6:33 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
4 Answers
+ 6
Hi Ruslan Guliyev ! XOR is used as an bitewise operator. Bitewise operators can be uesed when you want get a special output of two inputed values that is either high or low, ones or zeros, true or false. For XOR, the exclusive OR, both input values must be different to get the output true, otherwise false; you really have to choose between two things, but not both! So in real world it is used in programming or when you are working with electronic circuts. Take a look this video. It explains how XOR can be used as a logical gate, among the other logical operators: https://youtu.be/lXWpWNKwYbo And here an explaination in text about how bitwise operators works in Python: https://realpython.com/python-bitwise-operators/#why-use-binary
24th Jul 2022, 7:27 AM
Per Bratthammar
Per Bratthammar - avatar
+ 3
Not only in Python but in general, I use XOR frequently as a flip flop to toggle between two values without using an if statement. Example, a Boolean flag that holds alternating 0 or 1: flag ^= 1 #toggle to its opposite value A bit flipper - change case of a letter by toggling bit 5: letter ^= 32 # make a -> A, or A -> a Encoding/Encryption This is a bigger topic than I will address here, but XOR provides a tricky way to store two values at once in a single storage space: a = 6^5 # (equals 3) print(a^5, a^6) #Output: 6 5 I believe there are always other means to do the same thing as XOR, so it is not compelling to use it. In Boolean logic it is the same relation as !=.
24th Jul 2022, 8:21 AM
Brian
Brian - avatar
+ 2
Let's Take the example, we have an Input form: Player: XXOXXOX Enemy:XOXOXXO We've a swordsman turnement X-marks every Round where a swordsman hits his enemy. When both have an X means it's a Draw and we just want the Points where either the Player or enemy won, also for Input: XXXXOXOO XOXOXOXX Would we give out the Points 3:3.
24th Jul 2022, 7:32 AM
Felix Alcor
Felix Alcor - avatar
+ 1
Thank you very much for your answers and contribution!
24th Jul 2022, 12:21 PM
Ruslan Guliyev
Ruslan Guliyev - avatar