Computer Science, asked by chhanhima8580, 1 year ago

What's the fastest way to swap the values bound to two variables? Python?

Answers

Answered by atrs7391
0

a = input('Enter First Value: ')

b = input('Enter Second Value: ')

print("Value of a before swapping: ", a)

print("Value of b before swapping: ", b)

c = a

a = b

b = c

print("Value of a after swapping: ", a)

print("Value of b after swapping: ", b)

Answered by Oreki
2

\textsf{\large \textbf{Explanation}}\\\textsf{\hspace{1em} Assuming the variables to be \textbf{a} and \textbf{b},}\\\textsf{\hspace{2em} So, the shortest way to swap values of two variable would be, }\\\texttt{\hspace{3em} a, b = b, a}

\textsf{\large \textbf{For Example - }}\\\texttt{\hspace{1em} a = 10}\\\texttt{\hspace{1em} b = 20}\\\texttt{\hspace{1em} print(f`a - \{a\}, b - \{b\}') \# a = 10, b = 20}\\\texttt{\hspace{1em} a, b = b, a}\\\texttt{\hspace{1em} print(f`a - \{a\}, b - \{b\}') \# a = 20, b = 10}\\

Similar questions