Example 1: Reverse a Number using a while loop
num = 1234 reversed_num = 0 while num != 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num //= 10 print("Reversed Number: " + str(reversed_num))
In this program, while loop is used to reverse a number as given in the following steps:
- First, the remainder of the
numdivided by 10 is stored in the variable
digit. Now, the
digitcontains the last digit of
num, i.e. 4.
digitis then added to the variable reversed after multiplying it by 10. Multiplication by 10 adds a new place in the reversed number. One-th place multiplied by 10 gives you tenth place, tenth gives you hundredth, and so on. In this case,
0 * 10 + 4 = 4.
numis then divided by 10 so that now it only contains the first three digits: 123.
- After second iteration,
digitequals 3, reversed equals
4 * 10 + 3 = 43and
num = 12.
- After third iteration,
digitequals 2, reversed equals
43 * 10 + 2 = 432and
num = 1.
- After fourth iteration,
digitequals 1, reversed equals
432 * 10 + 1 = 4321and
num = 0.
num = 0, so the test expression
num != 0fails and while loop exits. reversed already contains the reversed number 4321.
Example 2: Using String slicing
num = 123456 print(str(num)[::-1])
Using the string slicing concept, you can get reverse the string.
::-1 corresponds to
start:stop:step. When you pass -1 as
start point goes to the end and
stop at the front.