# a = False # comment는 #으로 표기 a = 10; b = 20 # 줄바꿈 없이 두 문장이상을 한 줄에 쓸때는 ;으로 문장을 구분 a = True # Boolean print( type (a)) # ==> <class 'float'> a = 10 # 정수 print( type (a)) # ==> <class 'int'> a = 3.14 # 실수 print( type (a)) # ==> <class 'float'> a = 3 + 4j # 복소수. (허수부 표현시 i가 아닌 j를 사용) print( type (a)) # ==> <class 'complex'> print( a.real) # ==> 3.0 (real part) print( a.imag) # ==> 4.0 (imaginary part) print( a.conjugate()) # ==> (3-4j) (켤레 복소수: conjugate complex numbers)
s1 = "abc"
s2 = 'abc'
s3 = '''abc'''
s4 = """abc"""
print(s1) # ==> abc
print(s2) # ==> abc
print(s3) # ==> abc
print(s4) # ==> abc
s5 = "ab"\
"c"
print(s5) # ==> abc
s6 = '''ab
c'''
print(s6) # ==> ab
# c
'''
원래는 문자열인데,
이와 같이 여러줄 comment 대용으로 쓰기도 한다.
'''
s1='abc'
print( s1[0]) # ==> a (0은 index)
print( s1[-1]) # ==> c (-1은 뒤에서부터 시작하는 index)
# 0 1 2 (index)
# a b c
# -3 -2 -1 (index)
s1 = 'abcdefghi' print(s1[0:4:1]) # ==> abcd # : position 0 (include) to 4(exclude) print(s1[0:4]) # ==> abcd # : 증가치 생략 시 1씩 증가 # 024 print(s1[:5:2]) # ==> ace # : 시작 생략 시 0부터 시작 print(s1[1:]) # ==> bcdefghi # : 끝 생략 시 끝까지를 의미 print( s1[-1:-4:-1]) # ==> ihg # -1-2-3 (-4는 포함되지 않음)
s1 = 'abcd' s1 = s1 + 'korea' print(s1) # ==> abcdkorea s1 = 'abcd' s1 = s1 * 2 print(s1) # ==> abcdabcd a = 10 b = 3.14 s = 'abc' s1 = 'a=%d b=%f s=%s' % (a, b, s) print(s1) # ==> a=10 b=3.140000 s=abc s1 = 'a=%5d b=%0.2f s=%s' % (a, b, s) print(s1) # ==> a= 10 b=3.14 s=abc
# .split(), .strip() s = "abcd efg" print(s) # ==> abcd efg s = s.split() print(s) # ==> ['abcd', 'efg'] # .split() 하면, 분리되어 list type으로 반환 s = " abcd efg " s = s.strip() print(s) # ==> abcd efg # : 좌우 white space 제거. (공백,\n, \t, ...) s = 'abc' print( s[0] ) s[0] = 'A' # Type Error 발생. (str은 immutable type이라 수정불가) # TypeError: 'str' object does not support item assignment
옥텟(octet)은 컴퓨팅에서 8개의 비트가 한데 모인 것을 말한다.
초기 컴퓨터들은 1 바이트가 꼭 8 비트만을 의미하지 않았으므로,
8 비트를 명확하게 정의하기 위해 옥텟 이라는 용어가 필요 했던 것이다.
그러나 요즘에는 바이트하고 같은 의미가 되었다.
s = b'xyz'
print(s) # ==> b'xyz'
print( type(s) ) # ==> <class 'bytes'>
s1 = 'xyz'
s1 = s1.encode('utf-8') # str ==> utf-8
print(s1) # ==> xyz
print( type(s1)) # ==> <class 'bytes'>
s2 = b'xyz'
s2 = s2.decode('utf-8') # utf-8 ==> str
print(s2) # ==> xyz
print( type(s2)) # ==> <class 'str'>
| 순서 O (indexing, slicing) |
순서 X | |
| mutable (수정가능) |
list [] | set, dictionary {key:value} |
| immutable (수정불가) |
tuple (), str 'abc', bytes b'xyz' |
- |
myList = [10, 3.14, True, 'abc']
print(myList) # ==> [10, 3.14, True, 'abc']
print( type(myList) ) # ==> <class 'list'>
print( myList[0]) # ==> 10
print( myList[-1]) # ==> abc
print( myList[0:3]) # ==> [10, 3.14, True]
print( myList[1:3:2]) # ==> [3.14]
myList2 = list()
myList2.append(10)
myList2.append(3.14)
myList2.append(True)
myList2.append('abc')
print(myList2) # ==> [10, 3.14, True, 'abc']
print( type(myList2) ) # ==> <class 'list'>
myList = [10, 20, 30]
myList.append(40) # 뒤에 추가
print(myList) # ==> [10, 20, 30, 40]
myList[0] = 100 # 수정(mutable이라 가능함)
print(myList) # ==> [100, 20, 30, 40]
myList.insert(1, 200) # index 1위치에 삽입
print(myList) # ==> [100, 200, 20, 30, 40]
myList.extend([1, 2, 3]) # list 확장
print(myList) # ==> [100, 200, 20, 30, 40, 1, 2, 3]
myList = myList + [4, 5] # list 확장
print(myList) # ==> [100, 200, 20, 30, 40, 1, 2, 3, 4, 5]
myList.remove(30) # 30을 찾아서 삭제
print(myList) # ==> [100, 200, 20, 40, 1, 2, 3, 4, 5]
myList.pop() # 맨끝 삭제
print(myList) # ==> [100, 200, 20, 40, 1, 2, 3, 4]
myList.pop(1) # index 1위치 삭제
print(myList) # ==> [100, 20, 40, 1, 2, 3, 4]
del(myList[0]) # myList[0]을 찾아서 삭제
print(myList) # ==> [20, 40, 1, 2, 3, 4]
myList = myList * 2 #2번반복
print(myList) # ==> [20, 40, 1, 2, 3, 4, 20, 40, 1, 2, 3, 4]
n = myList.index(20) # 객체 20을 찾아서 index를 반환
print('n=%d' % n) # ==> n=0
n = myList.count(20) # 객체 20의 개수를 반환
print('n=%d' % n) # ==> n=2
n = len(myList) # myList 요소의 개수를 반환
print('n=%d' % n) # ==> n=12
myTuple = (10, 20, 30, 40) print( type(myTuple) ) # ==> <class 'tuple'> print( myTuple[0]) # ==> 10 print( myTuple[0:3]) # ==> (10, 20, 30) a = 10 b = 20 c = 30 a, b, c = 10, 20, 30 print(a, b, c) # ==> 10 20 30 # tuple과 list는 Unpacking 가능 a, b, c = (100, 200, 300) print(a, b, c) # ==> 100 200 300 a, b, c = [10, 20, 30] print(a, b, c) # ==> 10 20 30 # tuple만 packing 가능 a = 100, 200, 300 print(type(a)) # ==> <class 'tuple'> print(a) # ==> (100, 200, 300)
myD = { 10:"aa", 20:"bb", 30:"cc"}
print(myD) # ==> {10: 'aa', 20: 'bb', 30: 'cc'}
print(type(myD)) # ==> <class 'dict'>
#print(myD[0]) # 키값중 0은 없어서 에러 발생. (KeyError: 0)
print(myD[20]) # ==> bb
print(myD.get(20)) # ==> bb
print(myD.get(40, "zz")) # ==> zz
print(myD) # ==> {10: 'aa', 20: 'bb', 30: 'cc'}
myD[10] = "AA"
print(myD) # ==> {10: 'AA', 20: 'bb', 30: 'cc'}
# 키값이 중복되면, overwrite한다. (맨마지막에 추가된 값으로 갱신된다)
myD = { 10:"aa", 20:"bb", 30:"cc", 20:"BB"}
print(myD) # ==> {10: 'aa', 20: 'BB', 30: 'cc'}
# 키가 있으면 수정, 없으면 추가된다.
myD[10] = "AA"
myD[40] = "DD"
print(myD) # ==> {10: 'AA', 20: 'BB', 30: 'cc', 40: 'DD'}
myD.pop(20)
print(myD) # ==> {10: 'AA', 30: 'cc', 40: 'DD'}
del(myD[30])
print(myD) # ==> {10: 'AA', 40: 'DD'}
print(myD.keys()) # ==> dict_keys([10, 40])
print(myD.values()) # ==> dict_values(['AA', 'DD'])
print(myD.items()) # ==> dict_items([(10, 'AA'), (40, 'DD')])
# .items()를 호출하면, 키와 값이 tuple로 구성된 list를 반환한다.
test = [10, (11, 'aa')]
print( test ) # ==> [10, (11, 'aa')]
print( test[0]) # ==> 10
print( test[1]) # ==> (11, 'aa')
print( test[1][0]) # ==> 11
mySet = {10, 20, 30, 100}
print( mySet) # ==> {100, 10, 20, 30}
print( type(mySet)) # ==> <class 'set'>
#print( mySet[0]) # indexing 안됨
#print( mySet[0:3]) # slicing 안됨
mySet.add(1000)
print( mySet) # ==> {100, 1000, 10, 20, 30}
mySet.remove(30)
print( mySet) # ==> {100, 1000, 10, 20}
mySet = {10, 20, 30, 100, 20, 30}
print( mySet) # ==> {100, 10, 20, 30}
# 중복제거됨
mySet1 = {10, 20, 30}
mySet2 = {20, 30, 40, 50}
print( mySet1 & mySet2) # ==> {20, 30}
# 교집합 출력됨.
print( mySet1 | mySet2) # ==> {50, 20, 40, 10, 30}
# 합집합 출력됨.
print( mySet1 - mySet2) # ==> {10}
# 차집합 출력됨.
print( mySet1 ^ mySet2) # ==> {40, 10, 50}
# 대상 차집합 출력됨. (합집합에서 교집합을 뺀 것)
print( mySet1.intersection(mySet2)) # &
print( mySet1.union(mySet2)) # |
* 연산자 다르게 정리된 버전 (link) - 산술 연산자(Arithmetic Operators) - 할당 연산자(Assignment Operators) - 삼항 연산자(Ternary Operator) - 비교 연산자(Comparison Operators) - 논리 연산자(Logical Operators) - 항등 연산자(Identity Operators) - 멤버 연산자(Membership Operators) - 비트 연산자(Bitwise Operators)
a = 7 + 2 # ==> 9
b = 7 - 2 # ==> 5
c = 7 * 2 # ==> 14
d = 7 / 2 # ==> 3.5
e = 7 ** 2 # ==> 49
f = 7 // 2 # ==> 3
g = 7 % 2 # ==> 1
print(a, b, c, d, e, f, g) # ==> 9 5 14 3.5 49 3 1
# 연산자 우선순위
# **
# *, /, //, %
# +, -
# 결합도 좌 --> 우
a = 10 + 2 - 3 * 2 ** 2
a = 10 + 2 - (3 * (2 ** 2))
print( a ) # ==> 0
# 반지름 5인 원의 면적을 구하기
c = 3.14 * 5 ** 2
print( "원의 면적:", c) # ==> 원의 면적: 78.5
# 반지름을 입력받아 원의 면적을 구하기
s = input("입력:")
print(s) # ==>12
print( type(s) ) # ==>
# 형변환 (str --> int)
r = int(s) # int 형으로 변환
circle = 3.14 * r ** 2
print( "원의 면적:", circle) # ==> 원의 면적: 78.5
# 형변환 (tuple --> list)
c = (10, 20, 30) # tuple
c = list(c) # list로 변환
a += 1 # 1증가
a -= 1 # 1감소
# a++ # 지원하지 않음
# ++a # 지원하지 않지만 에러가 발생하진 않음
# # + ( + a) 로 해석하여 값의 변화가 없음
# 관계연산자
a = 3
b = a > 0
print(b) # ==> True
c = 0 < a < 5 # 이렇게 관계식으로 쓰도 됨
# 0 < a and a < 5 와 같이 쓸 필요 없음.
print(c) # ==> True
# 우선순위 : 관계연산자 --> 논리연산자
# 논리연산자
a = 5
b = 0 < a and a > 10
print( b ) # ==> False
# 비트 연산자
a = 2 & 1
print(a) # ==> 0
a = -2 | 1 # 2의 보수를 취한다.
# 0000 0010 (+2)
# 1111 1101 + 1 (2의보수로 변환)
# 1111 1110
# 0000 0001 을 bit or 하면
# 1111 1111 ==> 즉 -1이 된다.
print(a) # -1
print(2 << 1) # ==> 4
print(-2 << 1) # ==> -4
print(1 >> 1) # ==> 0
print(-1 >> 1) # ==> -1
#구성원 연산자
s = "abcdef hello"
print( "hello" in s) # ==> True
print( "hello" not in s) # ==> False
myList = [10, 20, 30, 40, 50]
print( 10 in myList) # ==> True
print( 100 in myList) # ==> False
myD = {10:"aa", 20:"bb", 30:"cc"}
print( 10 in myList) # ==> True
print( "aa" in myList) # ==> False # 키에 대해서만 확인 가능
print( 100 in myList) # ==> False
# 식별 연산자 a = 10 b = 10 print(a is b) # ==> True (a와 b가 둘 다 동일한 10을 가진 객체를 가리킴. 참조카운트가 2가 됨) print( id(a) ) # ==> 140725697868320 print( id(b) ) # ==> 140725697868320 # reference count 방식으로 동작하기때문에 값을 변경하기 전까진 같은 객체 # b의 값을 바꾸면 b = 20 print(a is b) # ==> False (a와 b가 다른 객체임) print( id(a) ) # ==> 140725697868320 print( id(b) ) # ==> 140725697868640 myList = [10, 20, 30, 40] myList1 = myList # shallow copy print(myList is myList1) # ==> True myList1[0] = 100 # myList1과 myList은 동일한 list 객체를 가리키므로, 10이 100으로 바뀌어서 출력됨 print(myList) # ==> [100, 20, 30, 40] myList = [10, 20, 30, 40] myList1 = [10, 20, 30, 40] print(myList is myList1) # ==> False myList1[0] = 100 # myList와 다른 객체를 가리키므로, 10이 그대로 출력됨 print(myList) # ==> [10, 20, 30, 40]