How to Reverse a number in Python?
In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most straightforward way to carry out this procedure on any user-provided input.
Mathematical reversal of numbers using simple logic
First, we will divide an integer by 10 to ensure that the remainder does not follow in reverse order.
Initial iteration:
num= 765
Remainder = num %10
Remainder = 765%10 = 5
Second iteration
Remainder = Num%10
Remainder = 74 %10 = 4
Example:
Python's slicing technique makes obtaining the original input number's reversed.
new_number = 65243
print(str(new_number)[::-1])
By employing the string-slicing technique, the inverted string can be obtained. The value of start:stop: step is zero. When you pass -1 as a step, the start point goes to the beginning and stops at the conclusion.
Output:
34256
In Python, we can reverse an input number in the following manners:
Using for loop to reverse a number in Python
- We may use this method to reverse a number by using a for loop and the characters from the back of the original string. The last character is added first, the second last, and so on, with the first character added last, creating a new string that is inverted.
- The input number can be read using the input() or raw input() methods. Next, ascertain whether the value entered is an integer. Now, verify that the supplied number is more than zero.
- Set the initial value of the variable "reverse" to "0."Find the leftover part of the supplied input number using the mod (%) operator. The reverse variable is multiplied by ten, and the remainder is added.
Example:
input_number = '5672'
result = ''
for m in range(len(input_number), 0, -1):
result += input_number[m-1]
print('The reverse number is =', result)
In this example, we declare a variable, give it an integer value, and then utilize the for loop and len() methods.
Output:
The reverse number is = 2765
In this demonstration, we learned how to use the for-loop technique to reverse a number in Python.
Python function to reverse an integer without a for loop
- The user must put the input and store the value in the variable n first. The while loop is run, and the modulus operator is used to find the number's last digit. After that, the next digit is preserved at position one, the following to last at position ten, and so on.
- To get rid of the last digit, divide the number by ten exactly as in the last step. This loop breaks when the number's value is 0, at which point the number is written in reverse.
Example:
new_number = int(input("Enter the value: "))
result = 0
while(new_number>0):
remainder = new_number % 10
result = (result * 10) + remainder
new_number = new_number//10
# Print the Result
print("Reverse number:”, result)
In this example, we will set the condition to divide by ten and display the result if the input number is less than 0.
Output:
Enter the value: 456
Reverse number: 6
Reverse number: 65
Reverse number: 654
This is how, without using the for loop technique, we can reverse a number in Python.
Using a function to reverse a number in Python
- In this example, we'll demonstrate how to reverse a number in Python using the reversed() method.
- Although nothing is truly reversed, the reversed() function returns an object that can loop through the parts in reverse order. The specified list can be traversed in reverse order with the help of an iterator provided by the reversed() method, but the list is altered.
- The Python reversed() method makes it simple to reverse an integer. The function's return value is a pointer that can iterate the string or list backward. The join() method of Python can then be used to get the inverted number from this iterator.
Example:
new_number = 54672
con_str = str(new_number)
#By applying the reversal technique
result = "".join(reversed(con_str))
#inverted number shown
print("Reversed Number is:",result)
We have initially defined the input number in the code below before converting it to a string. The transformed string was then assigned to it using the reversed() function. The reverse number of an original number will be displayed after this code has been executed.
Here is how the code was put into action.
Output:
Reversed Number is: 27645
We can reverse an integer using Python's reversed function in this manner.
Use a while loop to reverse a number in Python
- Here, we'll go through how to use Python's while loop to acquire an original integer's reverse number.
- We must first add the final digit since we will create a new variable to store the inverted number. In the while loop, we may multiply the integer by 10 to get the last digit. The answer to this will be revealed by the last digit.
Example:
new_number =7434
new_output = 0
while new_number != 0:
new_val = new_number % 10
new_output = new_output * 10 + new_val
new_number //= 10
print("Display the reversed Number: " + str(new_output))
Output:
Display the reversed Number: 4347
Use recursion to reverse a number in Python
- This method of number reversal is called recursion. The disadvantage of recursion is that it permits an infinite number of calls to the recursive function until the last index.
- In this simple case, which will be our starting point, the letters can then be appended to the resulting reversed string. The last index will be added first, followed by the next-to-last index, and so forth, with the addition of the first index coming last. Therefore, we can reverse the string by using the recursive method and including the letter.
Example:
new_num = 0
def reverse(new_val):
global new_num
if(new_val > 0):
Reminder = new_val %10
new_num = (new_num *10) + Reminder
reverse(new_val //10)
return new_num
new_val = int(input(" Enter the number : "))
new_num = reverse(new_val)
print(" The Result reverse number is:",new_num)
Output:
Enter the number: 5478
The Result reverse number is: 8745
Using a built-in function to reverse a number in Python
- Here, we'll go through how to use Python's built-in function to reverse a number.
- Built-in functions in Python are functions that have predefined functionality. The Python interpreter always has several functions accessible for use.
- The reversed() built-in function, available in Python, will be used in this example. It returns an iterator of a sequence that has been reversed.
Example:
Let's look at an example and see how the built-in function in Python may be used to reverse a number.
def new_number(m):
result = ''.join(reversed(m))
return result
new_val = input('Enter the value: ')
# Show the outcome
print('Reverse number is:', new_number(new_val))
Output:
Enter the value: 6751
The reverse number is: 1576
Using slicing to reverse a number in Python
- In this method, we'll use string-slicing techniques to reverse the number. The Python language's string-slicing feature will be used to first convert the number to a string, following which the string will be split up and added in reverse order. For a given integer input, the following operations will be carried out.
- The number format is changed to a string, and the number is then reversed by using string slicing.
- The string-slicing approach can be used in this method to reverse a number. Finding a substring of a string in Python is called slicing.
Example:
Let's look at an example and see how Python's slicing function may reverse a number.
new_num = 84596
str_val = str(new_num)
m = len(str_val )
result = str_val [m::-1]
#reversed number output
print("Reversed Number is:", result)
Output:
Reversed Number is: 69548
Python program to reverse number order
Example:
input_number = '6789'
result = ''
for m in range(len(input_number), 0, -1):
result += input_number[m-1]
print('The reverse number is =', result)
Output:
The reverse number is = 9876
We have learnt how to reverse the order of numbers in Python through this example.
Python program to reverse a number in a list
- In this method, we take advantage of the fact that Python lists have a reverse() method that flips the list's elements.
- Therefore, we simply add the digits of our number to the list, reverse them to get them in the reverse order, and then join them to get the final reversed number using Python's list() method.
- Use Python's join() method to combine a string with an iterable object. The strings of the iterable are concatenated to produce a new string. The iterable throws a Type Error exception if it contains any non-string values.
Example:
new_num = "8321"
# Put the input number into a list.
new_lis = list(new_num)
# Through the reverse() method
new_lis .reverse()
#changing a list to a number
new_num = ''.join(new_lis )
print ("Result of an input number is: "new_num)
Output:
Result of input number is: 1238
Python program to reverse a number and determine if it's a palindrome
- A palindrome is a word or group of numbers composed of letters that spell the same word when read both forward and backward. Python Palindrome allows for punctuation, symbols, letters, and spaces within the Palindrome words.
- A number can only be a palindrome if it stays the same when reversed. If the number does not equal the opposite of itself, it is not a palindrome.
Example:
new_val=input(("Enter the value:"))
new_reverse = int(str(new_val)[::-1])
if new_val == new_reverse:
print('It is Not Palindrome')
else:
print("It is Palindrome")
Output:
Enter the value: 123
It is Not Palindrome
Python reverse character
- In this section, we will go through how to reverse a character or string in Python.
- In this example, we'll make a slice that starts at the end of the string and moves backward.
- In this case, the slice symbol [::-1] signifies a one-step backward motion, beginning at position 0, and finishing at the end of the string.
Example:
new_char = "UK" [::-1]
print(new_char)
Output:
KU