Page 151 - Information_Practice_Fliipbook_Class11
P. 151
For this purpose, we begin with a clean slate, i.e.,
1. We initialise reverseNum as 0.
2. Next, we extract the unit's digit (4) and add it to reverseNum. So, reverseNum becomes 4.
3. Now that we do not require the unit's digit any more, we discard it by setting num = num // 10. Now num is
equal to 123.
4. Again, we multiply reverseNum by 10 and add to it the unit's digit (3) from the current value of num (123). Thus,
reverseNum becomes 43. Again, discarding the units's digit of num, we get num equal to 12.
5. We multiply reverseNum by 10 and add to it the unit's digit (2) from the current value of num (12). Thus,
reverseNum becomes 432. Now, discarding the units's digit (2) of num (12), we get the num equal to 1.
6. Again, we multiply reverseNum by 10 and add to it the unit's digit (1) from the current value of num (1). Thus,
reverseNum becomes 4321.7. Now, discarding the units's digit of num, we get num equal to 0, which indicates
that there are no more digits to be processed and we have been able to build reverseNum as desired.
Program 6.6 Write a program to find reverse of the number.
01 '''
02 Objective: To find reverse of the number
03 Input:
04 num : number whose reverse has to be returned
05 Output: reverse of num
06 '''
07 num = int(input('Enter a number: '))
08 reverseNum = 0
09 while num > 0:
10 remainder = num % 10
11 reverseNum = reverseNum * 10 + remainder
12 num = num // 10
13 print('Reverse: ', reverseNum)
Sample Output:
>>> Enter a number: 1234
Reverse: 4321
As shown in the syntax for the while statement, it may include an optional else clause. It operates like the else
clause in a for statement, i.e., the else clause gets executed on a smooth exit from the while loop. However, if control
moves out of the while loop on execution of the break statement, the else clause is ignored.
Enter in loop
False
Condition
True
else block
Body
Encounter
no break
yes
Exit from loop
Fig 6.3
Looping in Python 137

