Friday, 17 June 2016

Swap Values-Python

It's a very well known program given to the beginners, 'swap values of two variables'. In our first introductory programming course (structured programming in C) we solved it in different ways. Most of us used another temporary variable. Some of us did some math tricks. I remember that when i was beginner in programming of C i wrote the following code:

int a, b;
scanf("%d %d", &a, &b);
printf("%d %d\n", b, a);

And it made all other laugh :-D

Here is the best way of doing swapping in python. Try the following code:
a, b = 2,3
print a, b
a, b = b, a
print a, b

- Enjoy. :) 

No comments:

Post a Comment