Python program to swap two variables

Created with Sketch.

Python program to swap two variables

Variable swapping:

In computer programming, swapping two variables specifies the mutual exchange of values of the variables. It is generally done by using a temporary variable.

For example:

  1. data_item x := 1
  2. data_item y := 0
  3. swap (x, y)

After swapping:

  1. data_item x := 0
  2. data_item y := 1

See this example:

  1. # Python swap program 
  2. x = input(‘Enter value of x: ‘)
  3. y = input(‘Enter value of y: ‘)
  4. # create a temporary variable and swap the values
  5. temp = x
  6. x = y
  7. y = temp
  8. print(‘The value of x after swapping: {}’.format(x))
  9. print(‘The value of y after swapping: {}’.format(y))

Output:

Python Basic Programs6

 

Leave a Reply

Your email address will not be published. Required fields are marked *