Factorial calculation using Python

笑着哭i 提交于 2019-12-05 09:33:47

The construct could look like this:

while True:
    N = input("Please input factorial you would like to calculate: ")
    try: # try to ...
        N = int(N) # convert it to an integer.
    except ValueError: # If that didn't succeed...
        print("Invalid input: not an integer.")
        continue # retry by restarting the while loop.
    if N > 0: # valid input
        break # then leave the while loop.
    # If we are here, we are about to re-enter the while loop.
    print("Invalid input: not positive.")

In Python 3, input() returns a string. You have to convert it to a number in all cases. Your N != int(N) thus makes no sense, as you cannot compare a string with an int.

Instead, try to convert it to an int directly, and if that doesn't work, let the user enter again. That rejects floating point numbers as well as everything else which is not valid as an integer.

In Python's math library, there is a factorial function. You can use it like so:

import math
...
ans = math.factorial(N)

Since you want to calculate using a loop however, have you considered the following?

ans = -1
while ans < 0:
    N = input("Please enter a positive integer: ")
    if N.isdigit() == True:
        n = int(N)
        if n >= 0:
            ans = n
            for x in range (n-1, 1, -1):
                ans *= x
            print (ans)

Note, the second solution doesn't work for N = 0, where ans = 1 is correct by definition of factorial.

Number = int(input("Enter the number to calculate the factorial: "))
factorial = 1
for i in range(1,Number+1):
    factorial = i*factorial

print("Factorial of ",Number," is : ", factorial)
Sampath

You can check math module for python.

math.factorial(x)

Return x factorial. Raises ValueError if x is not integral or is negative.

Vinay
def factorial(a):
    if a == 1:
        return 1
    else:
        return a * factorial(a - 1)


    print('factorial of number', factorial(5))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!