본문 바로가기

Python/Python Basic

Day4) 2. multiple return(복수 값 반환) & variable scope(변수의 범위)

multiple return(복수 값 반환)

- tuple반환을 하여 복수개의 값 리턴 가능

- 부득이한 경우가 아니면 지양

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def add_sub(a, b):
    return a+b, a-b
 
def add(a, b):
    return a + b
 
def sub(a, b):
    return a - b
 
= add_sub(45)
e, f = add_sub(45)
print type(c), c
print e, f
 
<<<<< 실행결과 >>>>>
 
<type 'tuple'> (9-1)
9 -1
 
cs



variable scope(변수의 범위)

- 변수가 참조 가능한 코드상의 범위를 명시

- 함수내의 변수는 자신이 속한 코드 블록이 종료되면 소멸됨

- 이렇게 특정 코드 블록에서 선언된 변수를 지역변수(local variable)이라고 함

- 반대로 가장 상단에서 정의되어 프로그램 종료 전까지 유지되는 변수를 전역변수(global variable)이라고 함

- 같은 이름의 지역변수와 전역변수가 존재할 경우, 지역변수의 우선순위가 더 높음

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def f(): 
    s = 'java'
    print s # 지역변수 s를 출력
    
= "Python"
 
f()
 
<<<<< 실행결과 >>>>>
 
java
 
=================================
 
del s # 아래 예제를 위해 전역 변수 s 삭제
 
def f(): 
    s = "Perl" # 로컬 변수 생성
    print(s) 
 
f()
 
print s 
# s는 함수f의 지역변수였기 때문에 함수가 종료되면서 scope이 종료되어 사라짐, 따라서 오류 발생
 
<<<<< 실행결과 >>>>>
 
Perl
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-38-107e5c5e727d> in <module>()
      5 f()
      6 
----> 7 print s
      8 # s는 함수f의 지역변수였기 때문에 함수가 종료되면서 scope이 종료되어 사라짐, 따라서 오류 발생
 
NameError: name 's' is not defined
 
cs


1
2
3
4
5
6
7
8
9
10
def f():
    print s 
    
= 'Python'
 
f()
 
<<<<< 실행결과 >>>>>
 
Python
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def f(): 
    print 'test'
    
    # 한 scope 내에 동시에 글로벌 변수와 로컬 변수가 존재 하는 경우 에러 발생
    print s # 여기서는 전역변수
    s = "Perl"
    print s # 지역변수
 
= "Python" 
 
f()
 
<<<<< 실행결과 >>>>>

test
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-43-420fbccc6bea> in <module>()
      9 s = "Python"
     10 
---> 11 f()
 
<ipython-input-43-420fbccc6bea> in f()
      3 
      4     # 한 scope 내에 동시에 글로벌 변수와 로컬 변수가 존재 하는 경우 에러 발생
----> 5     print s # 여기서는 전역변수
      6     s = "Perl"
      7     print s # 지역변수
 
UnboundLocalError: local variable 's' referenced before assignment
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def f():
    global s # 명시적으로 global variable 임을 명시 해야 함
    print s
    s = "dog" # 지역변수가 아닌, 전역변수가 인식 (새로운 변수를 만드는 것이 아닌 전역변수에 새로운 값 대입)
    print s 
    
= "cat" 
print s
 
f()
print s
 
<<<<< 실행결과 >>>>>
 
cat
cat
dog
dog
cs



반응형