In this program, you will learn how to reverse a number.
num = int(input('Enter the number: '))
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed number: " + str(reversed_num))
Enter the number: 1234
Reversed number: 4321
In this program, the num variable holds the given value and reversed_num is intialized to zero. We are using while loop to reverse a number.
Now num = 0 . So, the expression num != 0 fails and while loop exits. The reversed_num is already contains values 4321.
num = int(input('Enter the number: '))
print("Reversed number: " + str(num)[::-1])
Enter the number: 5678
Reversed number: 8765
In this program, we are using string slicing concept to reverse the string. ::-1 represents start:stop:step. When you pass -1 as step, the start point goes to the end and stop at the front.
The following topics can be useful to understand this program.