python program for reverse of a number using type casting

In this tutorial, we are going to learn how to reverse a given number within two lines of code in Python using the type casting method.

How to reverse a number (optimum solution) in Python

Before jump into the program 1st, you have some knowledge of typecasting in Python.

following are the way of typecasting in python:

let’s consider two variable

x=’123′  (string variable)
y=123    (integer variable)

1)integer to string:
—->  z=str(y)
—-> o/p= ‘123’

2)string to an integer:
—->  z=int(x)
—-> o/p=123

3)integer to float:
—-> z=float(y)
—-> o/p=123.0

In similar way in this program we are going to use type casting .

Now move on the program.
first, take a value from  the user:

#take integer as a string input from users.
x=input("Please enter a integer ")

Now use type cast concept to convert a string because the reverse of number is easier than the reverse of the string so we directly taking a number as a string then reverse them.

the reverse of given number which is taken by the user in a string format.

#reverse of string instead of integer.
y=x[::-1]

Now again typecast the string into integer and print it as an output.

#type cast from string to integer.
y=int(y)
print("Reverse of given number = ",y)

let’s combine the whole code together :

# Reverse of a number in python within very less line of code.
#take integer as a string input from users.
x=input("Please enter a integer ")
#reverse of string instead of integer.
y=x[::-1]
#type cast from string to integer.
y=int(y)
print("Reverse of given number = ",y)

Output:

Please enter a integer 156
Reverse of given number =  651

You may also read:

Leave a Reply