「Python」globalでグルーバル変数の値を変更するサンプル

環境
PyCharm 2021.3
Python 3.9.7

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def 関数名():
global 変数名
def 関数名(): global 変数名
def 関数名():
  global 変数名

globalを利用して、グローバル変数の値を変更します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 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)

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
結果1
Tokyo
結果2
Tokyo
結果1 Tokyo 結果2 Tokyo
結果1
Tokyo
結果2
Tokyo

 

Python

Posted by arkgame