Global Variable in Python

前端 未结 2 1232
说谎
说谎 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
            ...
    

提交回复
热议问题