+ 1
Python Problem
Plz guys tell me how this program works. When I input 12 it returns 2 when I input 50 it returns 2 when I input 100 it returns 3 Plz explain the program to me. n = int(input()) length = 0 while n > 0: n //= 10 length += 1 print(length)
3 Respuestas
+ 3
When you input 100 it checks if 100 is greater than 0 ,if yes it proceeds for further execution otherwise while loop ends ,
n//=10 is executed as n=n//10 where "//" is floor division operator which returns a quotient which is a integer lower than the actual number ,
For first time ,n=100//10=10 so n is 10 now and length is 1
Again while loop condition is checked since n is 10 loop runs again ,n=10//10 =1 and length is incremented by 1 again and is 2 now
1 is still greater than 0 so loop runs again ,n=1//10 is equal to 0 which normal division in python would have output as 0.1 and again length is incremented by 1 and so it is 3 now
So since n is 0 now and 0 is not greater than 0 while loop ends and final value of length is 3
Hopefully it made sense ,
Edit:as jayakrishna said it is finding the length of number
+ 5
Its finding number of digits in input number.
Ex:
n = 12 =>
n//=10=> n=12//10=1
length +=1 =>length = 1
n//10=> n=1//10=0
length +=1 => length = 2
n>0 false so loop exits
prints length =>2
n=50
n//=10=>n=50//10=5, length=1
n=n//10=>n=5//10=0, length=2
n=100
n=n//10=>n=100//10=10, length=1
n=n//10=>n=10//10=1,length=2
n=1//10=>n=0,length =3
n>0 false loop exits and print length =>3
+ 2
Umar Haque here is you code with explanation in the while loop...
https://code.sololearn.com/cO7ae3E4I9sj/?ref=app
remember:
n > 0 so 12 / 10 = n = 1 > 0
remember:
n > 0 so 100 / 10 = n = 10 > 0 so 10 / 10 = n = 1 > 0