Windows_736
Windows_736

Reputation: 11

How to declare a variable as a global variable once? [Python]

How do I declare a variable as a global variable in python? So what I'm trying to do is make an arcade game where a variable called "money" is global, and each time you visit a game, the money goes down by five. Code:

money = 0

global money

Basically I want to declare money as "0" once, then make that a global variable.

Upvotes: 1

Views: 2059

Answers (1)

SpaceSaver2000
SpaceSaver2000

Reputation: 100

This w3schools article should be what you're looking for.

TL;DR

My understanding is that any variable defined outside of a function is technically global. To make a global variable accessible within a function you must use the global keyword. The global keyword is both able to create global variables and make them accessible within a function. My own experimentation is shown below:

>>> money = 0
>>> def changeMoney(newMoney):
...     money += newMoney
... 
>>> print(str(money))
0
>>> changeMoney(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in changeMoney
UnboundLocalError: local variable 'money' referenced before assignment
>>> def changeMoney(newMoney):
...     global money
...     money += newMoney
... 
>>> print(str(money))
0
>>> changeMoney(7)
>>> print(str(money))
7
>>> changeMoney(7)
>>> print(str(money))
14
>>> money += 1
>>> print(str(money))
15
>>> changeMoney(7)
>>> print(str(money))
22

Rereading your message, if you don't want to deal with global statements you may want to look into Python classes (not a coding course, but a thing in Python) and using instance variables.

Upvotes: 1

Related Questions