Search code examples
pythonpython-3.xprogram-entry-point

Assigning variables inside a function


this question is probably so common that it is being asked every other minute but I've tried to look for answers and couldn't find it. Most likely I wasn't able to phrase the question well enough.

Anyway, I'm working on a small text-game and it has variables, for simplicity let's say water = 100. And I have a function that is the main loop. Let's say the code looks something like this:

water = 100

def main():
    while True:
        water -= 5
        print(water)

main()

Of course, when I run this program it tells me that the variable was referenced before assignment. But if I make the variable inside the function then with each iteration of the loop it will reset the variable to the original 100.

So how do I make this work? Thanks!


Solution

  • Use keyword global. In your code declare in function global water before the loop and then your code will work fine.