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 のスコープ(変数の見える範囲)【Day 19】

Last updated at Posted at 2025-12-18

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day19 の記事です。

Python のスコープ(変数の見える範囲)

Python では 変数には「見える範囲」がある ことを理解しておくと、エラーやバグを防ぎやすくなります。
これを スコープ(scope) と呼びます。

1. グローバル変数とローカル変数

  • グローバル変数:関数の外で定義された変数。プログラム全体で見える
  • ローカル変数:関数の中で定義された変数。その関数の中でしか見えない

■ 例

x = 10  # グローバル変数

def my_func():
    y = 5  # ローカル変数
    print("x =", x)
    print("y =", y)

my_func()

print("x =", x)
# print("y =", y)  # ❌ エラー:yは関数外では見えない

2. グローバル変数を関数内で変更する

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1
  • global を使うと関数内からもグローバル変数を変更できる
  • ただし、安易に使うとバグの原因になるので注意

3. 関数内でのローカル変数優先

関数内で同じ名前の変数を作ると、ローカルが優先されます。

x = 10

def func():
    x = 5  # ローカル変数
    print(x)

func()   # 5
print(x) # 10(グローバルは変わらない)

4. ネストした関数(入れ子)と nonlocal

def outer():
    y = 10
    def inner():
        nonlocal y
        y += 5
    inner()
    print(y)

outer()  # 15
  • nonlocal を使うと 直近の外側関数の変数を変更 できる

5. 今日のまとめ

  • グローバル変数:関数外で定義、全体で見える
  • ローカル変数:関数内で定義、関数内だけで見える
  • 同じ名前がある場合はローカルが優先
  • 変更が必要なときは global または nonlocal を使うが、多用は避ける

6. ミニ問題

Q1.
次のコードでエラーが出る理由は?

def f():
    a = 1
f()
print(a)

Q2.
関数内の変数 x を、グローバル変数の x に加算するにはどうすればよいでしょうか?

x = 1
def f():
    x = 2
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?