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!

Upvotes: 0

Views: 5244

Answers (4)

Navakishore
Navakishore

Reputation: 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

Upvotes: -1

duffymo
duffymo

Reputation: 308753

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

Upvotes: 4

SteeveDroz
SteeveDroz

Reputation: 6136

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)

Upvotes: 2

Mark Tolonen
Mark Tolonen

Reputation: 177600

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

Upvotes: 1

Related Questions