please i need explanation
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Fri Jan 11 07:58:35 EST 2013
Am 11.01.2013 17:33 schrieb kwakukwatiah at gmail.com:
>> def factorial(n):
>> if n<2:
>> return 1
>> f = 1
>> while n>= 2:
>> f *= n
>> f -= 1
>> return f
>>
>>
>>
> please it works.
I doubt this.
If you give n = 4, you run into an endless loop.
> but don’t get why the return 1 and the code below.
The "if n < 2: return 1" serves to shorten the calculation process
below. It is redundant, as you have a "f = 1" and a "return f" for n < 2.
The code below first sets f, which holds the result, to 1 and then
multiplies it by n in each step. As the loop should contain a 'n -= 1',
n decreases by 1 every step, turning it into f = n * (n-1) * (n-2) * ...
* 2 and then, as n is not >= 2 any longer, stops the loop, returning f.
HTH,
Thomas
More information about the Python-list
mailing list