Learning/Python

전역변수 지역변수, 에러처리

cozy coding 2020. 8. 25. 14:05

#전역변수와 지역변수

x=10 #전역변수

def foo():

    print(x)

foo()

print(x)



def foo1():

    y=10

    print(y)

foo1()

print(y)

 

 

foo1()에서 y는 지역변수. 함수 안에서 출력할 수 있지만 바깥에선 출력하지 못함

 

 


def spam():
    eggs=99
    bacon()
    print(eggs)

def bacon():
    ham=101
    eggs=0


spam()

 

 


 

에러처리 try/Exception

#에러처리 try/Exception
def div10(num):
    try:
        return 10/num
    except:
        print("에러발생")
print(div10(2))
print(div10(0)) #에러발생
print(div10(5))