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:
Python Program to Convert Temperatures using Classes
Next article icon

Python Program for Reverse of a Number Using Type Casting

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 12345
Output: 54321

Input: -12345
Output: -54321

Input: 123.45
Output: 54.321

In this article, we are going to learn how to reverse a number using Type Casting in Python.

What is Type Casting in Python

The process of changing a variable's data type is called type casting. It is also referred to as type conversion. If you need to conduct actions that need specific data types, type casting in Python can help you change the data type of a variable. For instance, to execute arithmetic operations on a string of numbers, you may wish to convert it to an integer or a float.

Type casting — a basic programming concept — is widely applied in various contexts to guarantee that data is in the right format for processing. Variables can be converted between different data types using built-in type casting procedures in Python, such as int(), float(), str(), and so on.

Steps for Reversing a Number using Type Casting

Here is a step-by-step process for reversing a number using type casting in Python.

Typecast the Number to a String

The first step is to use the str() function to convert the integer/float number to a string. This function takes a number as a parameter. As a result, we can now handle the number like a string of characters.

str_num = str(num)

Reverse the String

To reverse the number's string representation, we use the String slicing method. The characters are then put in a new string in the opposite sequence.

rev_str = str_num[::-1]

Typecast String to Number

lastly, use the int() function to turn the reversed string back into an integer. By doing this, an integer is created from the inverted string of digits.

rev_num = int(rev_str)

Examples of Reversing a Number Using Type Casting

Now, let us see a few different examples to see how we can reverse a number using the type casting in Python.

Integer Value

In this example, we will take an integer value and then convert it to a string using the str() function. After reversing the string by the slicing method, we will convert the string back into an integer value using the int() function.

Python
# integer number to be reversed num = 12345  # convert the number to a string  # and reverse it using slicing reversed_number = int(str(num)[::-1])  # print the reversed number print("The reverse of", num, "is", reversed_number) 

Output:

The reverse of 12345 is 54321

Float Value

In this example, we will take a float point value and then convert it to a string using the str() function. After reversing the string by the slicing method, we will convert the string back into the float value using the float() function.

Python
# float number to be reversed num = 123.45  # convert the number to a string  # and reverse it using slicing reversed_number = float(str(num)[::-1])  # print the reversed number print("The reverse of", num, "is", reversed_number) 

Output:

The reverse of 123.45 is 54.321

Negative Integer Value

In this example, we will take a negative integer value and use a conditional statement to determine whether the input number, is positive or negative. Assign -1 to the variable sign if num is negative; else, assign 1.

Then convert the number to its absolute value using the typecasting function, which will eliminate the negative sign. Convert this absolute value to the string using the str() function.

After reversing the string by the slicing method, multiply the reversed number with the sign obtained previously and then convert the string back into an integer value using the int() function.

Python
# negative integer number to be reversed num = -12345  # Extract the sign of the number sign = -1 if num < 0 else 1  # Convert the absolute value of the number  # to a string and reverse it using slicing reversed_number = int(str(abs(num))[::-1]) * sign  # Print the reversed number print("The reverse of", num, "is", reversed_number) 

Output:

The reverse of -12345 is -54321

Conclusion

Reversing a number using type casting in Python is a straightforward process that combines the flexibility of string manipulation with the power of type conversion. This method not only simplifies the implementation but also provides an opportunity to understand and utilize typecasting effectively.


Next Article
Python Program to Convert Temperatures using Classes

S

saranyagudluri254
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Python Program to Reverse a Number
    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 SlicingIn this example, the Python code reverses a given number by conve
    3 min read
  • Python Program For Adding 1 To A Number Represented As Linked List
    Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) Recommended: Please solve it on "PRACTICE" first, before moving on to
    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 to Convert Temperatures using Classes
    Temperature conversion is a common task in various fields, and Python provides a versatile platform for creating programs to handle such conversions. In this article, we will explore how to create a temperature converter using classes in Python for four different conversions: Celsius to Fahrenheit,
    3 min read
  • Python program to convert Base 4 system to binary number
    Given a base 4 number N, the task is to write a python program to print its binary equivalent. Conversion Table: Examples: Input : N=11002233 Output : 101000010101111 Explanation : From that conversion table we changed 1 to 01, 2 to 10 ,3 to 11 ,0 to 00.Input : N=321321 Output: 111001111001Method 1:
    3 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
  • Python Program to Convert any Positive Real Number to Binary string
    Given any Real Number greater than or equal to zero that is passed in as float, print binary representation of entered real number. Examples: Input: 123.5 Output: 1 1 1 1 0 1 1 . 1 Input: 0.25 Output: .01 Mathematical Logic along with steps done in programming: Any real number is divided into two pa
    4 min read
  • Python program to sort digits of a number in ascending order
    Given an integer N, the task is to sort the digits in ascending order. Print the new number obtained after excluding leading zeroes. Examples: Input: N = 193202042Output: 1222349Explanation: Sorting all digits of the given number generates 001222349.Final number obtained after removal of leading 0s
    2 min read
  • Python Program For Printing Reverse Of A Linked List Without Actually Reversing
    Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorit
    2 min read
  • Python Program for Reversal algorithm for array rotation
    Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. In this article, we will explore the Reversal Algorithm for array rotation and implement it in Python. Example Input: arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output: arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array
    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