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.

1
  • 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 Commented Feb 13, 2014 at 8:48

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

7 Comments

continue means start loop again and break break to loop
Perhaps the OP means if float(N) != int(N) to check that an integer was actually entered?
@aquavitae Yes, but I cover that with the try:... part.
Hi. Thanks for your help.<br/> 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.
@Yin That is totally clear, and covered in my solution.
|
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.

7 Comments

+1 for the first part, -0.4 for the last one. Makes +0.6, which still is +1 :-)
Haha, close one! Mind if I ask what's wrong with the second part? :)
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.
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? :)
Use while if you want to repeat something while some condition is true, and use for to go over the elements of some sequence.
|
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)

Comments

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


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

2 Comments

Factorial of a number using python
Please edit your answer to include your comment to your answer for clarity.
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

2 Comments

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
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
0

You can check math module for python.

# math.factorial(x)
Return x factorial. 
Raises ValueError if x is not integral or is negative.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.