Python 기본문법
1. 변수
파이썬은 모든것이 객체로 이루어져 있다. 객체는 데이터의 형태를 결정해주는 타입으로, 파이썬에서는 객체의 타입을 바꿀 수 없다.
변수를 선언하고 사용하는 형태로 컴퓨터의 메모리에 값을 할당하고, 참조 할 수 있다.
var1 = 100
print(var1)
100
var1이라는 변수에 100의 정수를 할당하고 print를 사용해 var1변수가 가진 값을 출력한다. 변수는 단지 이름이며 그자체가 어떠한 값을 가지는 것이 아니다. var1은 100이란 데이터를 직접 가는 것이 아니라, 100이라는 정수형 객체가 있고 var1은 단순히 해당 객체를 참조하는 역할을 한다.
var2 = var1
var3 = var1
var4 = var1
과 같이 입력하고 id 주소를 출력하는 내장함수를 사용해 보면
id(var1)
id(var2)
id(var3)
id(var4)
는 모두 같은 객체를 가리킨다.
var1 = 101
id(var1)
다른 객체를 참조하도록 했을 때 var2~4가 var1을 참조한 것이 아니라, var1이 참조하던 객체를 참조했다는 것을 알수가 있다.
변수의 타입확인
type(var1)
<class 'int'>
# integer(정수)형
type('안녕하세요')
<class 'str'>
# str(문자)형 인것을 알수가 있다.
2. 숫자
50 + 3 = 53 # 더하기
50 - 3 = 47 # 빼기
50 * 3 = 150 # 곱하기
50 / 3 = 16.6666... # 나누기
50 // 3 = 16 # 나누기 몫
50 % 3 = 2 # 나누기 나머지
10 ** 3 = 1000 # 제곱, 세제곱...
우선순위 규칙이 적용 되지만 괄호도 쓸수 있다.
3. 문자열
python3는 문자열에서 기본적으로 유니코드를 사용한다.
’’, “” 작은 따옴표나 큰 따옴표를 쓴다.
세개의 작은 따옴표나 큰 따옴표를 사용하면 여러줄에 걸친 문장을 나타낼 때 사용한다
'''
안녕하세요
파이썬 문자열에
대해서
공부중입니다
'''
문자열은 더해서 추가 할 수가 있다.
notice = ''
notice += '공지사항'
notice += '(패치노트)'
notice 는 ‘공지사항(패치노트)’를 출력한다
인덱스 연산
adler = 'i am sherlocked'
adler[0] = 'i'
adler[2] = 'a'
문자열은 불변이므로 인덱싱한 부분에 새 값을 대입할 수 없다.
슬라이스 연산
# 처음부터 끝까지
[:]
# start 오프셋부터 마지막까지
[start:]
# 처음부터 end 오프셋 까지
[:end]
# start오프셋 부터 end 오프셋까지
[start:end]
# stat오프셋부터 end오프셋까지 step만큼씩 뛰어넘은 부분
[start:end:step]
길이 : 내장함수 len 사용
문자열 나누기(split)
fruits = "apple, banana, melon, mango"
fruits.split(,)
['apple', 'banana', 'melon', 'mango']
# split함수에 인자를 주지 않으면 공백을 기준으로 구분한다.
문자열 결합(join)
fruits = ['apple', 'banana', 'melon', 'mango']
fruits_str = ','.join(fruits_list)
print(fruits_list)
apple, banana, melon, mango
대소문자 다루기
sherlock = 'i am Sherlocked'
# 문자열의 첫글자만 대문자로
sherlock.capitalize()
'I am Sherlocked'
# 단어의 처음만 대문자로
sherlock.title()
'I Am Sherlocked'
# 전부다 대문자로
sherlock.upper()
'I AM SHERLOCKED'
# 전부다 소문자로
sherlock.lower()
'i am sherlocked'
# 대문자는 소문자로 소문자는 대문자로
sherlock.swapcase()
'I AM sHERLOCKED'
4. 시퀀스 타입
파이썬에 내장된 시퀀스 타입에는 문자열, 리스트, 튜플이 있다. 문자열은 인용부호(‘’,”“)을 사용하며, 리스트는 [], 튜플은 ()을 사용해 나타낸다.
리스트? 리스트는 순차적인 데이터를 나타내는데 유용하며, 문자열과는 달리 내부 항목을 변경할 수 있다.
list1 = []
lsit2 = list()
s_list1 = ['a', 'b', 'c', 'd']
list('I am sherlocked')
['I', ' ', 'a', 'm', ' ', 's', 'h', 'e', 'r', 'l', 'o', 'c', 'k', 'e', 'd']
리스트 항목 추가
s_list1 = ['a', 'b', 'c', 'd']
s_list1.append('e')
['a', 'b', 'c', 'd', 'e']
리스트 병합
fruits = ['apple', 'banana', 'melon']
colors = ['red', 'green', 'blue']
fruits.extend(colors)
fruits
['apple', 'banana', 'melon', 'red', 'green', 'blue']
fruits = ['apple', 'banana', 'melon']
colors = ['red', 'green', 'blue']
fruits += colors
fruits
['apple', 'banana', 'melon', 'red', 'green', 'blue']
fruits = ['apple', 'banana', 'melon']
# 특정위치에 리스트 항목 추가
fruits.insert(1, 'mango')
fruits
['apple', 'mango', 'banana', 'melon']
# 특정 위치 리스트 항목 삭제
# del은 리스트 함수가 아닌, 파이썬 구문이므로 del <list>[offset]
del fruit[0]
# remove 값으로 리스트 항목 삭제
fruits.remove('mango')
fruits
['apple', 'banana', 'melon']
# pop 리스트 항목 추출 후 삭제
# 아무것도 입력하지 않으면 마지막 항목이 삭제
fruits.pop()
fruits
['apple', 'banana']
# index 값으로 리스트 항목 오프셋 찾기
fruits.index('apple')
0
# in 존재여부 확인
'red' in fruits
True
# count 값 세기
fruits.append('apple')
fruits.count('apple')
2
# sort, sorted 정렬하기
# sort 리스트 자체를 정렬
colors = ['red', 'blue', 'green']
colors.sort()
colors
['blue', 'green', 'red']
#sorted 리스트의 정렬 복사본을 반환
sample_list = ['a', 'b', 'c', '가', '나', '다']
ordered_list = sorted(sample_list)
ordered_list
['a', 'b', 'c', '가', '나', '다']
sample_list
['a', 'b', 'c', '가', '나', '다']
copy 리스트 복사
fruits = ['apple', 'banana', 'melon']
colors = ['red', 'green', 'blue']
id(fruits)
140113535967880
fruits_cop = fruits.copy()
id(fruits_cop)
140113535970312
fruits.append(colors)
fruits
['apple', 'banana', 'melon', ['red', 'green', 'blue']]
id(fruits)
140113535967880
5. 튜플
튜플은 리스트와 비슷하나, 정의 후에 내부 항목의 삭제나 수정이 불가능하다.
tuple = ()
color = 'green'
colors = 'red',
fruits = 'apple', 'banana'
colors
('red',)
fruits
('apple', 'banana')
print(type(color))
<class str>
print(type(colors))
<class tuple>
튜플을 정의할 때는 괄호가 없어도 무관하나, 괄호로 묶는것이 좀 더 튜플임을 구분하기 좋다. 또한 튜플의 요소가 1개일 때는 요소의 뒤에 쉼표를 붙여야한다.
튜플을 사용해야하는 이유
- 리스트보다 적은 메모리 사용
- 정의후에는 변하지 않느 내부값
인덱싱
t1 = (1, 2, 'a', 'b')
t1[0]
1
t1[3]
'b'
리스트처럼 인덱싱이 가능하다
# 슬라이싱
t1 = (1, 2, 'a', 'b')
t1[1:]
(2, 'a', 'b')
# 더하기
t2 = (3, 4)
t1 + t2
(1, 2, 'a', 'b', 3, 4)
# 곱하기
t2 * 2
(3, 4, 3, 4)
6. 딕셔너리(dictionary)
key-value 형태로 항목을 가지는 자료구조
dict = {
'apple': 'red',
'banana': 'yellow'
'melon': 'green'}
key는 ‘apple’, ‘banana’, ‘melon’ value는 ‘red’, ‘yellow’, ‘‘green’
# key는 정수값 10, value는 kill(문자열)을 사용
points = {10:'kill'}
# value에 리스트를 넣을수도 있다
hanamura = {'A':[1,2]}
형변환
dict 함수를 사용, 두 값의 시퀀스(리스트나 튜플)를 딕셔너리로 변환
sample = [[1,2], [3,4], [5,6]]
dict(sample)
{1: 2, 3: 4, 5: 6}
항목 찾기/추가/변경 [key]
champion_dict = {
'Lux': 'the Lady of Luminosity',
'Ahri': 'the Nine-Tailed Fox',
'Ezreal': 'the Prodigal Explorer',
'Teemo': 'the Swift Scout',
}
champion_dict['Lux']
'the Lady of Luminosity'
champion_dict['sona'] = 'Maven of the Strings'
champion_dict['Lux'] = 'Demacia'
chmpion_dict
{'Ahri': 'the Nine-Tailed Fox',
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Demacia',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
결합 (update)
item_dict = {
'Doran\'s Ring': 400,
'Doran\'s Blade': 450,
'Doran\'s Shield': 450,}
com_dict = {}
com_dict.update(champion_dict)
com_dict.update(item_dict)
com_dict
{'Ahri': 'the Nine-Tailed Fox',
"Doran Blade": 450,
"Doran Ring": 400,
"Doran Shield": 450,
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Demacia',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
com_dict.update({'Lux': 'Test'})
com_dict
{'Ahri': 'the Nine-Tailed Fox',
"Doran Blade": 450,
"Doran Ring": 400,
"Doran Shield": 450,
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Test',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
서로 같은 키가 있을 경우, update에 주어진 딕셔너리의 값이 할당된다
삭제(del)
com_dict
{'Ahri': 'the Nine-Tailed Fox',
"Doran Blade": 450,
"Doran Ring": 400,
"Doran Shield": 450,
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Test',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
del com_dict['Doran\'s Blade']
del com_dict['Doran\'s Ring']
del com dict['Doran\'s Shield']
com_dict
{'Ahri': 'the Nine-Tailed Fox',
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Test',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
전체삭제(clear)
com_dict.clear()
com_dict
{}
in으로 키검색
# true/false를 반환
champion_dict
{'Ahri': 'the Nine-Tailed Fox',
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Demacia',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
'Lux' in champion_dict
True
'Zed' in champion_dict
False
키값 또는 얻기
# keys() : 모든 키얻기
champion_dict.keys()
dict_keys(['Ahri', 'Sona', 'Teemo', 'Lux', 'Ezreal'])
# values() : 모든 값 얻기
champion_dict.values()
dict_values(['the Nine-Tailed Fox', 'Maven of the String', 'the Swift Scout', 'Demacia', 'the Prodigal Explorer'])
# items() : 모든 키-값 얻기(튜플로 반환)
champion_dict.items()
dict_items([('Ahri', 'the Nine-Tailed Fox'), ('Sona', 'Maven of the String'), ('Teemo', 'the Swift Scout'), ('Lux', 'Demacia'), ('Ezreal', 'the Prodigal Explorer')])
복사 : copy()
champion_dict
{'Ahri': 'the Nine-Tailed Fox',
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Demacia',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
champion_dict_backup = champion_dict.copy()
champion_dict_backup
{'Ahri': 'the Nine-Tailed Fox',
'Ezreal': 'the Prodigal Explorer',
'Lux': 'Demacia',
'Sona': 'Maven of the String',
'Teemo': 'the Swift Scout'}
7. SET
set는 키만 있는 딕셔너리와 같으며 중복된 값이 존재 할 수 없다.
# set생성
empty_set = set()
champions = {'lux', 'ahri', 'ezreal'}
- 형변환
- 문자열, 리스트, 튜플, 딕셔너리를 세트로 변환 할 수 있으며, 중복된 값이 사라진다.
set('ezreal')
{'e', 'z', 'a', 'l', 'r'}
set(champion_dict)
{'Ahri', 'Lux', 'Ezreal', 'Sona', 'Teemo'}
딕셔너리는 키만 남는다.
8. 집합연산
연산자 | 설명 |
---|---|
합집합 | |
& | 교집합 |
- | 차집합 |
^ | 대칭차집합 |
<= | 부분집합 |
< | 진부분집합 |
>= | 상위집합 |
> | 진상위집합 |