if문
1
2
3
4
5
6
7
8
if 조건문:
수행할 문장1
수행할문장2
...
else:
수행할 문장A
수행할 문장B
... cs
1
2
3
4
5
6
7
money = True
if money:
print("택시를")
else:
print("가라")
# 출력 : 택시를
cs
※ 요즘 파이썬 커뮤니티에서는 들여쓰기를 할 때 공백(Spacebar) 4개를 사용하는 것을 권장한다.
※ PEP8(Python Enhance Proposal) : Style Guide for Python Code
https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces
https://www.python.org/dev/peps/pep-0008/#indentation
4.
• 필수X, 권장사항O
•준수 하지 않아도 되는 사례
: PEP8을 준수할 경우, 작성된 코드가 동작하지 않을 경우
• 1들여쓰기 = 4 space, 1 line = 79 columns(=char)
• 줄바꿈이 일어나는 요소는 수직으로 정렬,
수식일 경우엔 연산자가 앞으로 와야됨
• String Quotes
• 하나로 통일해서 사용하되 별도의 규칙 없음
• 3개의 따옴표에 대해서는 항상 쌍따옴표 사용
(“”” PEP257 : doc string의 일관성 유지 “””)
• , 뒤에 띄어쓰기
PEP 8 간단 정리
1
2
3
4
5
6
7
8
9
10
11
my_list = [
1, 2, 3,
4, 5, 6,
]
total = (a
+ (b - c)
+ d)
query = 'SELECT * '
+ 'FROM USER' cs
비교연산자 설명
x <y x가 y보다 작다
x > y x가 y보다 크다
x == y x와 y가 같다
x != y x와 y가 같지 않다
x >= y x가 y보다 크거나 같다
x <= y x가 y보다 작거나 같다
비교 연산자
1
2
3
4
5
6
7
>>> money = 2000
>>> if money >= 3000:
... print("택시를 타고 가라")
... else:
... print("걸어가라")
...
걸어가라 cs
7.
비교 연산자
in notin
x in 리스트 x not in 리스트
x in 튜플 x not in 튜플
x in 문자열 x not in 문자열
1
2
3
4
>>> 1 in [1, 2, 3]
True
>>> 1 not in [1, 2, 3]
False cs
연산자 설명
x or y x와 y 둘중에 하나만 참이면 참이다
x and y x와 y 모두 참이어야 참이다
not x x가 거짓이면 참이다
1
2
3
4
5
6
7
8
9
>>> money = 2000
>>> card = True
>>> if money >= 3000 or card:
... print("택시를 타고 가라")
... else:
... print("걸어가라")
...
택시를 타고 가라
>>>
cs
8.
https://www.python.org/dev/peps/pep-
0008/#programming-recommendations
is?
• is :reference
• == : value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -5 ~ 256 cached
>>> a = 1
>>> a is 1
True
>>> a == 1
True
# 257 not cached
>>> a = 257
>>> a is 257
False
>>> a == 257
True
# id(a) != id(257)
>>> id(a)
1264093736688
>>> id(257)
1264094572016 cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# list(object)
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
# Make a new copy of list `a`
# via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True cs
for
1
2
3
4
for 변수 in리스트(또는 튜플, 문자열):
수행할 문장1
수행할 문장2
... cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> test_list = ['one', 'two', 'three']
>>> for i in test_list:
... print(i)
...
one
two
three
>>> a = [(1,2), (3,4), (5,6)]
>>> for (first, last) in a:
... print(first + last)
...
3
7
11
Colored by Color Scripter
c
s
for - list
1
2
3
4
5
6
7
8
9
10
>>>a = [1,2,3,4]
>>> result = [num * 3 for num in a]
>>> print(result)
[3, 6, 9, 12]
>>> a = [1,2,3,4]
>>> result = [num * 3 for num in a if num % 2 == 0]
>>> print(result)
[6, 12] cs
1
2
3
4
[표현식 for 항목1 in 반복가능객체1 if 조건문1
for 항목2 in 반복가능객체2 if 조건문2
...
for 항목n in 반복가능객체n if 조건문n] cs
13.
for – list& index
1
2
3
4
5
6
7
8
for idx, val in enumerate(ints):
print(idx, val)
>>> for i, num in enumerate(['a', 'b', 'c']):
>>> print(i, num)
0 a
1 b
2 c cs
함수
1
2
3
4
def 함수명(매개변수):
<수행할 문장1>
<수행할문장2>
... cs
1
2
3
4
5
>>> a = 3
>>> b = 4
>>> c = add(a, b)
>>> print(c)
7
c
s
1
2
3
4
5
6
7
8
9
10
11
12
13
# 입력값 ---> 함수 ----> 리턴값
def 함수이름(매개변수):
<수행할 문장>
...
return 결과값
# 일반 함수
def add(a, b): # a, b는 매개변수(parameter)
result = a + b
return result
print(add(3, 4)) # 3, 4는 인수(arguments) cs
16.
함수 – 다른케이스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 입력이 없는 함수
def say():
return 'Hi'
>>> a = say()
>>> print(a)
Hi
# 결과가 없는 함수
def add(a, b):
print("%d, %d의 합은 %d입니다." % (a, b, a+b))
>>> add(3, 4)
3, 4의 합은 7입니다.
# 입력/결과 없는 함수
def say():
print('Hi')
>>> say()
Hi cs
1
2
3
4
5
6
7
8
9
10
11
12
# 매개변수 지정하여 호출하기
def add(a, b):
return a+b
>>> result = add(a=3, b=7) # a에 3, b에 7을 전달
>>> print(result)
10
>>> result = add(b=5, a=3) # a에 3, b에 7을 전달
>>> print(result)
8 cs
17.
함수 – args,kwargs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def 함수이름(*매개변수):
<수행할 문장>
...
def add_many(*args):
result = 0
for i in args:
result = result + i
return result
>>> result = add_many(1,2,3)
>>> print(result)
6 cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 앞에 *을 붙이면 튜플
def add_mul(choice, *args):
if choice == "add":
result = 0
for i in args:
result = result + i
elif choice == "mul":
result = 1
for i in args:
result = result * i
return result
>>> result = add_mul('add', 1,2,3,4,5)
>>> print(result)
15 cs
1
2
3
4
5
6
7
# 앞에 **을 붙이면 딕셔너리
def print_kwargs(**kwargs):
print(kwargs)
>>> print_kwargs(name='foo', age=3)
{'age': 3, 'name': 'foo'} cs
namespace
• 전역 네임스페이스
모듈별로 존재하며, 모듈 전체에 통용되는 이름을 사용한다.
• 지역 네임 스페이스
함수 및 메소드 별로 존재하며, 함수 내의 지역 변수들이 소속된다.
• 빌트인 네임 스페이스
기본 내장 함수 및 기본 예외들의 이름을 저장하는 곳
※ 모든 네임스페이스는 파이썬 dict으로 구현됨
※ 즉 이름과 객체 사이의 맵핑은 가변적(mutable) = 런타임 중 변경될 수 있다
20.
변수의 scope
• 변수의scope
변수의 이름으로 그 변수가 가리키는 엔티티를 찾을 수 있는 영역의 범위
• block 단위의 scope
• c, java
• {} 내(block)에서 선언된 변수는 block을 빠져나가면 폐기된다
• python scope
• 파이썬의 block은 프로그램 수행 흐름의 분기점
• 파이썬에서는 블럭단위의 스코프는 존재하지 않는다
• 오직 지역/전역 변수만 존재한다
※ {}으로 함수를 선언하지 않고 탭으로 구분하는 이유!
underscore(_) – naming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
_internal_name= 'one_module' # private 변수
_internal_version = '1.0' # private 변수
class A:
def __init__(self, price):
self._price = price
def _double_price(self): # private 메서드
return self._price * self._hidden_factor
# single_trailing_underscore_
# 파이썬 키워드(예약어)와의 충돌을 피하기 위해 사용하는 컨벤션
Tkinter.Toplevel(master, class_='ClassName') # class와의 충돌을 피함
list_ = List.objects.get(1) # list와의 충돌을 피함
cs
23.
underscore(_) – mangling
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#__double_leading_underscores
# 클래스 속성명을 맹글링(mangling)하여 클래스간 속성명의 충돌을 방지하기 위한 용도로 사용
# 맹글링(mangling)이란,
# 컴파일러나 인터프리터가 변수/함수명을 그대로 사용하지 않고 일정한 규칙에 의해 변형시키는 것
class A:
def _single_method(self):
pass
def __double_method(self): # 맹글링을 위한 메서드
pass
class B(A):
def __double_method(self): # 맹글링을 위한 메서드
pass
print(dir(A())) # ['_A_double_method', ..., '_single_method']
print(dir(B())) # ['_A_double_method', '_B_double_method', ..., '_single_method']
# 서로 같은 이름의 메서드를 가지지만 오버라이드가 되지 않는다. cs
24.
underscore(_) – 값무시
1
2
3
4
5
6
7
8
9
10
11
12
13
#언패킹시 특정값을 무시
x, _, y = (1, 2, 3) # x = 1, y = 3
# 여러개의 값 무시
x, *_, y = (1, 2, 3, 4, 5) # x = 1, y = 5
# 인덱스 무시
for _ in range(10):
do_something()
# 특정 위치의 값 무시
for _, val in list_of_tuple:
do_something()
cs
25.
underscore(_) – i18n/l10nfuctions
1
2
3
4
5
6
7
8
9
10
# gettext 공식 문서 참고 : https://docs.python.org/3/library/gettext.html
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print(_('This is a translatable string.')) cs
• i18n : internationalization
• l10n : localization
함수 - global
1
2
3
4
5
6
7
8
9
10
11
#vartest_global.py
a = 1
def vartest():
global a
a = a+1
vartest()
print(a)
# 출력
2 cs
프로그래밍을 할 때 global 명령어는 사용하지 않는 것이 좋다.
왜냐하면
함수는 독립적으로 존재하는 것이 좋다.
외부 변수에 종속적인 함수는 그다지 좋은 함수가 아니다.
그러므로 가급적 global 명령어를 사용하는 이 방법은 피하고
첫 번째 방법(return)을 사용하기를 권한다.
28.
함수 - lambda
1
2
3
4
>>>add = lambda a, b: a+b
>>> result = add(3, 4)
>>> print(result)
7 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
arr = [1, 2, 3, 4]
total = 0
for i in arr:
j = i * 2
if j > 4:
total += j
# 14
from functional import seq
seq(1, 2, 3, 4)
.map(lambda x: x * 2)
.filter(lambda x: x > 4)
.reduce(lambda x, y: x + y)
# 14
# or if you don't like backslash continuation
(seq(1, 2, 3, 4)
.map(lambda x: x * 2)
.filter(lambda x: x > 4)
.reduce(lambda x, y: x + y)
)
# 14 cs
29.
함수 – 일급함수(first-class)
• 모든 것은 객체(object)다.
• 객체는 숫자, 문자열, 튜플, 리스트, 딕셔너리,
변수, 함수, 클래스를 포함한다.
• 함수는 그 중에서 1급 시민(first-class citizen)이다.
• 1급 시민
• 변수에 담을 수 있다.
• 인자로 전달할 수 있다.
• 반환 값으로 전달할 수 있다.
• 1급 객체
• 객체를 1급 시민으로써 취급
• 1급 함수
• 함수를 1급 시민으로 취급
• (추가) 런타임 생성이 가능
• (추가) 익명으로 생성이 가능
30.
사용자 입력 -input
1
2
3
4
5
6
7
8
9
10
>>> a = input()
Life is too short, you need python
>>> a
'Life is too short, you need python'
>>> number = input("숫자를 입력하세요: ")
숫자를 입력하세요: 3
>>> print(number)
3 cs
31.
출력
1
2
3
4
5
6
7
8
9
>>> a =123
>>> print(a)
123
>>> a = "Python"
>>> print(a)
Python
>>> a = [1, 2, 3]
>>> print(a)
[1, 2, 3] cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> print("life" "is" "too short") # ①
lifeistoo short
>>> print("life"+"is"+"too short") # ②
lifeistoo short
>>> print("life", "is", "too short")
life is too short
>>> for i in range(10):
... print(i, end=' ')
...
0 1 2 3 4 5 6 7 8 9
cs
32.
파일 생성(쓰기)
1
2
3
4
5
f =open("새파일.txt", 'w')
f.close()
f = open("C:/doit/새파일.txt", 'w')
f.close() cs
1
2
3
4
5
6
# writedata.py
f = open("C:/doit/새파일.txt", 'w')
for i in range(1, 11):
data = "%d번째 줄입니다.n" % i
f.write(data)
f.close()
cs
쓰기 모드('w')로 파일을 열 때
이미 존재하는 파일을 열 경우
그 파일의 내용이 모두 사라지게 된다
33.
파일 읽기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# readline()
#readline_test.py
f = open("C:/doit/새파일.txt", 'r')
line = f.readline()
print(line)
f.close()
# readline_all.py
f = open("C:/doit/새파일.txt", 'r')
while True:
line = f.readline()
if not line: break
print(line)
f.close() cs
1
2
3
4
5
6
7
8
9
10
11
12
13
# readlines()
f = open("C:/doit/새파일.txt", 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
# read()
f = open("C:/doit/새파일.txt", 'r')
data = f.read()
print(data)
f.close() cs
34.
파일 내용 추가
1
2
3
4
5
6
#adddata.py
f = open("C:/doit/새파일.txt",'a')
for i in range(11, 20):
data = "%d번째 줄입니다.n" % i
f.write(data)
f.close()
cs
35.
with
1
2
3
4
5
6
7
8
9
# 일반적인 파일쓰기
f = open("foo.txt", 'w')
f.write("Life is too short, you need python")
f.close()
# with를 사용
# with 블록을 나가는 순간 f.close() 호출됨
with open("foo.txt", "w") as f:
f.write("Life is too short, you need python")
cs
※ with구문은 파이썬 2.5부터 지원됨
1
2
3
4
5
6
7
8
9
class controlled_execution:
def __enter__(self):
set things up
return thing
def __exit__(self, type, value, traceback):
tear things down
with controlled_execution() as thing:
some code using thing cs