πŸ“‚μ›Ή 개발(Web)/🐍파이썬(Python)

μ§€μ—­λ³€μˆ˜(local) μ „μ—­λ³€μˆ˜(global)

πŸ‘©‍πŸŽ“μΈν…”λ¦¬κ°μžπŸ₯” 2023. 2. 1. 17:46

μ§€μ—­λ³€μˆ˜(local)
    ν•¨μˆ˜ λ‚΄λΆ€ μ„ μ–Έ
    ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œλ§Œ μ‚¬μš© κ°€λŠ₯

 

μ „μ—­ λ³€μˆ˜(global)
    ν•¨μˆ˜ λ‚΄λΆ€ μ™ΈλΆ€ λͺ¨λ‘ μ‚¬μš© κ°€λŠ₯

1.

gVar = 'μ „μ—­'
def globalAndLocal():
    lVar = '지역'
    print(gVar, 'λ³€μˆ˜ μž…λ‹ˆλ‹€.') # μ „μ—­λ³€μˆ˜, 참쑰만 ν•˜κ³  μžˆλ‹€.


    print(lVar, 'λ³€μˆ˜ μž…λ‹ˆλ‹€.')



globalAndLocal()

gVar = 'μ „μ—­'
def globalAndLocal2():
    lVar = '지역'
    gVar = 'λ³€κ²½λœ 전역이 μ•„λ‹Œ μƒˆλ‘œμš΄ 지역'  #지역
    print(gVar, 'λ³€μˆ˜ μž…λ‹ˆλ‹€.')


    print(lVar, 'λ³€μˆ˜ μž…λ‹ˆλ‹€.')


globalAndLocal2()
print(gVar)



2. μ „μ—­λ³€μˆ˜ μ„ μ–Έ
total = 0
def gift(dic, who, money):
    global total # μ „μ—­λ³€μˆ˜ total을 μ‚¬μš©ν•˜κ² λ‹€
    total += money
    dic[who] = money

wedding = {} #dictionary μ΄ˆκΈ°ν™”
gift(wedding, '영희', 5) # wedding : {'영희':5} total : 5
gift(wedding, '철수', 6) # wedding : {'영희':5,'철수':6} total : 5+6=11
gift(wedding, '이λͺ¨', 10) # wedding : {'영희':5,'철수':6,'이λͺ¨':10} total : 11+10=21
print('μΆ•μ˜κΈˆ λͺ…단 : {}'.format(wedding))


print('전체 μΆ•μ˜κΈˆ : {}'.format(total))