Python "assumes" that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message. Any variable which is changed or created inside of a function is local, if it hasn t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword "global"
This is consistent to what we have found out in the previous subchapter: ? A variable defined inside of a function is local unless it is explicitly marked as global. ? In other words, we can refer a variable name in any enclosing scope, but we can only rebind variable names in the local scope by assigning to it or in the module-global scope by using a global declaration. ? We need a way to access variables of other scopes as well. The way to do this are nonlocal definitions.
Python introduced nonlocal variables as a new kind of variables. nonlocal variables have a lot in common with global variables. One difference to global variables lies in the fact that it is not possible to change variables from the module scope, i.e. Variables which are not defined inside of a function, by using the nonlocal statement.
This means that nonlocal bindings can only be used inside of nested functions. ? A nonlocal variable has to be defined in the enclosing function scope. ? If the variable is not defined in the enclosing function scope, the variable cannot be defined in the nested scope.
المادة المعروضة اعلاه هي مدخل الى المحاضرة المرفوعة بواسطة استاذ(ة) المادة . وقد تبدو لك غير متكاملة . حيث يضع استاذ المادة في بعض الاحيان فقط الجزء الاول من المحاضرة من اجل الاطلاع على ما ستقوم بتحميله لاحقا . في نظام التعليم الالكتروني نوفر هذه الخدمة لكي نبقيك على اطلاع حول محتوى الملف الذي ستقوم بتحميله .
|