TOPIC-PYTHON
--------------------------------
In the below code why r=0 and please explain r=r*10+d
------------------------------------------------------------------------------------------------------
s=int (input("Enter any number:"))
r=0
while (s>0):
d=s%10
r=r*10+d
s=s//10
print ("reverse",r)

Respuesta :

tonb

Explanation:

r=r*10+d shifts the previous value to the left (by multiplying by 10) and adds a new digit.

So imagine r = 123 and you want to append 4 to it.

First r is multiplied by 10, so you have 1230. Then you add 4, and get 1234.

The r variable builds up the reverse of s, so it starts at 0.

This program prints a number with reversed digits. For example, if you input 3564, you'll get 4653.

Suppose you give [tex]s=45[/tex], and let's see what the code does line by line:

We give 45 as input, and define [tex]r=0[/tex].

Then, we enter the while loop. The instruction d = s%10 simply extracts the last digit from s. In this case, [tex]d=5[/tex].

The istruction [tex]r = r\ast 10+d[/tex] adds a 0 at the end of the current value of [tex]r[/tex]. Then we add [tex]d[/tex], so now the last digit of [tex]r[/tex] is [tex]d[/tex]: we're performing

[tex]0\cdot 10 + 5 = 5[/tex]

Finally, the integer division s = s//10 cuts the last digit from [tex]s[/tex]. So, after the first loop, we have

[tex]d=5,\quad r=5,\quad s=4[/tex]

We enter the loop again. we have

[tex]d = s\%10 = 4\%10 = 4[/tex]

The new value of [tex]r[/tex] is

[tex]5\cdot 10 + 4 = 54[/tex]

And the division s//10 returns 0, so we exit the loop.

And indeed we have r=54, which is 45 in reverse.

ACCESS MORE
EDU ACCESS