程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python local variables and global variables

編輯:Python

Local variables cannot be modified. Global variables cannot be modified ? How can it still run ?

answer : because point += 2 amount to point = point + 2, This point Parameters received are 【 Positional arguments 】point

So it's equivalent to just 【 Local scope 】 Write an assignment statement .

def sum(point):
point += 2 # local variable
return point
point = 10 # Global variables
n = sum(5)
print(n)


It won't work like this :

point = 4
def sum(name):
point = point + 2
return point
point = 10
n = sum(10)
print(n)

There is an error :UnboundLocalError: local variable ‘point’ referenced before assignment. Translation is : local variable point Quoted before assignment . in other words :python hold point = point + 2 Medium point Used as a local variable , However, he was not assigned a value , Therefore, an error is reported , Why local variables don't use global variables point Well ? This is because in the same row of assignment statements , Local variables cannot reference global variables , Will be python It is misunderstood as modifying the global variable value .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved