0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで学ぶ「変数のスコープ」:globalとlocalの違い

0
Posted at

Pythonで学ぶ「変数のスコープ」:globalとlocalの違い

Pythonでプログラムを書いていると、「同じ変数名を使っているのに中身が違う!」「変数が参照できない!」といった混乱に陥ることがあります。
その原因の多くは「変数のスコープ(有効範囲)」にある

この記事では、Pythonにおける変数のスコープと、globalキーワードの使い方について、サンプルコード付きでわかりやすく解説する。


スコープとは?

スコープとは、「変数が使える範囲」のことです。
Pythonでは、どこで変数が定義されたか によって、どこからアクセスできるかが決まります。


スコープの種類

スコープの種類 説明
グローバル変数 関数の外で定義された変数。スクリプト全体で有効。
ローカル変数 関数の中で定義された変数。関数の外からはアクセスできない。

実際のコードで確認

arg = "arg"  # グローバル変数

def local_arg():
    arg = "local"  # ローカル変数(グローバルとは別物)

def global_arg():
    global arg     # ここでグローバル変数を参照・書き換える
    arg = "global"
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?