B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Swap Variables | LiveCodeProgramming

Python Swap Variables

Swapping means exchanging the values of two variables. Python provides different ways to swap values.

Swapping का मतलब दो variables की values को आपस में बदलना होता है। Python में यह कई तरीकों से किया जा सकता है।

Example 1: Swap using temp variable
a = 5
b = 10
temp = a
a = b
b = temp
print("a =", a)
print("b =", b)

Output:

a = 10
b = 5

Uses a third variable to swap values.

तीसरे variable से swapping की जाती है।

Example 2: Swap without using temp
a = 3
b = 7
a, b = b, a
print("a =", a)
print("b =", b)

Output:

a = 7
b = 3

Swaps using Python tuple unpacking.

Tuple unpacking के जरिये swap करता है।

Example 3: Swap using arithmetic operations
a = 4
b = 8
a = a + b
b = a - b
a = a - b
print("a =", a)
print("b =", b)

Output:

a = 8
b = 4

Swaps values using addition and subtraction.

Addition और subtraction से swapping करता है।

Example 4: Swap using user input
a = int(input("Enter first number: ") )
b = int(input("Enter second number: ") )
a, b = b, a
print("After swapping: a =", a)
print("b =", b)

Output:

Enter first number: 2
Enter second number: 9
After swapping: a = 9
b = 2

Takes user input and swaps.

User input लेकर values को swap करता है।