4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pyhton_ローカル変数とグローバル変数

Last updated at Posted at 2021-11-24

関数外で定義した変数はグローバル変数

num = 50
def printnum():
    print(num)

print(num)
printnum()
print(num)

50
50
50

関数の中で代入した変数はローカル変数

  • 関数内が範囲
  • グローバルに同名の変数があっても関数内では優先される
num = 50
def printnum():
    num = 20
    print(num)

print(num)
printnum()
print(num)

50
20
50

関数内でglobal変数を更新する

num = 50
def printnum():
    global num
    num = 20
    print(num)

print(num)
printnum()
print(num)

50
20
20

ネストした関数で1段上の関数の変数を更新する

何もしていない時はそれぞれのローカル変数を読み込む。

num = 0

def print_num_outer():
    num = 1
    
    def print_num_inner():
        num = 2
        print(num)
    
    print_num_inner()
    print(num)


print(num)
print_num_outer()
print(num)

0
2
1
0

ネストした関数で1段上の関数の変数を参照している

num = 0

def print_num_outer():
    num = 1
    
    def print_num_inner():
        nonlocal num
        num = 2
        print(num)
    
    print_num_inner()
    print(num)


print(num)
print_num_outer()
print(num)

0
2
2
0

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?