0

Here is what i wrote:

number = raw_input('Enter an integer= ')
if number < 0:
    print 'Invalid number'

else:
    for k in range(1,(number)):
        number *= k

print number

I want to be able to input any number (that is greater than 0), but when i input a number say 4 (the factorial of 4 is 24) i get this error:

Traceback (most recent call last):
  File "problem.py", line 6, in <module>
    for k in range(1,(number)):
TypeError: range() integer end argument expected, got str.

I don't understand what it means and as far as i know the code should be working, Please Help!

4 Answers 4

4

This works perfectly: factorial.py

#!/usr/bin/env python

# imports go here

__author__ = 'Michael O. Duffy'
__status__ = "Development"

def factorial(n):
    """ Calculate a factorial of an integer """
    factorial = 1
    if n < 0:
        print 'Invalid number'
    else:
        for k in range(1,n+1):
            factorial *= k
    return factorial

if __name__ == '__main__':

    for number in range(1, 20):
        print 'n: ', number, 'n!: ', factorial(number)

You should know that this is an inefficient, academic implementation that shouldn't be used in any serious application. You'll be a lot better off using a gamma or lngamma implementation and a dictionary cache to save on calculations if you use values repeatedly:

http://mathworld.wolfram.com/GammaFunction.html

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

Comments

2

What about recursion?

def factorial(n):
  if n < 0:
    print("ERROR!") # throw error, return -1, or whatever
  elif n <= 1:
    return 1
  else:
    return n * factorial(n - 1)

1 Comment

Thanks it works now, and im going to try out the lngamma implementation, by the way this was a part of my project for math class thanks for everybodies help!
1

raw_input returns a string, not an integer. Create an integer this way:

number = int(raw_input('Enter an integer= '))

The user might type something besides an integer, in which case you might want to handle that possibility.

while True:
    try:
        number = int(raw_input('Enter an integer= '))
    except ValueError:
        print "That wasn't an integer"
    else:
        break

Comments

-1
using xxxxx.py
num=int(raw_input("Enter a number"))
n=1
while num>=0:
  n=n*num
  num=num-1
print "Factorial of the given number is: ",n

Comments

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.