Take Tuition from the Best Tutors
Search in
Write a program to swap values of two variables with and without using third variable.
I assume you know Python 3, so I'll answer using that, similar can be done in other languages.
1) #suppose you want to switch values of a and b
temp = a #we create a temp variable which will store the value of a
a = b; b = temp
#Now, if we hadn't created temp variable then b would take the value of a but mind that a has a value of b, so b will take the value of a which is not what you want.
2) There is another way and that is using tuples it's most easy you
don't need to make any 3rd variable. it's simply:
a,b = b, a #you can add parenthesis if you want. that's it you've swapped the values.
Before swap a=10 b=20 After swap a=20 b=10
read less
View 246 more Answers
Related Questions
Now ask question in any of the 1000+ Categories, and get Answers from Tutors and Trainers on UrbanPro.com
Ask a QuestionRecommended Articles
How To Choose The Right School For Children?
Quality education does not only help children to get a successful career and life, but it also hugely contributes to society. The formal education of every child starts from school. Although there are numerous schools, parents find it challenging to choose the right one that would fit their child. It is difficult for them...
6 Exam Hall Tips To Follow, For Every Good Student
Appearing for exams could be stressful for students. Even though they might have prepared well, they could suffer from anxiety, tension etc. These are not good for their health and mind. However, following a few exam preparation tips can save them from all these and help them to score good marks. Let’s find out all...
Science, Arts Or Commerce - Which One To Go For?
Once over with the tenth board exams, a heavy percentage of students remain confused between the three academic streams they have to choose from - science, arts or commerce. Some are confident enough to take a call on this much in advance. But there is no worry if as a student you take time to make choice between - science,...
Top Benefits of e-Learning
With the current trend of the world going digital, electronic renaissance is a new movement that is welcomed by the new generation as it helps makes the lives of millions of people easier and convenient. Along with this rapidly changing movement and gaining popularity of Internet, e-Learning is a new tool that emerging...
Looking for Tuition ?
Learn from the Best Tutors on UrbanPro
Are you a Tutor or Training Institute?
Join UrbanPro Today to find students near youThe best tutors for Tuition Classes are on UrbanPro
The best Tutors for Tuition Classes are on UrbanPro