LoginSignup
2
3

More than 5 years have passed since last update.

グローバル変数とローカル変数についてのメモ

Posted at
test.py
#グローバル変数(どこでも使える)
globalNum = 3


#同じ変数名を使い回す
def sumInt():

    #ローカル変数(関数の中でのみ有効)
    local = 2
    print(globalNum + local)


def sumString():

    local = "ほげ"
    print(str(globalNum) + local)


#関数内でグローバル関数を書き換える
def globalRewrite():

    global globalNum
    globalNum = 4
    print(globalNum)


sumInt()
sumString()
globalRewrite()
#変数globalNumは書き換わったまま
print(globalNum)
#関数の外でローカル変数localを表示
print(local)

結果

5
3ほげ
4
4
----------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-a2e37807fa3a> in <module>()
     31 print(globalNum)
     32 #関数の外でローカル変数localを表示
---> 33 print(local)

NameError: name 'local' is not defined

2
3
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
2
3