6

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
useR
  • 3,062
  • 10
  • 51
  • 66
  • 1
    You don't need the last 1 in range(1,N+1,1) since the default incrementer is +1. Only range(1,N+1) suffices – Bayko Feb 13 '14 at 08:48

6 Answers6

4

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • `continue` means start loop again and `break` break to loop – WBAR Feb 13 '14 at 08:48
  • Perhaps the OP means `if float(N) != int(N)` to check that an integer was actually entered? – aquavitae Feb 13 '14 at 08:49
  • @aquavitae Yes, but I cover that with the `try:`... part. – glglgl Feb 13 '14 at 08:50
  • Hi. Thanks for your help.
    the reason i add N != int(N) is that i would like to sure N is an integer but not like 3.3. As 3.3! is undefined.
    – useR Feb 13 '14 at 08:51
  • @Yin That is totally clear, and covered in my solution. – glglgl Feb 13 '14 at 08:54
  • @glglgl Thanks! And one minor question is that i do found the output is slightly different if i input 3.3 and -2. It shown invalid input for 3.3 while do not for -2. What should i do if i want to print("invalid input") for negative number? Thanks again. – useR Feb 13 '14 at 09:08
  • Thanks again @glglgl, i would like to learn continue-break concept in a general case. For example besides checking whether N is integer and non-negative, i also want to ensure the input value N is an even number. Which line i should add? 'N % 2 == 0' Thanks – useR Feb 13 '14 at 09:43
1

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.

EducateMe
  • 461
  • 1
  • 3
  • 13
  • +1 for the first part, -0.4 for the last one. Makes +0.6, which still is +1 :-) – glglgl Feb 13 '14 at 08:55
  • Haha, close one! Mind if I ask what's wrong with the second part? :) – EducateMe Feb 13 '14 at 08:56
  • It is incomplete. It doesn't tell the user to re-enter the number, and you are calling `int(N)` three times - which is better done with `nn = int(N)` once. – glglgl Feb 13 '14 at 08:59
  • I wanted to avoid more lines to look nice, but you're right, your implementation is better. I feel the method of looping I've edited in isn't the best though, any ideas? :) – EducateMe Feb 13 '14 at 09:03
  • @EducateMe thanks for your reply. As i m new to programming, i would like to ask in this case, i should use while loop or for loop? And in general case, when i should use while loop and for loop? Please dun feel this question is stupid TT. Thanks again. – useR Feb 13 '14 at 09:14
  • 2
    Use `while` if you want to repeat something while some condition is true, and use `for` to go over the elements of some sequence. – RemcoGerlich Feb 13 '14 at 09:15
  • @Yin Use `while` for looping until the input is ok, and use `for` for your calculation. – glglgl Feb 13 '14 at 09:33
0

You can check math module for python.

# math.factorial(x)
Return x factorial. 
Raises ValueError if x is not integral or is negative.
General Grievance
  • 4,555
  • 31
  • 31
  • 45
sam
  • 1,819
  • 1
  • 18
  • 30
  • Thanks! Maybe my question title is misleading. I just want to use factorial calculation as a example. (i don't know there is something like continue or break). – useR Feb 13 '14 at 09:17
0
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
def factorial(a):
    if a == 1:
        return 1
    else:
        return a * factorial(a - 1)


    print('factorial of number', factorial(5))
ZF007
  • 3,708
  • 8
  • 29
  • 48
Vinay
  • 29
  • 2
0

Start Declare Integer n,i,n! Display “Enter a nonnegative integer.” Input n For i=1 to n-1 Step1, Display “n!=i*n” End for Stop

Tracy
  • 1
  • The user is asking for Python code to calculate factorial. You answer seems more like an algorithm for calculating factorial. Appreciate your attempt to contribute, but this is not a valid answer IMHO – Anas Tiour Feb 09 '23 at 12:49
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33789528) – bolino Feb 13 '23 at 03:34