0

Need Help please

Hi Guys, I need some help with this code. I debugged most of it but it still gives me a hard time with the return result statement error Python: SyntaxError 'return' outside function error can someone explain please exactly what the error means so I can fix it. Im new to python and im still struggling with the basics.If somebody could explain in layman terms would be great. def factorial(n): """Calculate the factorial of the given value and return the result. The factorial of n is the product of all positive integers less than or equal to n. Keyword arguments: n -- A positive integer """ result = 1 while n != 0: n = n - 1 result = result * n return result #Calculate factorial for the first four integers. for i in range(-1, 7): print('Factorial of', i, 'is', factorial(i))

14th Jan 2017, 1:25 AM
Tom
1 Resposta
0
I can't reproduce your error ( in code playground ), but I success to debug it ;) Firstly, in the factorial() function, you need to indent oe time more the line 'result = result * n ( to get it inside the while loop ), and swith this line with the previous ( n = n - 1 ), else the last iteration will multiply 'resut' by zero ^^ Next, you need to change the first parameter of the range() function because with a negative number passed to the factorial() function, the while loop becomes infinite ( decrementing a negative value will never reach zero :P )... Don't know what the behaviour of factorial of negative number is supposed to be, but you can certainly manage this case ;)
14th Jan 2017, 1:45 AM
visph
visph - avatar