Python Program to Get Reverse of a Number codigence
Python Program to Get Reverse of a Number codigence
- Python Program to get Reverse of a Number using For Loop.
- Reverse Number in Python using While Loop.
- Reverse Number in Python using slicing.
Overview of Reverse Number in Python
Reverse of a number is the revese order of its digits.For Example reverse of 12345 id 54321.
Python Program to get Reverse Number using For Loop
- Define a function to get Reverse No.
- Let's have a function named 'reverse_num' and take the argument 'no' for number to get reverse of number.
- Now Inside the Function,
- copy the value of no into a temporary variable,say dup_no.
- Now initialize a variable,say 'rev_no' to zero.This will store the reverse of the number.
- Using for loop get the reverse of number.
- Call the function to get reverse of number and print the Final results.
#python program to reverse a num
#using for loop
def reverse_num(no: int):
dup_no = no #duplicating num
rev_no = 0
for i in range(len(str(no))):
digit = dup_no % 10
rev_no = rev_no*10 + digit
dup_no//=10
return rev_no
print(f"Reverse of 12345 = {reverse_num(12345)}")
Output
Reverse of 12345 = 54321
Python Program to get Reverse Number using While Loop
- Define a function to get Reverse No.
- Let's have a function named 'reverse_num' and take the argument 'no' for number to get reverse of number.
- Now Inside the Function,
- copy the value of no into a temporary variable,say dup_no.
- Now initialize a variable,say 'rev_no' to zero.This will store the reverse of the number.
- Using while loop get the reverse of number.
- Call the function to get reverse of number and print the Final results.
#using while loop
def reverse_num(no: int):
dup_no = no
rev_no = 0
while dup_no != 0:
digit = dup_no % 10
rev_no = rev_no*10 + digit
dup_no//=10
return rev_no
print(f"Reverse of 12345 = {reverse_num(12345)}")
Output
Reverse of 12345 = 54321
Python Program to get Reverse Number using slicing
- Define a function to get Reverse No.
- Let's have a function named 'reverse_num' and take the argument 'no' for number to get reverse of number.
- Now Inside the Function,
- copy the value of no into a temporary variable,say dup_no.
- Using slicing loop store the reverse of number into a variable, say rev_no.
- Call the function to get reverse of number and print the Final results.
#using slicing
def reverse_num(no: int):
rev_no = str(no)[::-1]
return rev_no
print(f"Reverse of 12345 = {reverse_num(12345)}")
Output
Reverse of 12345 = 54321
Conclusion
Python allows us to implement Reverse number programs quickly and effectively through its multiple features.
Post a Comment