Skip to main content

Write a programme to SWAP the variable values

Description

This Python program showcases a common programming task - swapping the values of variables. It sets initial values for x, y, and z, and then proceeds to swap their values using a temporary variable. The code provides a "Before Swapping" message to display the initial values and an "After Swapping" message to show the new values of these variables. It serves as a practical example of how to perform variable value swapping in a clear and understandable manner.

Code

program2a.py
x=5
y=8
z=3
print("Before Swapping")
print("Values of x and y and z:",x,y,z)
temp=x
x=y
y=z
z=temp
print ("After Swapping")
print ("Values of x and y and z:",x,y,z)

Explanation of above code

  • The provided Python code exemplifies the process of swapping values between three variables: x, y, and z.
  • Initially, specific values are assigned to these variables: x is initialized with 5, y with 8, and z with 3.
  • To execute the swapping operation, the code introduces a temporary variable named 'temp' to retain the initial value of x.
  • A specific sequence of reassignments to x, y, and z is followed meticulously to accomplish the variable value swapping.
  • The program commences by presenting a message, 'Before Swapping,' followed by displaying the original values of x, y, and z.
  • Upon completing the swapping process, it proceeds to print a message, 'After Swapping,' and unveils the new values of these variables.
  • Upon execution, this program effectively serves as a practical illustration of the concept of variable value swapping in Python, offering a hands-on demonstration of this fundamental programming technique.

Learn more

Reference