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.

有帮助吗?

解决方案

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)

You can check math module for python.

math.factorial(x)

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

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


    print('factorial of number', factorial(5))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top