+ 1

Is there a way for a function to update a variable, that is outside of that function, and to continuously update it?

I'm trying to get my code to keep adding days as you choose your selections, but it stays at a value of 2. The basic gist of my code is this: import sys day = 1 health = 100 def actions() print("1 - add a day\n2 - end") action = input() if action == "1": addDay() elif action == "2": sys.exit() else: print("choose again") actions() def addDay(day) day +=1 return day while health > 0: actions() print("u died") sys.exit()

19th May 2017, 4:02 PM
John Sager
John Sager - avatar
7 Antworten
+ 2
a variable inside a function is by default a "local variable" meaning it is a variable for that function. You can do what your trying to do by making your variable a global variable
19th May 2017, 4:12 PM
LordHill
LordHill - avatar
+ 1
Please keep in mind that use of global variables is generally considered a bad practice.
19th May 2017, 8:02 PM
Igor B
Igor B - avatar
+ 1
It works! I tried googling why global variables are generally a bad practice. I found an article y that said to Google it... eventually found an article that described spaghetti code. I figured that I'm not using this to publish or anything, just a fun text based game. So global variables shouldn't be too evil.
20th May 2017, 3:42 AM
John Sager
John Sager - avatar
0
There are local and global variables. Local variables cannot be accessed outside their scope. Global variables can be accessed from anywhere. What you are doing wrong is that you included a parameter 'day' in your 'addDay' function. The problem with that is if you define a LOCAL variable with the SAME name as the GLOBAL variable, then the local version of the 'day' variable is used in the local scope (inside the 'addDay' fucntion). All you have to do is remove that paramater and the global version of that variable will be used inside that function.
19th May 2017, 4:15 PM
Ralf Sild
0
I tried to use it as a global variable, but I guess I forgot to take out the parameter. I'll try that.
19th May 2017, 4:22 PM
John Sager
John Sager - avatar
0
They are bad practice, but they do exist for a reason. Some of my early codes used them and people told me the same thing. as my skill went up I found that I no longer need or use them. keep up the good work John.
20th May 2017, 1:42 PM
LordHill
LordHill - avatar