Ask coding questions

← Back to all posts
Why Is the var Water not used when it is?
LukeShomper (26)

This is confuse. and I have smol brain

Water is not working and I am mad

Answered by Nemoiscool (44) [earned 5 cycles]
View Answer
Nemoiscool (44)

I have discovered a few issues. The first is on line 12:

'Water =- (Humans2)' should be:
'Water -= (Humans
2)' (note the switch of the '-' and '=')

Next, variables declared outside of functions cannot be used inside functions unless you do one of a couple things:

At the beginning of every function you declare the variable to be global by typing this line: 'global Water.'

Another way would be to use parameters. to declare a parameter, simply put the parameter name inside the parenthesis when you define it. Then, when you call the function, pass in the current value of water. Now, that will change it within the function, but not the value of the original variable, so at the end of the function you could type 'return [your parameter name].' That doesn't entirely fix the problem. To finish that up, every time you call the function, call it like this:

'Water = yourFunction(Water)'

That assigns the Water variable to be equal to what the function returned.

Also, you never call the function.

That was a very long answer, but I hope that explanation helps a bit. Good Luck! If you need clarification on something, let me know.

LukeShomper (26)

@Nemoiscool Did Have the answer that helped more but @maazzubair99 Helped a lot too!

maazzubair99 (93)

To understand why your code isnt working, you first have to understand scope. When you made the water variable, you made it in the global scope. This is normally what you use, but in functions, it will make a water variable in the local scope, which means only in that function. In your DAY() function, you are subtracting Humans*2 from water, and python thinks you are removing it from the local scope water. Python throws a fit because you are trying to subtract from a value that doesn't exist. If you want to use a global variable in the local scope, put the keyword global and then your variable, in your case global Water