Why does my factorial end in zero in my while loop?

Viewed 35

Here's my code:

inputNum = eval(input("enter number to calculate factorial"))

total = inputNum

j = 1

while j < total and inputNum != 0 :
    j = j + 1
    print("j is", j)
    print("initial total is", total)
    inputNum = inputNum-1
    print("inputNum is", inputNum)
    total = total * inputNum
    print("total is", total)  
    #once you get to j==5, it is greater than inputNum == 3
    #I'm going to redefine while to be while j!=0
print("The factorial of", inputNum, "is", total)

Now, no matter what number I put in, the last four lines of output give me:

initial total is (inputNum!)
inputNum is 0
total is 0
The factorial of 0 is 0

I already said that inputNum != 0, so why won't stop once it gets to the correct answer?

1 Answers

At the last iteration inputNum is 0, and then you multiply total by inputNum.
For example, you can multiply total first, and then decrease inputNum

Here is the code:

inputNum = eval(input("enter number to calculate factorial "))

total = 1
while inputNum > 0:
    total = total * inputNum
    inputNum = inputNum - 1

print(total)

Result:

enter number to calculate factorial 5
120
Related