Factorial calculation using Python

I am new to Python and am currently reading Python 3 for an absolute beginner and am facing the following problem.

I would like to calculate the factorial with the procedure.

  • ask the user to enter a non-negative number n
  • then use for loop to calculate factorial

and the code is as follows:

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 function to check if the input number N is a non-negative number. as:

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

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

Thank you for your kind help.

+6
source share
4 answers

The design may 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 must convert it to a number in all cases. Thus, your N != int(N) does not make sense, since you cannot compare a string with an int.

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

+4
source

There is a factorial function in the Python math library. You can use it like this:

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

Since you want to calculate using a loop, do you consider 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 that the second solution does not work for N = 0, where ans = 1 is correct by the definition of factorial.

+1
source

You can check the math module for Python.

math.factorial (x)

Return x factorial. Raises a ValueError if x is not integer or negative.

0
source
 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) 
0
source

All Articles