Python Program to Swap Two Variables Example
Development teams using “Python Program to Swap Two Variables Example” in client or internal work can use the relevant Monitask guide to document project effort and hand-offs, then assess the record against delivered functionality, tests and agreed outcomes.
Validate current syntax, security guidance and supported versions through Python.org before using the example in production.
Hello Friend,
Today, I am going learn you how to swap two variables in python program. We will talk about python program to swap two variables. I would like to share with you how to swap two variable in python.
In this article, I will show swap two variable using third variable in python. We will teach swapping of two numbers in python with temporary variable.
Here i will give you three example of swapping of two numbers in python program. So let's see the bellow example:
Example 1
swap.py
# Python program to swap two variables
x = 15
y = 25
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output :
The value of x after swapping: 25
The value of y after swapping: 15
Example 2
swap.py
# To take inputs from the user
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output :
Enter value of x: 5
Enter value of y: 10
The value of x after swapping: 10
The value of y after swapping: 5
Example 3 : Without Using Temporary Variable
swap.py
# To take inputs from the user
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# swap the values without temporary variable
x, y = y, x
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output :
Enter value of x: 55
Enter value of y: 60
The value of x after swapping: 60
The value of y after swapping: 55
Run python file:
python swap.py
It will help you....
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?