Skip to content
Advertisement

Python while loop not working as intended

I don’t know how to get over this problem with while loop. So basically I want to return the number of zeros at the end of a number’s factorial.

import math


def zeros(n):
    total_zero = 0
    n = math.factorial(n)
    while str(n)[-1] == '0':  # to check if the last number is 0 or not
        n = n * 0.1
        total_zero += 1

    return total_zero


output = zeros(30)
print(output)

After the while loop runs only 1 time, it breaks; I don’t know why.

Help would be very appreciated. Thanks!

Advertisement

Answer

After multiplying your value by 0.1 it becomes a float, and it’s string representation becomes the scientific notation 2.6525285981219107e+31 which doesn’t end by a 1

You’d better do the integer division by 10 to keep an int

def zeros(n):
    total_zero = 0
    n = math.factorial(n)
    while str(n)[-1] == '0':  # to check if the last number is 0 or not
        n = n // 10
        total_zero += 1
        print(f"testting {str(n)}")
    return total_zero

>> zeros(30)
testting 26525285981219105863630848000000
testting 2652528598121910586363084800000
testting 265252859812191058636308480000
testting 26525285981219105863630848000
testting 2652528598121910586363084800
testting 265252859812191058636308480
testting 26525285981219105863630848
7

Better You can also use str.rstrip : you remove the leading zeros and check the length difference

def zeros(n):
    value = str(math.factorial(n))
    return len(value) - len(value.rstrip("0"))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement