Write A Python Script To Get Three Numbers And Swap Them

Given three numbers as input to the Python program,  you should swap the three numbers  and interchange their values.

Let's use the Python standard swapping method to swap the  numbers and keep reading…

 

 

Write A Python Script To Get Three Numbers And Swap Them

 


Write A Python Script To Get Three Numbers And Swap Them

Let's take three integer variables a, b and c and ask the user to enter the three numbers Using the input function call and then convert them to an integer using type conversion.

a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
c = int(input("Enter Third Number: "))
print("Variables Before Swap")
print(f"First Number : {a} Second Number : {b} Third Number {c}")




Take three variables separated by comma in the programming and  set them to b, c, a as shown below. This will swap/ interchange the  integer values. Using the print function call  print the three variables a, b and c




a, b, c = b, c, a
print("Variables After Swap")

print(f"First Number : {a} Second Number : {b} Third Number {c}")






Python Code
======================
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
c = int(input("Enter Third Number: "))
print("Variables Before Swap")
print(f"First Number : {a} Second Number : {b} Third Number {c}")

a, b, c = b, c, a
print("Variables After Swap")

print(f"First Number : {a} Second Number : {b} Third Number {c}")





Output
==============
Enter First Number: 2
Enter Second Number: 22
Enter Third Number: 222

Variables Before Swap
First Number : 2 Second Number : 22 Third Number 222

Variables After Swap
First Number : 22 Second Number : 222 Third Number 2




Output
==============
Enter First Number: 1
Enter Second Number: 2
Enter Third Number: 3
Variables Before Swap
First Number : 1 Second Number : 2 Third Number 3
Variables After Swap
First Number : 2 Second Number : 3 Third Number 1




Conclusion
==================
Execute the above Python program by  providing three integers as input values,  also try replacing the Swag statement from

a, b, c = b, c, a
to
a, b, c = c, a, b

And note down the result after the execution.

Comment it down below if you have any suggestions to improve the above Python program.

Post a Comment

0 Comments