+ 1

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?

6th Apr 2020, 11:40 PM
Joel
3 Answers
+ 2
Joel The whole root of problems is that u used str() int() conversions which u dont need in this case. Remove ALL of them. You should have only integers in this case, not strings so remove quotation marks from "1". And yeah total should be 1 not x. total = 1, because: in the while loop x gets decreasing and gets multiplied to total so suppose x is 5. total = total * x 1 = 1 * 5 5 = 5 * 4 20 = 20 * 3 60 = 60 * 2 120 = 120 * 1 120 answer. And yeah, both of them are incorrect which u provided in question.
7th Apr 2020, 3:49 AM
maf
maf - avatar
+ 1
maf thank you! I made x into a string because I thought I had to for while to work. Thanks for the advice.
7th Apr 2020, 6:17 AM
Joel
+ 1
Joel np, this one is shorter. def fact(x): total = 1 while x - 1 != 0: total *= x x -= 1 return(total)
7th Apr 2020, 6:38 AM
maf
maf - avatar