简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM