코드 작성할 때마다 구글검색하기 귀찮으니 한 곳에서 보고 해결하자.
❗ 특정 코드만 작성 예정. 구글 검색할 때마다 추가.
❗ Ctrl + F 로 검색
❗ 코드 부분의 >는 결과를 나타내는데 사용함.
변수, 문자, 상수라는 자료형 존재.
숫자와 문자열의 차이를 알기 때문에 숫자와 문자의 합은 불가능
자료 타입 확인하는 방법: type()
type("hello")
#str, 문자열
type('k')
#chr, 문자
type(1)
#int, 정수
type(1.0)
#float, 실수 (double 존재x)
*) 메서드 확인: dir()
x = list()
dir(x)
me = input('who? ')
print('hi', me)
num = input("number: ")
print("number is", num)
# 내가 입력한 숫자 값 그대로 안나옴
num = input("number: ")
num = float(num) #자료형 변환 필요
print("number is", num)
x = 5
#if
if x == 5 :
print('equal')
if x != 5 :
print('not equal')
print('not equal')
#if, else
if x == 5 :
print('equal')
else :
print('not')
#if, elif, else
if x > 6 :
print('more than six')
elif x > 3 :
print(' more than three')
else :
print('other')
#1 try, except만
try:
...
except:
...
#예시)
aa = 'hello'
try:
aa1 = int(aa)
except:
aa1 = -1
#2 발생오류와 오류 메세지 변수 추가
try:
...
except 발생오류:
...
try:
...
except 발생오류 as 오류 메세지 변수:
...
#예시)
try:
3/0
except ZeroDivisionError as e:
print(e)
> 결과: division by zero
예외 종류 | |
---|---|
SyntaxError | 잘못된 문법 |
NameError | 참조변수 없음 |
ZeroDivisionError | 0으로 나눌 수 없음 |
IndexError | 인덱스 범위 벗어남 |
ValueError | 참조 값이 없음 |
KeyError | 키 없음 에러 |
AttributeError | 모듈, 클래스의 잘못된 속성 사용함 |
FileNotFoundError | 파일 못 찾음 |
TypeError | 타입 안 맞음 |
참고) 점프 투 파이썬, https://hleecaster.com/python-exception/
함수 만들기
def 함수이름([매개변수[=초기값], ...]):
...
return 반환값 #반환값없으면 return 안써도 됨.
예시)
def maxnumber(a,b):
if a < b :
return b
else :
return a
print(maxnumber(3,5))
> 5
n=3
while n > 0 :
print(n)
n -= 1
print("end")
>3
2
1
end
while true:
line = input("! ")
if line == "done" :
break
print(line)
print("end!!")
>! hello
hello
! done
end!!
while true:
line = input("! ")
if line[0] == "#" :
continue
if line == "done" :
break
print(line)
print("end!!")
>! hello
hello
! #print
! haha
haha
! done
end!!
#1)
for i in [3,2,1] :
print(i)
print("end!!")
>3
2
1
end!!
#2)
friends = ["aa", "bb", "cc"]
for i in friends :
print("hello", i)
print("end!!")
>hello aa
hello bb
hello cc
end!!
for i in range(3,0,-1) :
print(i)
print("end!!")
>3
2
1
end!!
aa = [9, 41, 12, 3, 74, 15]
maxVal = aa[0]
for i in range(1,len(aa)) :
if aa[i] > maxVal :
maxVal = aa[i]
print(maxVal)
smallest = None
for i in [9, 41, 12, 3, 74, 15] :
if smallest is None :
smallest = i
elif i < smallest :
smallest = i
print("small value:",smallest)
None
최솟값 찾기의 첫 줄에 적힌 None은 문자열이 아닌 None 자료형이다.
이는 공백을 나타내기 위해 쓰이며 상수이다. (존재하지않는다라는 뜻 아님)
is와 is not 연산자
is 연산자는 ==와 비슷한 역할을 하지만 ==보다 강력하다.
자료형과 값의 동등성을 요구하기 때문이다.
예시)
0 == 0.0 -> True
0 is 0.0 -> False
.
count = 0
sum = 0
while True :
num = input("Enter a number: ")
if num == "done" :
break
try :
num = int(num) #문자열 정수로 변환시 에러발생
except :
print("Invalid input")
continue # 코드 마저 실행 위해, 안쓰면 에러남
else :
count += 1
sum += num
avg = float(sum/count)
print(sum, count, avg)
fruit = 'apple'
print(len(fruit))
> 5
인덱스는 0부터 시작, len()-1이 마지막임!
즉, apple의 경우 apple[4]을 출력하면 e가 나옴
문자열 크기를 넘어 인덱스 접근시 에러 발생
즉, apple[5] 출력시 에러발생
.
while과 for 차이
fruit = 'banana'
index = 0
while index < len(fruit) :
...
fruit = 'banana'
for i in fruit :
...
fruit = 'apple'
'a' in fruit
-> True
'x' in fruit
-> False
슬라이싱(slicing)은 잘라낸다의 의미로 :(콜론)을 이용해 문자열의 특정 구간만 가져올 수 있다. (리스트도 가능)
a = 'Happy_Birthday'
print(a[0:5])
>Happy #인덱스 0~4(5-1)까지 출력됨.
print(a[11:12])
>d #두 번째 숫자-1 까지 출력하므로 11번째에 해당하는 d가 출력됨.
print(a[6:20])
>Birthday
a = 'Happy_Birthday'
print(a[:5])
>Happy
print(a[6:])
>Birthday
print(a[:])
>Happy_Birthday
+연산자를 문자열에 적용시 병합 의미
1) ,(콤마) 사용
a = "New"
print(a, "York")
>New York
2) + 사용
a = "New"
print(a + "York")
>NewYork
print(a + " " + "York")
>New York
문자열도 연산자 이용해 비교 가능.
if word == 'cat':
print('right!')
elif word < 'cat' :
print('your word(' + word + ') comes before cat')
else :
print('your word(' + word + ') comes after cat')
문자열.함수() 형태로 사용
함수이름 | |
---|---|
lower() | 문자열을 모두 소문자로 바꾼다. |
upper() | 문자열을 모두 대문자로 바꾼다. |
startswith(value,start,end) | 문자열내에서 value가 처음으로 나오면 True, 아니면 False를 반환한다. |
endswith(value,start,end) | 문자열내에서 value가 마지막으로 나오면 True, 아니면 False를 반환한다. |
find(value,start,end) | 문자열에서 처음 검색되는 value의 위치 반환한다. |
replace(old, new) | 문자열에서 모든 old를 new로 바꾼다. |
strip() | 문자열 왼쪽과 오른쪽에 있는 모든 공백을 제거한다. |
lstrip() | 문자열 왼쪽에 있는 모든 공백을 제거한다. |
rstrip() | 문자열 오른쪽에 있는 모든 공백을 제거한다. |
핸들 = open(파일명, 모드)
핸들 출력시 다음과 같이 출력됨.
rfile = open('member.txt','r')
print(rfile)
><_io.TextIOWrapper name = 'member.txt' ···>
모드명 | |
---|---|
'r' | 읽기모드 |
'w' | 쓰기모드 |
'a' | 추가모드(파일의 마지막에 새로운 내용 추가할때 사용, 파일이 없으면 생성) |
#한 줄씩 읽기
rfile = open('member.txt','r')
for line in rfile:
print(read)
> without haste, but without rest
do one thing everyday that scares tou
by falling, we learn to walk safely
fake it till you make it
dread is a moment
위와 같이 한 줄당 줄바꿈이 2번씩 들어가 있음.
각 줄 끝에 있는 개행 문자와 print에 들어가 있는 개행 문자 때문임.
따라서 각 줄 끝에 있는 개행 문자 삭제 필요.
#한 줄씩 읽기, rstrip()
rfile = open('member.txt','r')
for line in rfile:
line = line.rstrip()
print(read)
> without haste, but without rest
do one thing everyday that scares tou
by falling, we learn to walk safely
fake it till you make it
dread is a moment
#전체 읽기
rfile = open('member.txt','r')
rfile.read()
여러 개의 값을 하나의 변수에 담을 수 있다. 즉, 변수 안에 공간을 여러 개 가질 수 있다. 컬렉션에는 리스트, 딕셔너리가 포함된다.
list1 = ['red', 'yellow', 'green']
list2 = ['red', 24, 12.5]
list3 = [1, [3, 4], 7]
list4 = []
문자열은 내용을 변경할 수 없다.
그러나 리스트는 인덱스를 이용해 리스트 요소 변경 가능하다.
#문자열
color = 'yeliow'
color[3] = 'l' #에러, 변경 불가능
#리스트
color2 = ['red', 'yellow', 'green']
color2[1] = 'blue' # 변경 가능
문자열과 마찬가지로 리스트 길이도 len함수를 이용해 구할 수 있다.
문자열의 경우 문자열의 길이를 나타내고 리스트는 원소 개수를 나타낸다.
#문자열
color = 'yellow'
print(color.len())
>6
#리스트
color2 = ['red', 'yellow', 'green']
print(color2.len())
>3
a = [1, 2, 3]
b = [3, 4, 5]
print(a+b)
>1, 2, 3, 3, 4, 5
list1 = list()
list1.append('book')
list1.append(23.4)
print(list1)
>['book', 23.4]
list1.append('movie')
print(list1)
>['book', 23.4, 'movie']
리스트 안에서는 순서가 유지되고 새로 추가한 원소는 끝에 더해진다.
num = [2,5,3,1,8]
num.sort()
print(num)
>[1,2,3,5,8]
word = 'fake it till you make it'
spl = word.split()
print(spl)
>['fake', 'it', 'till', 'you', 'make', 'it']
print(len(spl))
>6
print(spl[3])
>you
for i in spl :
print(i)
>fake
it
till
you
make
it
split메서드의 default 구획 문자는 공백임.
여러 칸의 공백도 하나의 구획 문자로 여김.
문장을 나눌 때 어떤 구획 문자를 사용할지 정할 수 있음.
num = 'first;second;third'
thing = num.split()
print(thing)
>['first;second;third']
thing = num.split(';')
print(thing)
>['first', 'second', 'third']
#딕셔너리
dic = dict() # 빈 딕셔너리 생성, dic = {}도 가능
dic['apple'] = 5
dic['cherry'] = 8
dic['orange'] = 2
print(dic)
>{'cherry' : 8, 'apple' : 5, 'orange' : 2}
aa = {}
print(aa['hello'])
> error발생
'hello' in aa
> False
count = dict()
name = ['aa', 'bb', 'aa', 'dd', 'bb']
for i in name :
if i not in count :
count[i] = 1 #없으면 빈도 1
else :
count[i] = count[i] + 1 # 있으면 빈도 + 1
print(count)
>{'dd' : 1, 'bb' : 2, 'aa' : 2}
딕셔너리 안에 찾고자 하는 키가 있는지 확인하고 없다면 기본값을 대신 가져오게 할 수 있다.
count = dict()
name = ['aa', 'bb', 'aa', 'dd', 'bb']
for i in name :
count[i] = count.get(i, 0) + 1
#i에 해당하는 키 값이 있으면 해당 값 +1, 없으면 기본값인 0 +1
print(count)
>{'dd' : 1, 'bb' : 2, 'aa' : 2}
1) 키만, 2) 값만, 3) 키와 값 쌍으로 얻는 방법
a = {'name' : 'sue', 'num' : 123, 'birth' : '0531'}
# 1)키 리스트로 얻기
print(list(a))
>['name', 'birth', 'num']
#keys(), 1)키 리스트로 얻기
print(a.keys())
>['name', 'birth', 'num']
#values(), 2)값 리스트로 얻기
print(a.values())
>['sue', '0531', 123]
#items(), 3)키와 값 쌍으로 얻기(튜플값)
print(a.items())
>[('name' : 'sue'), ('num' : 123), ('birth' : '0531')]
두개의 반복 변수를 이용해 키와 값 얻기
a = {'name' : 'sue', 'num' : 123, 'birth' : '0531'}
for i, j in a.items() :
print(i, j)
>name sue
num 123
birth 0531
fname = input('Enter File: ')
if len(fname) < 1 :
fname = 'abc.txt' # 기본실행 파일(파일 존재해야함)
hand = open(fname)
dir = dict()
for line in hand :
line = line.rstrip()
wds = line.split()
for i in wds :
dir[i] = dir.get(i,0) + 1
print(i, dir[i])
print(dir)
# 가장 많이 등장하는 단어 찾기
bigword = None
bigcount = None
for k, v in dir.items() :
if bigcount is None or v > bigcount :
bigword = k
bigcount = v
print(bigword, bigcount)
튜플은 리스트와 비슷한 기능을 한다.
차이점은 튜플은 수정 가능하지 않게 저장하기 때문에 리스트와 비교하여 메모리 사용량과 성능 측면에서 훨씬 효율적이다.
따라서 튜플은 내용을 절대 변경할 수 없다.
(sort(), append(), reverse()등 사용 불가)
l = list()
dir(l)
>['append','count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
t = tuple()
dir(t)
>['count', 'index']
또한, 리스트는 대괄호'[]'를 사용하고 튜플은 소괄호'()'를 사용한다.
x, y = (4, 'fred')
print(y)
>fred
a = {'cc': 2, 'dd' : 4}
print(a.items())
>[('cc': 2), ('dd' : 4)]
튜플은 비교가 가능하다.
여러 요소로 이루어져있을 경우 첫 번째 요소가 같다면 다음 요소를 비교하는 형식으로 다른 요소가 있을 때까지 비교한다.
(0, 1, 2) < (5, 1, 2)
>True #0 < 5
('Jones', 'Sally') < ('Jones', 'Sam')
> True #Jones == Jones, Sally < Sam
딕셔너리의 '데이터 빈도 측정 + 빈도 가장 높은 단어 찾기'에 추가
fname = input('Enter File: ')
if len(fname) < 1 :
fname = 'clown.txt' # 기본실행
hand = open(fname)
dir = dict()
for line in hand :
line = line.rstrip()
wds = line.split()
for i in wds :
dir[i] = dir.get(i,0) + 1
#위는 딕셔너리 코드
#(value,key)의 튜플형식으로 리스트에 삽입
tmp = list()
for k,v in dir.items() :
newt = (v,k)
tmp.append(newt)
#value값을 기준으로 내림차순 정렬(reverse = True)
tmp = sorted(tmp,reverse = True)
print("Sorted: ", tmp[:5])
#가장 많이 쓰이는 단어 5개 출력, (key,value 형식으로)
for v,k in tmp[:5] :
print(k,v)
특수 문자로 이루어진 언어로 문자만을 사용해 프로그래밍한다.
정규식 사용 전 라이브러리에서 불러오기
import re
find()처럼 정규식과 매칭되는 문자열을 찾을 수 있다.
import re
a = open('abc.txt')
for line in a :
line = line.rstrip()
if re.search('^From:', line) :
print(line)
정규식에 맞는 문자열을 추출할 수 있다.
return값으로 리스트를 준다.
import re
x = 'My 2 favorite numbers are 19 and 42'
y = re.findall('[0-9]+', x)
print(y)
>['2', '19', '42']
z = re.findall('[AEIOU]+',x)
print(z)
>[] #만족하는 것을 못 찾을 경우 false가 아닌 빈 리스트를 return
re.findall('[0-9]+', x):
x에서 숫자(0~9)를 한번 이상 반복 사용한걸 찾아서 추출해줘
re.findall('[AEIOU]+',x):
AEIOU로 이루어진 하나 이상의 대문자를 반복 사용한걸 찾아 추출해줘
^X.*:
X로 시작하고 아무 문자(.)는 0번 이상 사용되고 :로 끝나라
ex)
Xsin23:
X-Result:
^X-\S+:
X-로 시작하고 공백제외 모든 문자(\S)를 한번 이상 사용하고 :로 끝나라
^From (\S+@\S+)
From으로 시작한 후 공백 한칸이 있고 (공백제외 모든 문자(\S)를 한번 이상 사용하고 @를 한 번 쓴 후 공백제외 모든 문자(\S)를 한번 이상 사용해라). 굵은 글씨 부분(괄호로 묶인 부분)만 추출해라
import re
x = 'From abc.mart@nna.ac.kr Sat Jan 5'
y = re.findall('^From (\S+@\S+)', x)
print(y)
>['abc.mart@nna.ac.kr']
import re
x = 'From abc.mart@nna.ac.kr Sat Jan 5'
y = re.findall('@([^ ]*)', x)
print(y)
>['nna.ac.kr']
기본적으로 정규식의 +와 *는 가장 길게 매칭되는 경우를 검색한다.
import re
x = 'From: Using the : character'
y = re.findall('^F.+:', x)
print(y)
>['From: Using the :']
+또는 * 뒤에 ?를 붙여줄 경우 가장 짧은 경우를 검색한다.
import re
x = 'From: Using the : character'
y = re.findall('^F.+?:', x)
print(y)
>['From:']
지정된 특수 문자를 문자 그대로 사용하고 싶은 경우 앞에 \를 붙이면 된다.
import re
x = 'We just received $100.00 for cookies.'
y = re.findall('\$[0-9.]+',x)
print(y)
>['$100.00']