파이썬2.7 기초 공부한 것 정리
Post on 25-Jul-2015
497 Views
Preview:
TRANSCRIPT
- 무료다.
- 문법이 쉽다.
- 문장 흐름이 자연스럽고 명확하고 간결하다.
- 접착언어다.
장점4-> 사용하기에 제약이 없다.
-> 배우기 쉽다.
-> 코드를 이해하기 쉽다. 파이썬은 가장 좋은 방법 하나를 선호한다.
-> 사용 범위가 넓다.
- 하드웨어 제어가 어렵다.
- 매우 복잡하고 반복적인 연산이 어렵다.
- 따라서 OS 같은 시스템 프로그래밍이 어렵다.
- 하지만 다른 언어로 제작된 모듈을 사용할 수 있기 때문에
단점을 어느정도 극복할 수 있다.
단점3
GUI : Tkinter, wxPython, PyQT, PyGTK
Web : Flask, Django
Operation : Numeric Python
DB : pickleㄹㄹ
주요 모듈1
우분투에서
버전 확인 : $ python -V
인터프리터 실행 : $python 또는 $python3
종료 : Ctrl + D
SublimeText3
http://www.ubuntuupdates.org/ppa/sublime_3?dist=trusty
설치
- print #표준 출력- raw_input() #표준 입력- del #변수 제거 or 요소 제거 - in #들어있는지- is #맞는지- open() #파일 열기- range(0, 10, 2) #셋째인수는 간격
- type() #자료형 반환 int, float, str, list, dict, set, tuple, instance, classobj
- pow()- abs()- chr(65) #아스키 코드를 문자로- ord(‘A’) #문자를 아스키코드값으로
- dir([]) #변수가 가지고 있는 함수(동작)와 속성(상태)을 보여줍니다. (클래스 변수 포함)
- divmod(3,2) #=(1,1), 목과 나머지를 튜플로 반환
내장 함수13
- enumerate([1,2,3]) #자료구조 자료형을 인덱스와 값의 쌍을 가지는 enumerate객체로 반환합니다. for i, value in enumerate([1,2,3])과 같이 주로 for문과 함께 쓰입니다.단, dict는 keys로 만듭니다.
- eval(‘divmod(3,2)’) #실행 가능한 문자열을 실행한 결과값을 반환합니다.
- int(‘0xA’, 10) #=10int(1.1) #= 1
- hex(10) #=’0xA’, 정수->문자열- oct(10) #=’0o12’ 정수->문자열- id(1), id(a) #객체의 레퍼런스를 반환합니다.
- isinstance(obj, class) # 인스턴스가 클래스의 인스턴스인지
- list(filter(lambda x: x > 0, [1,-3,2,0,-5,6])) #시퀀스 자료형을 받아 요소들을 걸러내어 다시 리스트로 반환합니다.
내장 함수8
- lamdba a,b: a+b#= def sum(a,b): return a+b[lambda a,b:a+b, lambda a,b:a*b]
- len() #자료구조 자료형의 요소 개수를 반환합니다.
- list() #자료구조 자료형을 요소들의 순서를 지켜서 복사해서 리스트로 반환합니다. 단, dict는 keys를 리스트로 만듭니다.
- list(map(lambda e: e * 2, [1,-3,2,0,-5,6])) #시퀀스 자료형을 받아 요소들마다 첫번째 인자로 받은 함수를 수행하고 모아서 새 리스트로 반환합니다. filter()와 같은 사용방법
- min([1,2,3]), min(‘abcd’)- max([1,2,3]), min(‘abcd’)
- zip([1,2,3],[4,5,6]) #= [[1,4],[2,5],[3,6]], 요소마다 짝을 지어 새 리스트로 반환
내장 함수7
- tuple() #자료구조 자료형을 요소들의 순서를 지켜서 복사해서 튜플로 반환합니다. 단, dict는 keys로 만듭니다.
- sorted() #자료구조 자료형을 요소들을 정렬해서 새 리스트로 반환합니다. 단, dict는 = keys로 만듭니다.
- repr(‘hi’) #=”’hi’”주로 eval의 인자로 쓰입니다
- str(1) #= ‘1’
내장 함수4
자료형 - Number5,7operations
+ - * ** / // %
** : exponentiation
% : modulus
// : 나머지를 뺀 몫 연산자
data types
정수 : 1
실수 : 1.2, 0.3e-10
복소수 : 1 + 2x
8진수 : 0o12
16진수 : 0xAB
declarations(4가지)
str = “싱글라인”str = '싱글라인'str = """멀티라인입니다."""str = '''멀티라인입니다.'''
자료형 - String4문자열은 immutable
comments
'''멀티라인'''과 """멀티라인"""은 대
입연산자(=)를 사용하지 않았을 때
주석이 됩니다.
싱글라인 주석은 #내용
자료형 - String11
\b 백스페이스
\000 null문자\\ 문자 '\'\' single quote\” double quote
escaping characters
\n 개행
\v 수직탭
\t 수평탭
\r 캐리지 리턴\f 폼 피드\a eep
자료형 - Stringoperations : + *
concatenation : ‘i’ + ‘ am’ + ‘ a boy’repeating : ‘go’ * 2
indexing
‘life’[2] #=’f’‘life’[-1] #=’e’
slicing
‘life’[0:4] #=’life’
‘life’[:2] #=’li’
‘life’[2:] #=’fe’
자료형 - String7formatting(서식화)
print ‘i like %s and %s’ % (‘pizza’, ‘bulgogi’)
print '[%5s][%-5s][%.1f][%5.1f]' %
('go', 'go', 12.34, 12.34)
#=[ go][go ][12.3][ 12.3]
formatting characters
%s 문자열
%c 문자 한개%d 정수 %f 부동소수
%o 8진수%x 16진수%%문자 '%'
자료형 - String12functions
‘bssin’.upper()‘bssin’.lower()‘bssin’.count('b’) #=1‘bssin’.find(‘b’) #=0, 없으면 -1‘bssin’.index(‘b’) #=0, 없으면 에러‘,’.join(‘abc’) #=’a,b,c’‘-’.join(‘[‘a’,’b’,’c’]) #=’a-b-c’
‘ bssin ’.lstrip() #=’bssin ‘‘ bssin ’.rstrip() #=’ bssin’‘ bssin ’.strip() #=’bssin’‘bssin’.replace(‘bs’, ‘ab’)‘bs si n’.split(‘ ’) #=[‘bs’,’si’,’n’]‘Bsshin’.swapcase() #=’bSSHIN’
자료형 - Listdeclarations
list = []
list = [1, a, [2, ‘b’]]
indexing
list[-1][1] #=’b’
slicing
[1,2,3][:2] #=[1,2]
operations : + *
[1,2]+[3,4] #=[1,2,3,4]
[1,2] * 2 #=[1,2,1,2]
자료형 - List9modifications
[1,2,3][:2] = [] #=[3]
[1,2,3][:2] = [4,5] #=[4,5,3]
del list[1] #=[1,3]
functions
[‘a’,1].append(‘b’)
[‘b’,1,‘a’,2,’a’].sort() #=None
#sort()는 반환값 없기 때문
list=[‘b’,1,‘a’,2,’a’]
list.sort() #[1,2,‘a’,’a’,’b’]
list.reverse()
자료형 - Listfunctions
[‘a’,1].index(‘b’) #=에러[‘a’,1].insert(1, ’b’) #=[‘a’,’b’,1][‘a’,1].remove(1) #= 리턴값 없음[‘a’,1].pop() #= 리턴값 1[‘a’,1].pop(0) #= 리턴값 'a’[1,2,3,4,1,2].count(1) #=2[1,2].extend([3,4]) #=[1,2,3,4]
deep copy
1. new_list = old_list[:]2. new_list = list(old_list)3. from copy import copy
new_list = copy(old_list)
자료형 - Tuple2declarations
tuple = ()
tuple = (1,’a’)
tuple = 1, ‘a’
functions
index(), count()
튜플은 immutable
리스트와 사용 방법이 같습니다.
immutable이기 때문에 요소를 수정
하는 함수는 제외됩니다.
자료형 - Dictionarydeclarations
dict = {‘k1’:’v1’, ‘k2’:2, 3:’v3’}
modifications
dict[‘k4’] = 4 #={‘k1’:’v1’, ‘k2’:2, 3:’
v3’, ‘k4’:4}
del dict[‘k4’]
cautions
key값으로 리스트나 딕셔너리, 셋을 사용할 수 없습니다. 딕셔너리는 중복키를 허용하지 않는데, 리스트와 딕셔셔너리, 셋은 immutable이 아니기 때문입니다.
자료형 - Dictionaryfunctions
.keys() #키의 리스트를 반환
.values() #값의 리스트를 반환
.items() #쌍들을 튜플로 묶은 리스
트를 반환
.clear()
finding
‘key’ in dict
자료형 - Set7declarations
set1 = {‘a’,2,3}
set1 = set([‘a’,2,3])
set1 = set(‘abcda’) #= {‘a’,’b’,’c’,’d’}
operations
&(교집합), |(합집합), -(차집합)
set은 중복無 순서無
key값으로 non-immutable사용 불가
functions
.intersection()
.union()
.difference()
.add(‘1’) #1개 추가
.update([‘1’,’2’,’3’]) #여러 개 추가
.remove(‘1’) #1개 제거
.clear()
참과 거짓자료구조에 경우
차있으면 참, 비어있으면 거짓
[1,2,3], ‘hi’ #= True
[], {}, (), ‘’ #= False
List, Dict, Set, Tuple 이 네 가지 자료구조는 비교연산 시 모든 요소들의 값을 비교합니다. ->
값에 경우
0, None이 아닌 모든 값 #= True
0, None #= False
그러나 요소 중 instance타입이 있다면 그것들이 완전히 같은 값을 갖고 있다고 해도 다르게 봅니다.
변수a = 1;b = 1;a is b #=True
del a #=b변수가 제거됨.del b #=a변수가 제거됨.1의 reference count가 0이 되어 1이 메모리에서 제거됨.
del 하지 않아도 지역변수는 알아서 GC됨.
In Python, whitespace is used to structure code.
def spam():
eggs = 12 #왼쪽처럼 반드시 들여쓰기
return eggs
공백(whitespace)
조건문declarations
if expression:pass #아무 동작도 안 함
elif expression:pass
else print ‘else’
if expression: pass #한 줄짜리
comparation operators
==, !=, >, >=, <, <=, in, not in, is
logical operators
or, and, not
반복문declarations
while 1: #무한 루프pass
break절continue절
declarations
for i in 리스트:pass
for i in range(0, 10): #0,1,2, … ,9pass
for i, j, k in [[1,2,3],[4,5,6]]:print i + j + k
함수declarationsdef func(a, b):
return a + b
def no_return(a, b):pass
def no_return2(a, b):return
def two_return():return 1, 2 #=(1,2)튜플
declarations
def default_args(a, b=1, c=1):return a+b+c #correct
def default_args(a, b=1, c):return a+b+c #wrong
#SyntaxError: non-default argument follows default argument
def func(* args): for arg in args: pass
sys모듈
$python basic.py aa bb
import sysfor arg in sys.argv:
print arg#=‘basic.py’, ‘aa’, ‘bb’
입출력input
str = raw_input(‘input :’)
output
같은 결과1. print(‘i ‘ + ‘am ‘ + ‘a ‘ + ‘boy’) 2. print(‘i ” “am ” “a ” “boy”)3. print(“i”, “am”, “a”, “boy”)
file output
f = open(‘newfile.txt’, w) #r,w,a
f.write(‘new content’);
f.close()
입출력8file input
f = open(‘newfile.txt’, r)
f.readline() #=[‘line1’]
f.readlines() #=[‘line1’,’line2’, …]
f.read() #=’all data in file’
f.tell() #현재 위치
f.seek(0) #위치 이동
클래스definitionsclass Calc(Parent): #Parent는 상속할 클래스
magic_num = 10 #클래스 변수, 반시 초기화해야 합니다.__init__(self, name): #생성자를 정의했으므로 디폴트 생성자가 정의되지 않습니다.
self.name = name #self에 this객체가 들어옵니다. name은 인스턴스 변수
def set_name(self, name): #name변수 사용을 위해 반드시 먼저 name을 초기화self.name = name #생성자에서 이미 초기화하므로 사실 set_name()은 필요 없
음.
def sum(self, a, b): #클래스 함수return a + b
클래스definitionsclass Calc:
magic_num = 10__del__(self): #소멸자
print ‘i will be back’
>>> c = Calc()>>> Calc.magic_num #=c.magic_num, 클래스변수에 접근>>> del c
overriding 지원함!
overloading 지원 안 함!
operator overroading만 지원!
function overroading이 필요할 땐 var args 기능을 사용합니다.def func(* args) :
클래스16operation overloading__add__(self, other) +(이항) A + B, A += B__pos__(self) +(단항) +A__sub__(self, other) - (이항) A - B, A -= B__neg__(self) - (단항) -A__mul__(self, other) * A * B, A *= B__truediv__(self, other) / A / B, A /= B__floordiv__(self, other) // A // B, A //= B__mod__(self, other) % A % B, A %= B__pow__(self, other) pow(), ** pow(A, B), A ** B__lshift__(self, other) << A << B, A <<= B__rshift__(self, other) >> A >> B, A >>= B__and__(self, other) & A & B, A &= B__xor__(self, other) ^ A ^ B, A ^= B__or__(self, other) | A | B, A |= B__invert__(self) ~ ~A__abs__(self) abs() abs(A)
모듈usage
#def func() in mod.py
1. import modprint mod.func() #클래스도 같은 방법으로 이용
2. from mod import func print func() #또는 import *
#def func() in 외부 경로의 mod.py
import syssys.path.append(외부 경로)import mod#메인 모듈 종료 후 다시 실행하면 path가 초기화 됨.
모듈reload
import mod#이 시점에 mod모듈이 수정됨.mod.reload() #수정된 내용을 갱신print mod.func()#인터프리터로 실행 중일 때 유용#인터프리터가 재실행 되면 당연히 자동 갱신
#import를 한 번 더 호출해도 갱신 안 됨.
testing
if __name__ ==’__main__’
#이 모듈(파일)의 테스트 구문
#이 모듈을 import해서 사용하는 경우에는 위에 if문이 False가 되기 때문에 테스트용도로 사용합니다.
from 뒤엔 패키지 또는 모듈만 올 수 있습니다.
import 방법1. import 패키지.패키지.모듈 #안 되는 듯2. from 패키지.패키지 import 모듈 #모듈 사용3. from 패키지.패키지.모듈 import 함수, 변수 등 #
모듈 내에서 import로 지정한 것을 사용4. from 패키지.패키지.모듈 import * # 모듈 내 모든
것 사용5. from 패키지.패키지 import * #패키지 내 모든 모
듈 사용, 단 해당 패키지의 __init__.py에 __all__ = ['모듈']이 기록되어 있아야 함.
패키지pakage_a/
__init__.pydir_a/
__init__.pygogo.py
dir_b/__init__.pysoso.py
__init__.py : 해당 디렉토리가 패키지의 일부림을 알려는 역할
from ..패키지 import 모듈 #..은 상위 디렉토리, 즉 relative 패키지
try: 4 / 0 except ZeroDivisionError as e: print(e)
try: raise NotImplementedErrorexcept NotImplementedError as e: print(e)
예외 처리FileNotFoundError: [Errno 2] No such file or directory:
ZeroDivisionError: division by zero
IndexError: list index out of range
import osos.environos.environ[‘PATH’]os.chdir(‘/home/bssin’)os.getcwd()os.system(‘system command’)os.popen() ??os.mkdir()os.rmdir()os.unlink(‘filename’) #delete fileos.rename(‘src’, ‘dst’)
import shutil shutil.copy("src", "dst")
외장 함수import syssys.argvsys.exit()sys.pathsys.path.append()
import picklepickle.dump(data, f)data = pickle.load(f)
import iof = io.StringIO()f.write(“aaa”), value = f.getvalue()f.close()
등등등…
import randomimport globimport tempfileimport timeimport datetimeimport calendarimport _theadimport webbrowser
top related