Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorial calculation using Python

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.

like image 645
useR Avatar asked Feb 13 '14 08:02

useR


2 Answers

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.

like image 199
glglgl Avatar answered Oct 12 '22 06:10

glglgl


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.

like image 40
EducateMe Avatar answered Oct 12 '22 05:10

EducateMe