2019-11-10
약 1년전에 Python 공부를 했었다.
링크: http://b1ix.net/358

하지만, 최근 1년간 Python으로 프로젝트를 할 일이 없었고, 결과적으로 Python에 대해서 거의 까먹고 말았다.
그래도 이미 한번 공부 했던거라서, 반나절 정도 책을 보니, 기초 문법은 금방 숙지 할 수 있었다.
그렇지만, 이미 까먹은 선례가 있어서, 다음에 까먹었을 때는 조금 더 빠른 습득을 할 수 있게 하기 위해서, 여기에 기초 문법을 정리해 놓는다.


참고링크: 파이선으로 배우는 알고리즘 트레이닝

변수할당
- id() 함수: 메모리에 할당된 객체의 주소값(정확히는 주소가 아님) 출력
- 256까지는 같은 id값이 할당됨
>>> a=100
>>> b=100
>>> c=10000
>>> d=10000
>>> id(a),id(b),id(c),id(d)
(1695014688, 1695014688, 56810976, 56811120)
문자열
>>> string1 = "Helllo World"
>>> string1
'Helllo World'
>>> print(string1)
Helllo World
>>> len(string1)
12
>>> string1[0:6]
'Helllo'
>>> string1[:6]
'Helllo'
>>> string1[7:]
'World'
>>> string1[:-5]
'Helllo '
>>> string1[-5:]
'World'
>>> string1[:-6]
'Helllo'
>>> string1[-7:-3]
'o Wo'
>>> string1[-5:-1]
'Worl'
>>> string1.split(' ')
['Helllo', 'World']
>>> string1.split(' ')[0]
'Helllo'
>>> s = string1.split(' ')
>>> print(s)
['Helllo', 'World']
>>> print(s[1])
World
>>> string1 + ' '+ s[1]
'Helllo World World'
type
>>> type(395)
<class 'int'>
>>> type(3.14159)
<class 'float'>
>>> type('helllo')
<class 'str'>
>>> type(True)
<class 'bool'>
리스트
>>> list1 = ['one', 2, 3, 'four', 'five']
>>> list1
['one', 2, 3, 'four', 'five']
>>> list1[3]
'four'
>>> list1[-2]
'four'
>>> list1[1:2]
[2]
>>> list1[1:]
[2, 3, 'four', 'five']
>>> list1[1:3]
[2, 3]
>>> list1[:-3]
['one', 2]
>>> list1[0:3]
['one', 2, 3]
>>> list1[3:1]
[]
>>> list1[-2:-4]
[]
>>> list1[-2:-1]
['four']
>>> list1[-5:-3]
['one', 2]
>>> list1[-4:-2]
[2, 3]
>>> list1[1:-1]
[2, 3, 'four']
>>> list1.append(6)
>>> list1
['one', 2, 3, 'four', 'five', 6]
>>> list1.insert(3,4)
>>> list1
['one', 2, 3, 4, 'four', 'five', 6]
>>> del list1[3]
>>> list1
['one', 2, 3, 'four', 'five', 6]
>>> del list1[-1]
>>> list1
['one', 2, 3, 'four', 'five']
>>> list1[0] = 1
>>> list1
[1, 2, 3, 'four', 'five']
튜플 - 리스트는 [], 튜플은 () - 단, 한번 정한 원소들을 변경 할수가 없다. - 대신 리스트보다 속도가 빠르다
>>> tuple1 = ('one', 2, 'three')
>>> tuple1[1]
2
>>> tuple1[1] = 'two'
Traceback (most recent call last):
  File "<pyshell#107>", line 1, in <module>
    tuple1[1] = 'two'
TypeError: 'tuple' object does not support item assignment
>>> 
딕션너리(dictionary)
>>> dictionary1 = {'one':1, 2:'two', 3:'three', 'four':4}
>>> dictionary1
{'one': 1, 2: 'two', 3: 'three', 'four': 4}
>>> dictionary1['5'] = 5
>>> del dictionary1[2]
>>> dictionary1
{'one': 1, 3: 'three', 'four': 4, '5': 5}
>>> len(dictionary1)
4
>>> dictionary1.keys()
dict_keys(['one', 3, 'four', '5'])
>>> dictionary1.values()
dict_values([1, 'three', 4, 5])
>>> dictionary1.items()
dict_items([('one', 1), (3, 'three'), ('four', 4), ('5', 5)])
>>> 1 in dictionary1.keys()
False
>>> 3 in dictionary1.keys()
True
if문
>>> a = 100
>>> if a > 100:
	print('a > 100')
elif a == 100:
	print('a == 100')
else:
	print('a < 100')


a == 100
>>>
>>> if a >= 100 and bool(a):
	print(a)


100
for문
>>> list2 = ['a', 'b', 'c']
>>> for i in list2:
	print( 'alphabet: %s' % i)


alphabet: a
alphabet: b
alphabet: c
>>> for i, value in enumerate(list2):
	print( i, value )


0 a
1 b
2 c
>>> for i in list("helllo"):
	print(i)


h
e
l
l
l
o
>>> for i in range(1, 3):
	print(i)


1
2
>>> dictionary2 = { 'a':10, 'b':20, 'c':30}
>>> for k,v in dictionary2.items():
	print("key: %s, value: %s" % (k, v))


key: a, value: 10
key: b, value: 20
key: c, value: 30
while문
>>> i = 1
>>> while i <= 3:
	print(i)
	i = i+1


1
2
3
>>> i = 1
>>> while 1:
	print(i)
	i = i+1
	if( i > 4 ):
		break
	else:
		continue


1
2
3
4
함수 - 내장함수: https://docs.python.org/ko/3/library/functions.html
>>> def add(a,b):
	return a+b

>>> print( add(10,20))
30
>>> def cal(a,b):
	return (a+b, a-b)

>>> (a,b) = cal(30, 10)
>>> print(a, b)
40 20
전역변수
>>> i = 10
>>> # 지역범위에서 전역변수 사용시 global로 선언 해주어야 함
>>> def i_print():
	global i
	print(i)


>>> i_print()
10
>>> i = 12354
>>> i_print()
12354
모듈
>>> __name__
'__main__'
>>> if( __name__ == "__main__" )
SyntaxError: invalid syntax
>>>
>>>
>>> if( __name__ == "__main__" ):
	print("import가 아닌 직접 실행된 상태")


import가 아닌 직접 실행된 상태
>>>
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> import time
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'time']
>>>
>>> time.time()
1573448287.213396
>>> time.ctime()
'Mon Nov 11 13:58:15 2019'
>>> type(time)
<class 'module'>
>>>
>>> import os
>>> # 현재 파일 위치
>>> os.getcwd()
'C:\\ProgramData\\Anaconda3\\Lib\\idlelib'
>>>
>>> import sys
>>> #모듈 위치 - 해당 위치에 모듈을 생성하면 import 가능
>>> sys.path
['', ..... , 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin']
>>>
>>> # 모듈 위치 추가
>>> sys.path.append( os.getcwd() + '\\modules')
>>> sys.path
['', ..... , 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin', 'C:\\ProgramData\\Anaconda3\\Lib\\idlelib\\modules']
>>>
>>> # 별칭
>>> import os as winOS
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os', 'sys', 'time', 'winOS']
>>>
>>> # 특정 함수만 import 하기
>>> from os import getcwd as osGetcwd
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os', 'osGetcwd', 'sys', 'time', 'winOS']
>>>
>>> osGetcwd
<built-in function getcwd>
>>> osGetcwd()
'C:\\ProgramData\\Anaconda3\\Lib\\idlelib'
클래스
>>> class aaa:
	def __init__(self, a, b):
		self.a = a
		self.b = b
		self.c = 10
	def add(self):
		return self.a + self.b
	def id_print(self):
		print( id(self) )
	def __del__(self):
		pass


>>> class1 = aaa(10,30)
>>> class1.add()
40
>>> # 참조 방식
>>> class1.id_print()
57126224
>>> id(class1)
57126224
>>> aaa.id_print(class1)
57126224
>>>
>>> class2 = aaa(30,40)
>>> class1.c
10
>>> class2.c
10
>>> class1.c = 100
>>> class1.c
100
>>> class2.c
10
>>> # 상속
>>> class bbb(aaa):
	def __init__(self):
		aaa.__init__(self, 10, 20)


>>> class3 = bbb()
>>> class3.add()
30
>>> class3.c
10
파일
>>> f = open("test.txt", 'w')
>>> f.writelines(['aaa\n', 'bbb\n'])
>>> f.write('ccc')
3
>>> f.close()
>>> f = open("test.txt", 'r')
>>> for i in f.readlines():
	print(i)


aaa

bbb

ccc
>>> f.readlines()
[]
>>> # 파일 인덱스 0으로 만들기
>>> f.seek(0)
0
>>> f.readlines()
['aaa\n', 'bbb\n', 'ccc']