[Tutor] Simple factorial program

Dave Angel davea at ieee.org
Thu Jun 11 19:25:33 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 [?]
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <http://mail.python.org/pipermail/tutor/attachments/20090612/b4700543/attachment-0001.htm>
> -------------- next part --------------
> A non-text attachment was scrubbed...
> Name: not available
> Type: image/gif
> Size: 96 bytes
> Desc: not available
> URL: <http://mail.python.org/pipermail/tutor/attachments/20090612/b4700543/attachment-0001.gif>
>
>   

Six problems in that initial code.  Two of them were identified 
already.  But I'll repeat them to put them in one place.

1) Need closing parenthesis on the input function call
2) Need to give an initial value to factorial, sometime before the for loop
3) Must not indent the for loop statement;  it should line up with the 
input statement
4) parameters to range don't make sense
5) Need to end the for loop with a colon
6) Need to indent the body of the for loop


print "Factorial finder"
number = input("Please enter a non-negative integer: ")
factorial = 1
for number in range(1, number+1):
        factorial = (factorial * number)

print "Factorial:", factorial





More information about the Tutor mailing list