[Solved] Python script- need help understanding this while loop [closed]


This is the proper indentation you need to use.

def mystery(n):  
    m = ""
    while n > 0:
        m += str(n % 10)
        n //= 10
    return m

When you call the function:

mystery(9870)
' 0789'

The function takes a parameter and checks if it is greater than 0. While the condition is satisfied, it divides the number by 10 and converts the remainder into a string and appends it to an empty string m. n //= 10 will remove the last digit of the number and stores the remaining in n. And the while loop checks if n is greater than 0 again. Etc.. The whole thing continues until n is a single digit number at which point, n//=10 will return 0 and the condition of while loop will not satisfy.

Basically, it reverses the digits of the number you pass as parameter.
Hope this explanation helps.

3

solved Python script- need help understanding this while loop [closed]