[Python]전역변수, 지역변수

파이썬에서의 전역변수와 지역변수에 대해 알아보자

# 전역변수 예제1
x = 100

def test1():    
    return x * 10

print(test1())
print()

# 전역변수 예제2
y = 100

def test2():
    global y
    y = y * 10  #  전역변수 y 값을 변경한다.
    return y

print(test2())
print(f' y = {y}')

## 결과
1000

1000
 y = 1000
# 지역변수 예제

a = 20

def test():
    global a
    
    print(f'순서3 a = {a}')    
    
    a = 35
    
    return a

print(f"순서1 a = {a}")

a = 100

print(f"순서2 a = {a}")

print("순서4 test() = ", test())

print(f"순서5 a = {a}")

## 결과
순서1 a = 20
순서2 a = 100
순서3 a = 100
순서4 test() =  35
순서5 a = 35
def test(x, y):
    global a
    a = 49
    x,y = y,x
    b = 53
    b = 7
    a = 135
    # 예상1
    print('Step1 : ', a, b, x, y)

a, b, x, y = 8, 13, 33, 44 

# 함수 실행
test(23, 7)

# 예상2
print('Step2 : ', a, b, x, y)

## 결과
Step1 :  135 7 7 23
Step2 :  135 13 33 44

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다