0
0

More than 1 year has passed since last update.

Q. Pythonの"global"ってなに?

Last updated at Posted at 2022-12-29

関数のなかに書いてあったけど、なにこれ。

結論

「この関数ではグローバル変数を上書きするよ」という宣言。

Pythonでは、関数内から普通にグローバル変数を上書きしようとしてもエラーを吐くようになっている。(グローバル変数の安易な編集を防ぐため)

wallet = 0

def pay(amount):
  wallet -= amount

# UnboundLocalError: local variable 'wallet' referenced before assignment

この例では、pay()関数内でwalletというグローバル変数から引き算しようとしているので、UnboundLocalErrorを引き起こしている。

wallet = 0

def pay(amount):
  global wallet
  wallet -= amount

これで解決。

おわりに

Pythonくん、こういうところ意外と親切。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0