파이썬 기본 문법을 정리해보았습니다.
  기존에 개발을 해 보신 분들이, 예제를 통해 대략적으로 파이썬 기본 문법을 파악하기 위한 용도입니다.
  따라서, 긴 설명 없이 항목 별 예제를 중심으로 정리하였으며, 추가적인 설명이 필요한 경우에만 간략하게 정리하였습니다.

  각 '주제'를 클릭하면 관련 내용이 명시된 파이썬 자습서 홈페이지로 이동합니다.

 


 

파이썬 인터프리터

  - 대화형 모드로 동작

 

 


문자열 연산 : 불변

# 문자열 연산
>>> word = 'Python'
>>> word[0]
'P'
>>> word[-2]
'o'
>>> word[:2]
'Py'
>>> word[2:5]
'tho'
>>> 3 * word[0] + word[1:4] + '~~~' + word[4:]
'PPPyth~~~on'
>>> len(word)
6

 

 


if 문

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...         x = 0
...         print('Negative changed to zero')
...     elif x == 0:
...         print('Zero')
...     elif x == 1:
...         print('Single')
...     else:
...         print('More')
...
More

 

for 문

>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...         print(w, len(w))
...
cat 3
window 6
defenestrate 12
>>> for n in range(2, 10):
...         for x in range(2, n):
...             if n % x == 0:
...                 print(n, 'equals', x, '*', n//x)
...                 break
...         else:
...             print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

 

 


리스트 연산

  - Compound 데이터 타입 중 대표적
  - 가변인 시퀀스형
  - 대괄호나 list 함수를 이용하여 생성

>>> squares = [1, 4, 9, 16]
>>> squares 
[1, 4, 9, 16]
>>> squares[2]
9
>>> squares + [36, 49]
[1, 4, 9, 16, 36, 49]
>>> squares.append(50)
>>> len(squares)
5
>>> x = [squares, squares]
>>> x[0]
[1, 4, 9, 16, 50]
>>> x[0][1]
4
>>> lst = list('abcde')
>>> lst
['a', 'b', 'c', 'd', 'e']

 

 

리스트 메소드

append(x) 리스트의 끝에 항목 추가. a[len(a):] = [x] 와 동일.
extend(iterable) 리스트의 끝에 이터러블의 모든 항목을 추가. a[len(a):] = iterable 와 동일
insert(i, x) 주어진 위치에 항목을 삽입. 첫 번째 인자는 삽입 위치(인덱스). 두 번째 인자는 삽입할 값.
a.insert(len(a), x)와 a.append(x) 와 동일함.
remove(x) 리스트에서 값이 x첫 번째 항목을 삭제.
pop([i]) 리스트에서 주어진 위치에 있는 항목을 삭제하고, 그 항목을 return.
인덱스를 지정하지 않으면
리스트의 마지막 항목을 삭제하고 return.
clear() 리스트의 모든 항목을 삭제. del a[:] 와 동일
index(x[, start[, end]]) 리스트에 있는 항목 중 값이 x 와 같은 첫 번째 항목의 인덱스를 return.
count(x) 리스트에서 x 의 전체 건수를 return.
list.sort(key=None, reverse=False) 리스트의 항목을 정렬.
reverse() 리스트의 요소의 순서를 역으로 변경.
copy() 리스트의 사본 반환. a[:] 와 동일.

 

 

리스트 컴프리헨션 (Comprehension)

>>> squares = [x**2 for x in range(10)] 
>>> squares 
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = list(map(lambda x: x**2, range(10))) 
>>> squares 
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = [] 
>>> for x in range(10): 
...        squares.append(x**2)
... 
>>> squares 
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

 

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
>>> combs = [] 
>>> for x in [1,2,3]: 
...         for y in [3,1,4]: 
...             if x != y: 
...                  combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

 

>>> matrix = [
...         [1, 2, 3, 4],
...         [5, 6, 7, 8],
...         [9, 10, 11, 12],
... ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> transposed = []
>>> for i in range(4):
...          transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> transposed = []
>>> for i in range(4):
...         transposed_row = []
...         for row in matrix:
...             transposed_row.append(row[i])
...         transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

 

>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

 

튜플

  - 불변인 시퀀스형.
  - 괄호나 tuple 함수를 사용하여 생성.

>>> tu = 12345, 54321, 'hello!'
>>> tu
(12345, 54321, 'hello!')
>>> tu[0]
12345
>>> v1, v2, v3 = tu
>>> v1
12345
>>> v2
54321
>>> v3
'hello!'
>>> tu = tuple('abcde')
>>> tu
('a', 'b', 'c', 'd', 'e')

 

집합

  - 중복 없는 유일한 값들이 순서에 상관없이 저장되는 컬렉션.
  - 중괄호{}나 set() 함수를 사용하여 생성.

>>> chr1 = {'a', 'z', 'z', 'r', 'd', 'j', 'd'}
>>> chr1
{'j', 'd', 'r', 'z', 'a'}
>>> chr2 = set('arojxg')
>>> chr2
{'j', 'o', 'g', 'r', 'x', 'a'}
>>> chr1 - chr2
{'z', 'd'}
>>> chr1 & chr2
{'j', 'r', 'a'}
>>> chr1 | chr2
{'j', 'o', 'd', 'x', 'r', 'z', 'g', 'a'}
>>> chr1 ^ chr2
{'o', 'x', 'd', 'z', 'g'}

 

>>> a = {x for x in 'abracadabra' if x not in 'abc'} 
>>> a 
{'r', 'd'}

 

 

딕셔너리

  - 매핑 데이터 형. 가변형 임.
  - {키:값} 쌍의 형태로 관리되며, 키로 인덱싱함.
  - 중괄호{}나 dict() 함수를 사용하여 생성. 

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> list(tel)
['jack', 'sape', 'guido']
>>> sorted(tel)
['guido', 'jack', 'sape']

 

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

 

 


사용자 함수 

>>> def fib(n): 
...        """Print a Fibonacci series up to n. <-- Docstring"""
...         a, b = 0, 1 
...         while a < n: 
...             print(a, end=' ') 
...              a, b = b, a+b 
...         print() 
... 
>>> 
>>> fib(2000) 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>> def fib2(n, a=0, b=1): 
...          """Return a list containing the Fibonacci series up to n.""" 
...          result = [] 
...          n1, n2 = a, b 
...          while n1 < n:
...               result.append(n1)
...               n1, n2 = n2, n1+n2 
...          return result 
... 
>>> f100 = fib2(100) 
>>> f100 
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> def cheeseshop(kind, *arguments, **keywords): 
...         print("-- Do you have any", kind, "?") 
...         print("-- I'm sorry, we're all out of", kind) 
...         for arg in arguments: 
...             print(arg) 
...         print("-" * 40) 
...         for kw in keywords: 
...             print(kw, ":", keywords[kw]) 
...
>>> cheeseshop("Limburger", "It's very runny, sir.", 
           "It's really very, VERY runny, sir.", 
           shopkeeper="Michael Palin", 
           client="John Cleese", 
           sketch="Cheese Shop Sketch") 
-- Do you have any Limburger ? 
-- I'm sorry, we're all out of Limburger 
It's very runny, sir. 
It's really very, VERY runny, sir. 
---------------------------------------- 
shopkeeper : Michael Palin 
client : John Cleese 
sketch : Cheese Shop Sketch

 

 


모듈

  - 함수, 클래스, 변수가 저장된 파일. import 하여 사용.
  - 파일명 형식 : [패키지명\]모듈명.py
  - 모듈 검색 경로
     1) 내장 모듈 검색
     2) sys.path
        . 입력 스크립트를 포함하는 디렉터리 (또는 파일이 지정되지 않았을 때는 현재 디렉터리).
        . PYTHONPATH (디렉터리 이름들의 목록, 셸 변수 PATH 와 같은 문법).
        . 설치 의존적인 기본값

${PYTHONPATH}\pkg\fibo.py
# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

if __name__ == "__main__":  #__main__ : executed by script
    import sys 
    fib(int(sys.argv[1]))

 

 

# 패키지명 : pkg, 모듈명 : fibo

>>> import pkg.fibo
>>> pkg.fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> pkg.fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> pkg.fibo.__name__
'pkg.fibo'
>>> from pkg.fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>> fib2(50)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

 - 모듈을 스크립트로 실행

D:\90_Workspace_Python\pkg>python fibo.py 50

 

 


클래스

  - 파이썬 클래스는 객체 지향형 프로그래밍의 모든 표준 기능들(클래스 상속, 매서드 재정의 등)을 제공

${PYTHONPATH}\myclass.py
class MyClass:

    def __init__(self, msg):
        print("Init message of MyClass")
        self.__msg = msg

    def setmsg(self, msg):
        self.__msg = msg
    
    def printmsg(self):
        print(self.__msg)
    
    def getmsg(self):
        return self.__msg


class MyClassSub(MyClass):

    def __init__(self, msg):
        print("Init message of MyClassSub")
        super().__init__(msg)
    
    def printmsg(self):
        print("Message is \"{}\"".format(super().getmsg()))

>>> from myclass import MyClass, MyClassSub
>>> m = MyClass('test...')
Init message of MyClass
>>> m.printmsg()
test...
>>> m.getmsg()
'test...'
>>> m.setmsg('new message')
>>> m.printmsg()
new message
>>> m.getmsg()
'new message'
>>> ms = MyClassSub('Sub Message')
Init message of MyClassSub
Init message of MyClass
>>> ms.printmsg()
Message is "Sub Message"
>>> ms.getmsg()
'Sub Message'

  - __init()__ : 클래스의 생성자 실행 시 자동으로 init__() 를 호출. 

 

 


입출력

  - 포맷 문자열 리터럴(formatted string literal) 또는 f-문자열 (f-string)
     . 'f' 나 'F' 를 앞에 붙인 문자열 리터럴
     . 치환 필드 포함 가능
     . 중괄호 {} 로 구분되는 표현식
     . 실행시간에 계산되는 표현식

>>> year = 2020
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2020 Referendum'
>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...         print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack        ==>       4098
Dcab       ==>       7678
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
>>> print('This {food} is {adjective}.'.format(
...     food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))
The story of Bill, Manfred, and Georg.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...            'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
>>> for x in range(1, 6):
...         print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...         print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125

 

 

파일 입출력

  - open(filename, mode)
    . mode : r (readonly, 기본 값), w (writeonly), a (append), r+ (read and write), b (binary mode)

>>> f = open('d:\\testfile', 'r+')
>>> read_data = f.read()
>>> read_data
'This is the first line of the file.\nSecond line of the file\n'
>>> f.readline()
''
>>> f.seek(0)
0
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
>>> f.write('This is a test\n')
15
>>> f.seek(0)
0
>>> f.read()
'This is the first line of the file.\nSecond line of the file\nThis is a test\n'
>>> f.closed
False

 

 


예외 처리

>>> import sys
>>>
>>> try:
...         f = open('myfile.txt')
...         s = f.readline()
...         i = int(s.strip())
... except OSError as err:
...         print("OS error: {0}".format(err))
... except ValueError:
...         print("Could not convert data to an integer.")
... except:
...         print("Unexpected error:", sys.exc_info()[0])
...         raise
...
OS error: [Errno 2] No such file or directory: 'myfile.txt'

 

 

 


파이썬 스타일 가이드

 

PEP 8 -- Style Guide for Python Code

The official home of the Python Programming Language

www.python.org

 

  • 들여쓰기 단위 : 공백 4칸. 탭 사용 불가.

  • 한 줄 길이 : 최대 79자.

  • 함수, 클래스, 함수 내의 큰 코드 블록 사이는 빈 줄을 넣어 구분.

  • 가능하다면, 주석은 별도의 줄로 입력.

  • DocString 사용을 권장.

  • 연산자들 앞/뒤와 콤마 뒤에는 공백 입력.
    괄호 바로 안쪽에는 공백 불가.
    예) a = f(1, 2) + g(3, 4)

  • 명명 규칙
    . 상수 : UPPER_CASE_WITH_UNDERSCORES.
    . 패키지 : 짧은 소문자 이름 권고. 밑줄은 사용 불가.
    . 모듈 : 짧은 소문자 이름 권고. 밑줄은 사용가능하지만 지양할 것.
    . 클래스 : UpperCamelCase.
    . 함수와 메소드 : lowercase_with_underscores.
    . 메소드의 첫 번째 인수는 항상 self를 사용.
    . 클래스 메소드의 첫 번째 인수에는 항상 cls를 사용.

  • 파이썬의 배포판 코드는 항상 UTF-8이나 파이썬2의 ASCII를 사용할 것.

 

[Ref.] https://docs.python.org/ko/3/tutorial/index.html
        https://docs.python.org/3/tutorial/index.html

 

+ Recent posts