Factorial calculation using Python

a 夏天 提交于 2019-12-07 04:54:53

问题


I am new to Python and currently reading Python 3 for absolute beginner and face following problem.

I would like to calculate factorial with procedure.

  1. request user to input an non negative number n
  2. then use for loop to calculate factorial

and the code is like that:

N = input("Please input factorial you would like to calculate: ")
ans = 1
for i in range(1,N+1,1):
    ans = ans*i
print(ans)

while i would like to add a feature to check whether input number N is non-negative number. like:

if N != int(N) and N < 0:

I want the user to input N again if it is NOT non-negative number.

Thanks for your gentle help.


回答1:


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.




回答2:


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.




回答3:


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)



回答4:


You can check math module for python.

math.factorial(x)

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




回答5:


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


    print('factorial of number', factorial(5))


来源:https://stackoverflow.com/questions/21748910/factorial-calculation-using-python

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