Introduction to Reverse Number in Python
Reverse operation in python can be defined as a process of turning the order of the input assigned to a variable from back to front or front to back. This operation can be achieved by any kind of logic involving the conditional statements of python, such as for loop, while conditional statement, if condition, etc. There are multiple pre-defined methods in python which can be worked along with the conditional statements for creating reverse logical function, and they are list method, slice method, recursion method, etc. Reverse() method is the straightforward method for performing this operation for any kind of input provided by the user.
Logic for Reverse Number in Python
The below points briefly us about how to reverse a given number in python:
- The input number can be read by using input () or raw_input () method.
- Next, check whether the entered value is an integer or not.
- Now check whether a given integer is greater than 0 or not.
- Create a variable called reverse and initialize the variable value with 0.
- Now find the remainder for the given input number by using the mod (%) operator.
- Multiply the variable reverse with 10 and add the remainder value to it.
- Now floor (floor division is performing the division operation and resulting value provides lower integer to the value) divide the given input number with 10.
- The given input number will become 0 at some point.
- Now repeat the steps 5, 6, 7 until you get the input number is not greater than zero.
- In the last step, display the variable in reverse.
Reversing the Number Using different ways in Python
Below are the different ways in Python:
1. Using Slicing Method
Code:
def reverse_slicing(s):
return s[::-1]
my_number = '123456'
if __name__ == "__main__":
print('Reversing the given number using slicing =', reverse_slicing(my_number))
Execution Steps:
- Save the python code in your drive. (Here, we have used D drive for executing the programs)
- Now open the command prompt and locate your drive.
- Execute the program with the command as python program_name.py
- The python programs will be saved with .py extension.
Output:
Note: Follow the above steps for executing the python programs for reversing which are going to be discussed below.
2. Using For loop Method
Code:
def reverse_for_loop(s):
s1 = ''
for c in s:
s1 = c + s1
return s1
my_number = '123456'
if __name__ == "__main__":
print('Reversing the given number using for loop =', reverse_for_loop(my_number))
Output:
3. While Loop Method
Code:
def reverse_while_loop(s):
s1 = ''
length = len(s) - 1
while length >= 0:
s1 = s1 + s[length]
length = length - 1
return s1
my_number = '123456'
if __name__ == "__main__":
print('Reversing the given number using while loop =', reverse_while_loop(my_number))
Output:
4. Using Reversed Method
Code:
def reverse(string):
string = "".join(reversed(string))
return string
my_number = "123456"
print ("The given number is : ",end="")
print (my_number)
print ("Reversing the given number using reversed is : ",end="")
print (reverse(my_number))
Output:
5. Using user-entered number and then reversing it
Code:
My_Number = int(input("Please provide the number to be reversed: "))
Reverse_Number = 0
while(My_Number > 0):
Reminder = My_Number %10
Reverse_Number = (Reverse_Number *10) + Reminder
My_Number = My_Number //10
print("Reverse of the provided number is = %d" %Reverse_Number)
Output:
6. Two-Digit Reverse Method
Code:
My_Number = int(input("Please provide the number to be reversed: "))
Reverse_Number = 0
temp = Reverse_Number
Reminder = 1
for i in range (Reminder+1):
Reminder = My_Number %10
Reverse_Number = (Reverse_Number *10) + Reminder
My_Number = My_Number //10
print("Reverse of the provided number is = %d" %Reverse_Number)
Output:
7. Three-Digit Reverse Method
Code:
My_Number = int(input("Please provide the number to be reversed: "))
Reverse_Number = 0
temp = Reverse_Number
Reminder = 1
for i in range (Reminder+2):
Reminder = My_Number %10
Reverse_Number = (Reverse_Number *10) + Reminder
My_Number = My_Number //10
print("Reverse of the provided number is = %d" %Reverse_Number)
Output:
8. Without the Recursion Method
Code:
my_num=str(input("Enter the number to be reversed: "))
print("Reverse of the given number is: ")
print(my_num[::-1])
Output:
9. With Recursion Method
Code:
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
my_number = "123456789"
print ("The given number is : ",end="")
print (my_number)
print ("Reversing the given number using recursion is : ",end="")
print (reverse(my_number))
Output:
10. Using Function Method
Code:
def rev_number(My_Number) :
reverse_num = 0
while(My_Number) :
Reminder = My_Number % 10
reverse_num = reverse_num* 10 + Reminder
My_Number //= 10
return reverse_num
if __name__ == "__main__" :
My_Number = int(input('Please provide the number to be reversed:: '))
print('Reverse of the provided number is: ', rev_number(My_Number))
Output:
11. Using List Method
Code:
number = "123456789"
print ("The given number is : " + number)
#converting number into list
list1 = list(number)
#applying reverse method of list
list1.reverse()
#converting list into number
number = ''.join(list1)
print ("Reverse of the provided number is : " + number)
Output:
12. Using the Stack Method
Code:
def create_stack():
#creating a list as stack and return it
stack = []
return stack
def push(stack,element):
#adding new element to list
stack.append(element)
def pop(stack):
#deleting the last element from the list
if len(stack) == 0:
return
return stack.pop()
def reverse(number):
#reversing the number by using stack's functions
num = len(number)
#creating empty list (stack)
stack = create_stack()
#inserting number into list
for i in range(0,num):
push(stack,number[i])
number = ""
#getting last element of the stack list
for i in range(0,num):
number = number + pop(stack)
return number
number1 = "123456789"
number2 = reverse(number1)
print ("The given number is : " + number1)
print ("Reverse of the given number is : " + number2)
Output:
Conclusion
So far in this tutorial, we have learned to find the reverse number of a given number in python. This program runs only once, i.e. it asks the user to enter a number, find the reverse value, print and exit. We can also insert it into an infinite loop for continuous reading of a new number from the user. Put it in an infinite loop and check what’s going on.
Recommended Articles
We hope that this EDUCBA information on “Reverse Number in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
- Random Number Generator in Python
- Math Functions in Python
- Python Sets
- Python Features
In this tutorial, you’ll learn how to use Python to reverse a number. While this is similar to learning how to reverse a string in Python, which you can learn about here, reversing a number allows us to use math to reverse our number. You’ll learn how to use a Python while loop, string indexing, and how to create an easy-to-read function to reverse a number in Python.
The Quick Answer: Use a Python While Loop
Reverse a Python Number Using a While Loop
Python makes it easy to reverse a number by using a while loop. We can use a Python while loop with the help of both floor division and the modulus %
operator.
Let’s take a look at an example to see how this works and then dive into why this works:
# How to Reverse a Number with a While Loop
number = 67890
reversed_number = 0
while number != 0:
digit = number % 10
reversed_number = reversed_number * 10 + digit
number //= 10
print(reversed_number)
# Returns: 9876
Let’s break down what we do here:
- We instantiate two variables,
number
andreversed_number
. The first stores our original number and the second is given the value of0
- While our
number
variable is equal to anything by0
, we repeat our actions below - We instantiate
digit
, and assign it the modulus (remainder) of our number divided by 10 - We multiply our reversed number by 10 and add our digit
- Finally, we return the floored result of our number divided by 10 (this essentially removes the number on the right)
- This process is repeated until our original number is equal to zero
It’s important to note, this approach only works for integers and will not work for floats.
In the next section, you’ll learn how to use Python string indexing to reverse a number.
Reverse a Python Number Using String Indexing
Another way that we can reverse a number is to use string indexing. One of the benefits of this approach is that this approach will work with both integers and floats.
In order to make this work, we first turn the number into a string, reverse it, and turn it back into a number. Since we’ll need to convert it back to its original type, we need to first check the numbers type.
Let’s take a look at how we can accomplish this in Python:
# How to Reverse a Number with String Indexing
number = 67890.123
reversed_number_string = str(number)[::-1]
if type(number) == float:
reversed_number = float(reversed_number_string)
elif type(number) == int:
reversed_number = int(reversed_number_string)
print(reversed_number)
# Returns 321.09876
Python indexing allows us to iterate over an iterable object, such as a string. The third parameter is optional, but represents the step counter, meaning how to traverse an item. By default, the value is 1
, which means it goes from the first to the last. By using the value of -1
, we tell Python to generate a new string in its reverse.
We use type checking in order to determine what type of number to return back to.
In the next section, you’ll learn how to create a custom function that makes the code easier to follow and understand.
Reverse a Python Number Using a Custom Function
In this section, you’ll learn how to turn what you learned in the section above into an easy-to-read function. While the code may seem intuitive as we write it, our future readers may not agree. Because of this, we can turn our code into a function that makes it clear what our code is hoping to accomplish.
Let’s take a look at how we can accomplish this in Python:
def reverse_number(number):
"""Reverses a number (either float or int) and returns the appropriate type.
Args:
number (int|float): the number to reverse
Returns:
int|float: the reversed number
"""
if type(number) == float:
return float(str(number)[::-1])
elif type(number) == int:
return int(str(number)[::-1])
else:
print('Not an integer or float')
print(reverse_number(12345.43))
print(reverse_number(456))
# Returns:
# 34.54321
# 654
Our function accepts a single parameter, a number. The function first checks what the type is. If the type is either float
or int
, it reverses the number and returns it back to the same type. If the type is anything else, the function prints out that the type is neither a float nor an int.
Conclusion
In this post, you learned how to reverse a number using both math and string indexing. You also learned how to convert the string indexing method to a function that will make it clear to readers of your code what your code is doing.
If you want to learn more about string indexing in Python, check out the official documentation for strings here.
Additional Resources
To learn more about related topics, check out the resources below:
- Python: Reverse a String (6 Easy Ways)
- How to Reverse a Python List (6 Ways)
- Python range(): A Complete Guide (w/ Examples)
Перевернуть число
Вводится целое число. Вывести число, обратное введенному по порядку составляющих его цифр. Например, введено 3425, надо вывести 5243.
Решение задачи на языке программирования Python
Алгоритм:
- Найдем остаток от деления на 10 исходного (первого) числа. Тем самым получим последнюю его цифру. Запомним ее.
- Присвоим эту цифру новому (второму) числу-«перевертышу».
- Разделим нацело на 10 первое число. Тем самым избавимся от последней цифры в нем.
- Снова найдем остаток от деления на 10 того, что осталось от первого числа. Запомним цифру-остаток.
- Разделим нацело на 10 первое число. Избавимся от текущей последней цифры в нем.
- Умножим на 10 второе число. Тем самым увеличим его разрядность до двух и сдвинем первую цифру в более старший разряд.
- Добавим к полученному второму числу запомненную ранее цифру из первого числа.
- Будем повторять действия п. 4-7 пока первое число не уменьшится до нуля, т. е. пока не избавимся от всех его разрядов.
n1 = int(input("Введите целое число: ")) # Последнюю цифру первого числа переносим во второе digit = n1 % 10 n2 = digit # Избавляемся от последней цифры первого числа n1 = n1 // 10 while n1 > 0: # находим остаток - последнюю цифру digit = n1 % 10 # делим нацело - удаляем последнюю цифру n1 = n1 // 10 # увеличиваем разрядность второго числа n2 = n2 * 10 # добавляем очередную цифру n2 = n2 + digit print('"Обратное" ему число:', n2)
Примеры выполнения кода:
Введите целое число: 32809 "Обратное" ему число: 90823
Введите целое число: 78290 "Обратное" ему число: 9287
На самом деле мы можем не добавлять последнюю цифру первого числа во второе до цикла. Если присвоить n2 ноль, то в цикле при выполнении выражения n2 = n2 * 10
не будет происходить сдвига разряда, так как при умножении на 0 получается 0. И первая цифра будет добавляться в разряд единиц.
n1 = int(input("Введите целое число: ")) n2 = 0 while n1 > 0: digit = n1 % 10 n1 = n1 // 10 n2 = n2 * 10 n2 = n2 + digit print('"Обратное" ему число:', n2)
Приведенный алгоритм решения математический и соответствует задаче, если условие, что надо обрабатывать именно число, является строгим.
Однако средства Python позволяют решить подобную задачу более практично. Так у списков есть метод reverse
, позволяющий изменять порядок элементов на обратный. Мы можем получить из исходной строки список символов, выполнить его реверс, после чего с помощью строкового метода join
опять собрать в единую строку.
n1 = input("Введите целое число: ") n_list = list(n1) n_list.reverse() n2 = "".join(n_list) print('"Обратное" ему число:', n2)
Также можно воспользоваться взятием среза из исходной строки с первого до последнего символа с обратным шагом:
n1 = input("Введите целое число: ") n2 = n1[::-1] print('"Обратное" ему число:', n2)
Два последних варианта решения задачи — это способы переворота строки, а не числа как такового. Если объект, который надо переверуть, изначально имеет числовой тип данных (например, генерируется функцией randint()
), то его придется преобразовывать в строковый тип данных с помощью функции str()
. И если на выходе мы должны получить опять же число, то надо будет строку превращать обратно в число с помощью функции int()
.
from random import randint print("Исходное число:", end=' ') n1 = randint(5000, 1000000) print(n1) n1 = str(n1) n2 = n1[::-1] n2 = int(n2) print('"Обратное" ему число:', n2)
Пример выполнения:
Исходное число: 970334 "Обратное" ему число: 433079
Больше задач в PDF
Published on Sep 24,2019 66.8K Views
7 / 11 Blog from Python Programs
Python is an interpreted, high-level, general-purpose programming language with different applications. To learn the fundamental concepts of Python, there are some standard programs which would give you a brief understanding of all the concepts practically. Reverse a number in Python is one of these programs which gives the learner a deep understanding of loops and arithmetic operators. This blog will help you understand and implement the ways to reverse a number. It will cover the following topics –
- How to reverse a number in Python?
- Python program to reverse a number
- Using loops
- Using recursion
How to reverse a number in Python?
It’s simple! You can write a Python program which takes input number and reverse the same. The value of an integer is stored in a variable which is checked using a condition and then each digit of the number is stored in another variable, which will print the reversed number. Numbers can be reversed in Python using different methods, let us take a look at the Python program to implement the same.
Python program to reverse a number
There are two ways to reverse a number in Python programming language –
- Using a Loop
- Using Recursion
Reverse a Number using Loop
# Get the number from user manually num = int(input("Enter your favourite number: ")) # Initiate value to null test_num = 0 # Check using while loop while(num>0): #Logic remainder = num % 10 test_num = (test_num * 10) + remainder num = num//10 # Display the result print("The reverse number is : {}".format(test_num))
Output:
Program Explanation
User value: Number = 123456 and Reverse = 0
First Iteration
Reminder = Number %10
Reminder = 123456%10 = 6
Reverse = Reverse *10 + Reminder
Reverse = 0 * 10 + 6 = 0 + 6 = 6
Number = Number //10
Number = 123456 //10 = 12345
Second Iteration
From the first Iteration the values of both Number and Reverse have been changed as: Number = 12345 and Reverse = 6
Reminder = Number % 10
Reminder = 12345 % 10 = 5
Reverse = Reverse *10+ Reminder = 6 * 10 + 5
Reverse = 60 + 5 = 65
Number = Number //10 = 12345 //10
Number = 1234
Third Iteration
From the Second Iteration, the values of both Number and Reverse have been changed as: Number = 1234 and Reverse = 65
Reminder = Number %10
Reminder = 1234%10 = 4
Reverse = Reverse *10+ Reminder = 65 * 10 + 4
Reverse = 650 + 4 = 654
Number = Number //10 = 1234//10
Number = 123
Fourth Iteration
From the Second Iteration the values of both Number and Reverse have been changed as: Number = 123 and Reverse = 654
Reminder = Number %10
Reminder = 123 %10 = 3
Reverse = Reverse *10+ Reminder = 654 * 10 + 3
Reverse = 6540 + 3 = 6543
Number = Number //10 = 123//10
Number = 12
Fifth iteration
From the Second Iteration the values of both Number and Reverse have been changed as: Number = 12 and Reverse = 6543
Reminder = Number %10
Reminder = 12 %10 = 2
Reverse = Reverse *10+ Reminder = 6543 * 10 + 2
Reverse = 65430 + 2 = 65432
Number = Number //10 = 12//10
Number = 1
Sixth iteration
From the Second Iteration, the values of both Number and Reverse have been changed as, Number = 1 and Reverse = 65432
Reminder = Number %10
Reminder = 1 %10 = 1
Reverse = Reverse *10+ Reminder = 65432 * 10 + 1
Reverse = 654320 + 1 = 654321
Number ended:
Reverse a Number using Recursion
# Python Program to Reverse a Number using Recursion Num = int(input("Please Enter any Number: ")) Result = 0 def Result_Int(Num): global Result if(Num > 0): Reminder = Num %10 Result = (Result *10) + Reminder Result_Int(Num //10) return Result Result = Result_Int(Num) print("n Reverse of entered number is = %d" %Result)
Output:
With this, we come to an end of this blog on “Reverse a Number in Python”. I hope it added value to your knowledge of Python programming.
To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access. Got a question for us? Mention them in the comments section of “Reverse a Number in Python” and we will get back to you.
Recommended videos for you
Python Programming – Learn Python Programming From Scratch
Watch Now
Python List, Tuple, String, Set And Dictonary – Python Sequences
Watch Now
Web Scraping And Analytics With Python
Watch Now
Introduction to Business Analytics with R
Watch Now
3 Scenarios Where Predictive Analytics is a Must
Watch Now
Data Science : Make Smarter Business Decisions
Watch Now
Python Classes – Python Programming Tutorial
Watch Now
Android Development : Using Android 5.0 Lollipop
Watch Now
Python Loops – While, For and Nested Loops in Python Programming
Watch Now
Python Numpy Tutorial – Arrays In Python
Watch Now
Know The Science Behind Product Recommendation With R Programming
Watch Now
Sentiment Analysis In Retail Domain
Watch Now
Application of Clustering in Data Science Using Real-Time Examples
Watch Now
Business Analytics Decision Tree in R
Watch Now
Mastering Python : An Excellent tool for Web Scraping and Data Analysis
Watch Now
Recommended blogs for you
How To Implement Expert System in Artificial Intelligence?
Read Article
What is Data Analytics? Introduction to Data Analysis
Read Article
Cluster Analysis Steps in Business Analytics with R
Read Article
Data Analyst Roles and Responsibilities : All You Need to Know
Read Article
Top 10 Applications of Machine Learning : Machine Learning Applications in Daily Life
Read Article
What is Socket Programming in Python and how to master it?
Read Article
Tkinter Tutorial For Beginners | GUI Programming Using Tkinter In Python
Read Article
Introduction To Markov Chains With Examples – Markov Chains With Python
Read Article
How To Best Utilize Python CGI In Day To Day Coding?
Read Article
Object Detection Tutorial in TensorFlow: Real-Time Object Detection
Read Article
I’m creating a python script which prints out the whole song of ’99 bottles of beer’, but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall n")
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.