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 is called date.py
dd,mm,yy=0,0,0
def isValidDate(d,m,y):
if(d>=1 and d<=31 and m>=1 and m<=12):
dd,mm,yy=d,m,y #problem
print(dd,mm,yy) #problem
print(d,m,y) #problem
return True
else:
return False
def printDate():
print(dd,mm,yy) #problem
this file is called module1.py
import date
def main():
dd,mm,yy = 23,1,1984
valid = date.isValidDate(dd,mm,yy) #problem
print (valid)
date.printDate()
date.dd=22 #problem
date.printDate()
if __name__ == '__main__':
main()
The lines that I have commented as "problem" are giving me problems.
When the statement in module1.py (which is "date.dd=22") executes, the value of the global variable in date.py changes to 22 and stays that way.
But when I call the isValidDate() function, even though the test condition is passed, the assignment does not seem to be permanent. The local print statement in isValidDate() function shows that "dd" is assigned the value, but in the main() function the call to printDate() shows the original values.
What is going on?
date.dd = 22inmodule1and then callisValidDate(). However, your code does not do this. Can you post the exact code you are running and its output?isValidDatefunction so that the caller supplies those values. Python almost never requires global variables unless you're doing something really unusual. I just searched through a hundred-thousand-line codebase I've spent the last decade developing, and found that I've used exactly one global variable (and that one could be removed if I cared to).