开发者

Python Factorial program help

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!


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


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)


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜