I got error in this.
The error is gone when I comment on these lines as shown below:
Why is this happening?
Initialize fact=1 before for loop.
The line fact = 1 should be written above the loop as any variable declared in the loop cant be used outside the loop . also in any function all the content of that function should be written befor the return statement otherwise they will not be executed.
Here is the function code if you want it.
def factorial_iterative ( n ) : fact = 1 # now it can be used in all the function for i in range( n ): fact = fact * (i + 1) return fact
please replace “_” by white space i.e. " "
Aakash, here is the way to write code in Discourse:
Thanks sir, will keep in mind
No…you’re missing my point. I know that it works if I initialize fact before for loop. My doubt is
fact is a global variable right? So if it works in the second screenshot…should it not work in the first as well. fact used in the return statement is recognised as a global variable…but it is not so when used inside the for loop. Is it because fact is two levels of scope outside when it is used inside the for loop? Either ways…fact is a global variable and should be visible anywhere inside the function right? Sorry If I am terribly wrong with the concept.
I took the question out of context.
in python for using global variable we have to use the following syntax
fact = 1 def factorial_iterative (n) : global fact for i in range( n ): fact = fact * (i+1) return fact print(factorial_iterative(5))
Then how come the second screenshot with just the return statement is working fine without using the global keyword?
You can return add subtract and multiply the global variable. But you can’t change its value without using global keyword.
Here is an article you can read that explains it way better then me
Cool…I understand now. Thanks man!
Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they’re declared global with the global keyword). A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can’t modify the binding in the enclosing environment. UnboundLocalError happend because when python sees an assignment inside a function then it considers that variable as local variable and will not fetch its value from enclosing or global scope when we execute the function. To modify a global variable inside a function, you must use the global keyword.