Python code to swap 2 number with or without third variable.

 Swapping two numbers in Python can be done in a variety of ways. Here are a few methods to swap two numbers, along with explanations:

1. Using a Temporary Variable

This is the traditional method of swapping two numbers using a temporary variable.

python

# Method 1: Using a temporary variable # Initial values a = 5 b = 10 # Print original values print("Before swapping:") print("a =", a) print("b =", b) # Swap using a temporary variable temp = a a = b b = temp # Print swapped values print("After swapping:") print("a =", a) print("b =", b)

2. method

Python allows for a more concise and elegant way to swap values using tuple unpacking.

python
# Method 2: Using tuple unpacking # Initial values a = 5 b = 10 # Print original values print("Before swapping:") print("a =", a) print("b =", b) # Swap using tuple unpacking a, b = b, a # Print swapped values print("After swapping:") print("a =", a) print("b =", b)

3. Using Arithmetic Operations

You can also swap two numbers using arithmetic operations. This method doesn’t require a temporary variable but involves some arithmetic.

python

# Method 3: Using arithmetic operations # Initial values a = 5 b = 10 # Print original values print("Before swapping:") print("a =", a) print("b =", b) # Swap using arithmetic operations a = a + b b = a - b a = a - b # Print swapped values print("After swapping:") print("a =", a) print("b =", b)


Explanation of Each Method

  • Temporary Variable: Simple and easy to understand; involves using an extra variable.
  • 2 method: Python-specific, concise, and elegant; no extra variable needed.
  • Arithmetic Operations: Uses basic arithmetic to swap values; be cautious with large numbers to avoid overflow..

Choose the method that best fits your needs and coding style.

Post a Comment

0 Comments