Global Variable in Python

前端 未结 2 1217
说谎
说谎 2020-12-21 06:30

I am very new to Python. Not learnt classes yet. Using Python 3.2.2. Tried implement some procedural C logic. My code is spread over 2 files as follows.

this file i

相关标签:
2条回答
  • 2020-12-21 06:58

    To assign values to a global variable in your code you've got to mark it as such, otherwise the code would be assigning to a local variable with the same name (that would be actually shadowing the global variable).

    As explained in the documentation:

    It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

    Hence, to fix the problem, you'd need something like this:

    def isValidDate(d,m,y):
        if(d>=1 and d<=31 and m>=1 and m<=12):
            global dd, mm, yy
            dd,mm,yy=d,m,y
            ...
    
    0 讨论(0)
  • 2020-12-21 07:15

    Your date.isValidDate function does not operate on the globalvariables dd, mm, yy - it rather operates on (function) local variables with the same names.

    In order for date.isValidDate to change the (module) global values of the variables you want, you have to declare them as global at the top of the function - like this:

    def isValidDate(d,m,y):
        global dd, mm, yy
        ...
    
    0 讨论(0)
提交回复
热议问题