×

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

Related Topics

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python Num2words

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

Mrcnn Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.