Different Methods in Python for Swapping Two Numbers without using third variableIn this tutorial, we will discuss different methods used for swapping two variables (n1 and n2) without using a third variable in Python programs. Example: Method 1: By using inbuilt methodThe inbuilt method can work with any data type values such as string, float, it. This method is very easy to use. Example: Output: Variables Value Before Swapping: Value of P: JavaTpoint Value of Q: Tutorial Variables Value After Swapping: Value of P: Tutorial Value of Q: JavaTpoint Method 2: By using Bitwise XOR operatorThe Bitwise XOR method only works with integers, and it works faster as it uses bit operation that is for same value result = 0 and for different value result = 1. Example: Output: Variables Value Before Swapping: Value of P: 5 Value of Q: 10 Variables Value After Swapping: Value of P: 10 Value of Q: 5 Method 3: By using Addition and Subtraction OperatorsThis method can be used only for numerical values. Example: Output: Variables Value Before Swapping: Value of P: 112 Value of Q: 211 Variables Value After Swapping: Value of P: 112 Value of Q: 211 Method 4: By using Multiplication and Division OperatorsThis method can be only used for numerical value except 0. Example: Output: Variables Value Before Swapping: Value of P: 11.2 Value of Q: 21.1 Variables Value After Swapping: Value of P: 21.1 Value of Q: 11.2 Method 5: By using both Bitwise operators and Arithmetic operatorsIn this method, we will use both bitwise operators and arithmetic operators. This method only works with integers and not with float types. Example: Output: Variables Value Before Swapping: Value of P: 112 Value of Q: 211 Variables Value After Swapping: Value of P: 211 Value of Q: 112 ConclusionIn this tutorial, we have discussed different methods used for swapping values of two variables without using the third variable. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263449.html