Hello every one, welcome back ! Here we will learn a simple python logic to reverse a number.
Here we read a number from user and reverse that number using slice operations. We first cast that integer number as string, and then perform a slicing operation to reverse the number.
We can also reverse a number without using slice operations, that is discussed in another post.
Reverse a number – Code Visualization
To reverse a given integer number.
- Read an input number using
- Check whether the value entered is integer or not.
- We convert that integer number to string
- Now we use advanced slice operation
[start:end:step]leaving start and empty and giving step a value of -1, this slice operation reverses the string.
- Print the result.
num = input('Enter any number : ')
val = int(num)
print('Reverse of the given number is : ', str(num)[::-1])
print("That's not a valid number!")
Want to be strong at OOP in Python? If yes, I would suggest you to take the course below.
Object Oriented Programming in Python