Python Program to Reverse a Number

Introduction

Reversing a number is a common task in programming, where the digits of the number are flipped in reverse order. This tutorial will guide you through creating a Python program that takes a number as input and outputs its reverse.

Example:

  • Input: 1234

  • Output: 4321

  • Input: -5678

  • Output: -8765

Problem Statement

Create a Python program that:

  • Takes a number as input.
  • Reverses the digits of the number.
  • Displays the reversed number.

Solution Steps

  1. Take Input from the User: Use the input() function to get a number from the user.
  2. Convert Input to String: Convert the input number to a string to manipulate its digits.
  3. Reverse the String: Use slicing to reverse the string.
  4. Convert the Reversed String Back to an Integer: Convert the reversed string back to an integer.
  5. Display the Result: Use the print() function to display the reversed number.

Python Program

# Python Program to Reverse a Number
# Author: https://www.rameshfadatare.com/

# Step 1: Take input from the user
num = input("Enter a number: ")

# Step 2: Reverse the string using slicing
if num[0] == '-':
    # If the number is negative, keep the negative sign at the start
    reversed_num = '-' + num[:0:-1]
else:
    reversed_num = num[::-1]

# Step 3: Convert the reversed string back to an integer
reversed_num = int(reversed_num)

# Step 4: Display the result
print(f"The reversed number is {reversed_num}")

Explanation

Step 1: Take Input from the User

  • The input() function prompts the user to enter a number. The input is taken as a string to facilitate the manipulation of individual digits.

Step 2: Reverse the String Using Slicing

  • The program checks if the input number is negative by looking at the first character. If it is, the negative sign is preserved, and the rest of the number is reversed using slicing ([::-1]).

Step 3: Convert the Reversed String Back to an Integer

  • The reversed string is converted back to an integer using int() to ensure the output is a valid number.

Step 4: Display the Result

  • The print() function is used to display the reversed number.

Output Example

Example 1:

Enter a number: 1234
The reversed number is 4321

Example 2:

Enter a number: -5678
The reversed number is -8765

Example 3:

Enter a number: 1000
The reversed number is 1

Conclusion

This Python program demonstrates how to reverse the digits of a number by converting it to a string, manipulating the string, and converting it back to an integer. It’s a straightforward example that helps beginners understand string slicing and type conversion in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top