Search code examples
pythonloopsfor-loopoutputfactorial

How to make the output numbers match the factorial results


I got an assignment to make a program using loops. User inputs a number from 1-98, then the output is a factorial of that number. If the user enters a number other than the number above, then the user is asked to re-enter the appropriate number. Now when the user input is appropriate, the output that comes out does not match the factorial results.

here's the picture of that error

and this is the code

num = int(input("Input Number (1-98) : "))

    Factorial = 1
    for a in range(1,num+1):
        if 0 < num < 99:
            Factorial = Factorial*a
        else :
            print("input does not match, Repeat input (1-98)")
            num = int(input("Input Number (1-98) :"))
    
    print ("The factorial of", num, "is", Factorial)

can you help me to fix this?


Solution

  • You must separate the input part and the compute part

    num = -1
    while not (0 < num < 99):
        num = int(input("Input Number (1-98) :"))
    
    Factorial = 1
    for a in range(1, num + 1):
        Factorial = Factorial * a
    
    print("The factorial of", num, "is", Factorial)
    

    The reason was

    • you input 99
    • the loop runs for all value, computing factorial until 98
    • else says "input does not match"
    • loop is over or not, but you keep the computed factorial in memory and starts from there