Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python3 Program to Rotate bits of a number
Next article icon

Python Program to Reverse a Number

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a number and our task is to reverse its digits. For example, if the input is 12345 then the output should be 54321. In this article, we will explore various techniques for reversing a number in Python.

Using String Slicing

In this example, the Python code reverses a given number by converting it to a string, slicing it in reverse order and then converting it back to an integer. The original and reversed numbers are printed for the example case where the original number is 1234.

Python
n1 = 1234 rev_num = int(str(n1)[::-1])  print(n1) print(rev_num) 

Output
1234 4321 

Explanation:

  • number n1 is converted to a string and reversed using slicing ([::-1]).
  • reversed string is then converted back to an integer.

Table of Content

  • Using While Loop
  • Using For Loop
  • Using Recursion

Using While Loop

In this example, the Python code reverses a given number using a while loop. It prints both the original and reversed numbers. The example demonstrates reversing the number 6789.

Python
n1 = 6789 rev = 0  while n1 > 0:     digit = n1 % 10     rev = rev * 10 + digit     n1 //= 10  print(6789) print(rev) 

Output
6789 9876 

Explanation:

  • number n1 is processed by repeatedly extracting its last digit, appending it to rev, and then removing the last digit from n1 using the // operator.
  • The original number (6789) and the reversed number are printed

Using For Loop

In this example, the Python code reverses a given number by iterating through its digits using a for loop. It prints both the original and reversed numbers. The example demonstrates reversing the number 6789.

Python
n1 = 6789 rev = 0  for _ in str(n1):     digit = n1 % 10     rev = rev * 10 + digit     n1 //= 10  print(6789) print(rev) 

Output
6789 9876 

Explanation:

  • number n1 is processed by converting it to a string and using a for loop to extract each digit from the number.
  • The digits are added to rev to build the reversed number.
  • Finally, the original number (6789) and the reversed number are printed.

Using Recursion

In this example, in below code Python function `reverse_number` recursively reverses a given number by extracting the last digit and placing it at the appropriate position. The recursion continues until the original number is fully reversed. The example demonstrates reversing the number 987654.

Python
def reverse_number(n):     if n == 0:         return 0     else:         return (n % 10) * 10 ** (len(str(n)) - 1) + reverse_number(n // 10)   # Example num = 987654 orig_num = num rev_num = reverse_number(num) print(orig_num) print(rev_num) 

Output
987654 456789 


Next Article
Python3 Program to Rotate bits of a number
author
neeraj3304
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Python program to reverse a range in list
    Reversing a specific range within a list is a common task in Python programming that can be quite useful, when data needs to be rearranged. In this article, we will explore various approaches to reverse a given range within a list. We'll cover both simple and optimized methods. One of the simplest w
    4 min read
  • Python3 Program to Rotate bits of a number
    Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. In the left rotation, the bits that fall off at the left end are put back at the right end. In the right rotation, the bits that fall off at th
    3 min read
  • Python Program for Reverse of a Number Using Type Casting
    Reversing a number is a common problem-solving exercise in programming, often used to teach the basics of algorithms and data manipulation. In Python, reversing a number can be efficiently achieved using type casting. Example: Input: 12345Output: 54321Input: -12345Output: -54321Input: 123.45Output:
    4 min read
  • Python Program to Reverse Every Kth row in a Matrix
    We are given a matrix (a list of lists) and an integer K. Our task is to reverse every Kth row in the matrix. For example: Input : a = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4 Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]]Using reversed() and loopWe
    5 min read
  • Python Program to Subtract Two Binary Numbers
    We are given two binary numbers, num1 and num2 and we have to subtract these two binary numbers and return the result. In this article, we will see how we can subtract two binary numbers in Python. Examples: Input: a = "1110" , b = "0110"Output: "1000"Explanation: We can see that when "1110" is subt
    3 min read
  • Python Program to Find Cube of a Number
    We are given a number and our task is to find the cube of this number in Python. The cube of a number is calculated by multiplying the number by itself twice. For example, if the input is 3, then the output will be 3 * 3 * 3 = 27. In this article, we will learn different ways to find the cube of a n
    2 min read
  • Python program to find smallest number in a list
    In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python's built-in min() function. Using min()The min() function takes an iterable (like a list, typle etc.) and returns the smallest value. [GFGTABS]
    3 min read
  • How to Reverse a Dictionary in Python
    Reversing a dictionary typically means swapping the keys and values, where the keys become the values and the values become the keys. In this article, we will explore how to reverse a dictionary in Python using a variety of methods. Using Dictionary ComprehensionDictionary comprehension is a concise
    2 min read
  • Python program to Reverse a single line of a text file
    Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer scie
    2 min read
  • Python3 Program to Generate all rotations of a number
    Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: Input: n = 123 Output: 231 31
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences