While loop breaking
Hi all, I can't seem to get my while loop to break when my count (total) reaches 0. I'm trying to make a function that calculates a factorial of a number, as an exercise. I want to input an integer into factorial(), and my function to return the total of that factorial. A factorial is the multiplication of a number by every number lower than it, until 1. So if I run factorial(4), I want the function to calculate 4 * 3 * 2 * 1. If I input 6, I want it to calculate 6 * 5 * 4 * 3 * 2 * 1. 1 def factorial(x): 2 total = int(x) 3 x = str(x) 4 if x == "1": 5 return total 6 else: 7 while int(x) > 0: 8 total *= (int(x) - 1) 9 x = int(x) - 1 10 if int(total) == 0: 11 break 12 return total In the while loop, I am trying to say that if int(x) is greater than zero, the while loop should operate (line 7). I added at the end an if condition (line 10), saying that if total is equal to zero, the while loop should break. When I run factorial(2), the result is 0. The result should be 2, as 2*1 = 2. Can anyone offer a suggestion to make this work? EDIT I found a solution that gave me the answer that I was looking for: 1 def factorial(x): 2 total = int(x) 3 x = str(x) 4 if x == "1": 5 return total 6 else: 7 while int(x) > 0: 8 total *= x 9 x -=x 10 return total I'm still not sure why my original code wasn't working though -- any help?