[Tutor] Simple factorial program

ayyaz ayyaz84 at gmail.com
Thu Jun 11 18:11:27 CEST 2009


Eddie wrote:
> I'm trying to write a simple factorial program and am unsure at what is 
> wrong with it. Why Can't I go *factorial = factorial * number* where 
> factorial and number are both integers?
> 
> #Factorial program
> 
> print "Factorial finder"
> number = input("Please enter a non-negative integer: "
>     for number in range(number, 1)
>     factorial = (factorial * number)
> 
> print "Factorial:", factorial
>       
> Thanks Eddie
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
Hello Eddie,

You never initialized the variable factorial. So the line
"factorial = (factorial * number)" will crash your program since
the program doesn't know what the variable factorial is.

I would modify your code as follows:

factorial  = int(raw_input("\nPlease enter a non-negative integer: "))

for i in range(1,factorial):
     factorial *= i

print "Factorial:", factorial

raw_input("\nPress enter to exit")


I hope this helps.
--ayyaz



More information about the Tutor mailing list