×

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 PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Difference between For Loop and While Loop in Python

What is the “For” loop? The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is...

3 minutes read.

Python History

Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. Python language is known for its features. Some features are given below: SimplisticFree and open...

4 minutes read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.