Wednesday, 28 February 2024

Swapping 2 numbers doesn't involve making a new variable in python

Swapping

Description
You are given two integer variables,  x and y. You have to swap the values stored in x and y.

----------------------------------------------------------------------
Input:
Two numbers x and separated by a comma.

Output:
Print 5 lines. The first two lines will have values of variables shown before swapping, and the last two lines will have values of variables shown after swapping. The third line will be blank.


Ans:

#takes input in form of the string

in_string=12,15


#here extract the two numbers from the string

mylist = in_string.split(',')

x=int(mylist[0])

y=int(mylist[1])


#print x and y before swapping


print('x before swapping: {0}'.format(x))

print('y before swapping: {0}'.format(y))


#Writing your swapping code here

x = x + y 

y = x - y 

x = x - y 


print()

#print x and y after swapping

print('x after swapping: {0}'.format(x))

print('y after swapping: {0}'.format(y))



Output:

x before swapping: 12

y before swapping: 15


x after swapping: 15

y after swapping: 12


No comments:

Post a Comment