「Python」globalでグルーバル変数の値を変更するサンプル
環境
PyCharm 2021.3
Python 3.9.7
書式
def 関数名():
global 変数名
def 関数名():
global 変数名
def 関数名(): global 変数名
globalを利用して、グローバル変数の値を変更します。
使用例
# coding: utf-8
#グローバル変数
strA = "study"
#定義関数funA
def funA():
#変数の前にglobalを付け
global strA
#変数名strAに値を代入する
strA = "Tokyo"
return strA
print("結果1")
print(funA())
print("結果2")
print(strA)
# coding: utf-8
#グローバル変数
strA = "study"
#定義関数funA
def funA():
#変数の前にglobalを付け
global strA
#変数名strAに値を代入する
strA = "Tokyo"
return strA
print("結果1")
print(funA())
print("結果2")
print(strA)
# coding: utf-8 #グローバル変数 strA = "study" #定義関数funA def funA(): #変数の前にglobalを付け global strA #変数名strAに値を代入する strA = "Tokyo" return strA print("結果1") print(funA()) print("結果2") print(strA)
実行結果
結果1
Tokyo
結果2
Tokyo
結果1
Tokyo
結果2
Tokyo
結果1 Tokyo 結果2 Tokyo