[Tutor] For Loops Program Issue

Alan Gauld alan.gauld at yahoo.co.uk
Tue Aug 18 12:49:12 EDT 2020


On 18/08/2020 16:17, eric grunfeld wrote:

> Here is the problem:
> 
> def factorial(n):
>     result = 1
>     for i in range(result,n):
>         result = result * n+1
>     return result
> 
> print(factorial(4)) # should return 24

A common debugging technique is to work through the program manually to
see what the variables are doing.

Lets try that:

For i = 1
n = 4,  result = 1
result => 1 * 4 + 1 => 5 (*)

For i = 2
n = 4, result = 5
result => 5 * 4 + 1 => 21

For i = 3
n = 4, result = 21
result => 21 * 4 + 1 => 85

...

Can you see what is going wrong?
What values should you be multiplying by?
Recall that multiplication comes before addition in priority so

result * n+1 is (result*n) + 1

Also you want n to increase but it doesn't.
What does increase is i.

> Here is your output:
> 85

> Based upon my understanding, it appears that my issue is with the set-up of
> my range.

Not entirely, its mainly to do with which values you
are mutiplying by.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list