본문 바로가기
코뮤니티 모각코

[Python] 기초 (4)

by 넝구리 2022. 4. 4.

'코뮤니티 모각코' 활동에서의 학습 내용을 바탕으로 작성한 글입니다.

자세한 내용은 링크를 통해 확인하시기 바랍니다.


함수

 

https://codemate.kr/@datasponge/파이썬-기초-함수

 

함수 by datasponge | 코드메이트

함수 ✔ def : 함수를 만들 때 가장 먼저 적어줘야 함, def 뒤에 나오는 코드는 함수를 만드는 코드임을 알려주는 역할 ✔ 함수명 : print, input 등과 같은 함수의 이름 ✔ 매개변수 : 함수에 전달될 값

codemate.kr

 

 

함수

 

✔ def : 함수를 만들 때 가장 먼저 적어줘야 함, def 뒤에 나오는 코드는 함수를 만드는 코드임을 알려주는 역할

✔ 함수명 : print, input 등과 같은 함수의 이름

✔ 매개변수 : 함수에 전달될 값

def 함수명(매개변수1, 매개변수2, ...):
	함수내용

 

함수 미사용 vs 함수 사용

# 함수 미사용
print(4*2/2+48//4)
print(8*2/2+48//4)
print(12*2/2+48//4)
print(16*2/2+48//4)

# 함수 사용
def Calculate(x):
	return x*2/2+48//4

print(Calculate(4))
print(Calculate(8))
print(Calculate(12))
print(Calculate(16))

 

"return" 뒤에 나오는 코드는 함수가 끝나고 돌려줄 값을 의미

def getSum(a,b,c):
	return a+b+c

 

함수 예시

def getAvg(a,b):
	return (a+b)/2

num1=68
num2=72
result=getAvg(num1,num2)
print(result)     # 70.0 출력

 

 

 

리스트

 

https://codemate.kr/@datasponge/파이썬-기초-리스트

 

리스트 by datasponge | 코드메이트

리스트 ✔ 다른 프로그래밍 언어의 배열과 비슷한 개념 ✔ 대괄호([])와 콤마(,)를 사용해 선언 ✔ 자료형이 달라도 한번에 처리 가능 받아오기 '리스트이름[인덱스]' 형식을 통해 값 꺼내기 lst=[1,

codemate.kr

 

 

리스트

 

✔ 다른 프로그래밍 언어의 배열과 비슷한 개념

✔ 대괄호([])와 콤마(,)를 사용해 선언

✔ 자료형이 달라도 한번에 처리 가능

 

 

받아오기

 

'리스트이름[인덱스]' 형식을 통해 값 꺼내기

lst=[1,3,5,7,9]     # 리스트 선언

print(lst[0])     # 1 출력
print(lst[2])     # 5 출력
print(lst[4])     # 9 출력

 

for문 사용 - 인덱스를 사용해 리스트에 접근, len 함수를 사용해 매개변수로 전달된 변수의 크기를 구해줌

lst=[2,0,2,2,"년"]

for i in range(0,len(lst)):
	print(lst[i])

 

for문 사용 - 반복문을 사용해 리스트 데이터 받아오기

lst=[2,0,2,2,"년"]

for i in lst:
	print(i)

 

 

자르기

 

리스트 슬라이싱 - list[a:b]

lst=[2,0,2,2,"년"]

a=lst[0:2]
b=lst[2:5]
c=lst[:2]
d=lst[2:]

print(lst)     # [2,0,2,2,'년'] 출력
print(a)     # [2,0] 출력
print(b)     # [2,2,'년'] 출력
print(c)     # [2,0] 출력
print(d)     # [2,2,'년'] 출력

 

 

삽입하기

 

append 함수 - 리스트의 마지막에 값 삽입, list.append(값) 형태

lst=[2,0,2,2,"년"]
print(lst)     # [2,0,2,2,'년'] 출력

lst.append("!")
print(lst)     # [2,0,2,2,'년','!'] 출력

 

insert 함수 - 특정 인덱스에 값 삽입, list.insert(인덱스, 값) 형태

lst=[2,0,2,2,"년"]
print(lst)     # [2,0,2,2,'년'] 출력

lst.insert(4, "임인")
print(lst)     # [2,0,2,2,'임인','년'] 출력

 

 

제거하기

 

del 함수 - 특정 인덱스의 값 제거

lst=[2,0,2,2,"년"]
print(lst)     # [2,0,2,2,'년'] 출력

del lst[4]
print(lst)     # [2,0,2,2] 출력

 

remove 함수 - 값을 통해 원소 제거

lst=[2,0,2,2,"년"]
print(lst)     # [2,0,2,2,'년'] 출력

lst.remove("년")
print(lst)      # [2,0,2,2] 출력

 

 

 

튜플, 집합, 딕셔너리

 

https://codemate.kr/@datasponge/파이썬-기초-튜플-집합-딕셔너리

 

튜플, 집합, 딕셔너리 by datasponge | 코드메이트

튜플 ✔ ()로 둘러쌈 ✔ 값을 추가, 삭제할 수 없음 ✔ +, * 연산으로 튜플을 추가, 반복할 수 있음 ✔ 함수의 리턴값을 한꺼번에 여러 개 받을 수 있음 ✔ 다양한 자료형 포함 가능 ✔ 인덱스로 접

codemate.kr

 

 

튜플

 

✔ ()로 둘러쌈

✔ 값을 추가, 삭제할 수 없음

✔ +, * 연산으로 튜플을 추가, 반복할 수 있음

✔ 함수의 리턴값을 한꺼번에 여러 개 받을 수 있음

✔ 다양한 자료형 포함 가능

✔ 인덱스로 접근 가능

 

튜플 생성 및 출력

tuple1=(3,7)
tuple2=("coding",3,9)
tuple3=(1,2,(3,4,5))

print(tuple1)
print(tuple2)
print(tuple3)

 

튜플 추가(+), 반복(*)

tuple1=(1,3,5)
tuple2=(7,9,11)

plus=tuple1+tuple2
multi=tuple1*2

print(plus)     # (1,3,5,7,9,11) 출력
print(multi)     # (1,3,5,1,3,5) 출력

 

함수의 리턴값을 한꺼번에 여러 개 받을 수 있음

def minmax(lst):
	return min(lst), max(lst)     # 이 경우 함수의 리턴값이 자동으로 튜플로 처리됨

lst=[1,2,3]
tup=minmax(lst)

print(tup)     # (1,3) 출력

 

 

집합

 

✔ {} 또는 set()를 통해 생성

✔ {}를 이용해 생성할 경우 원소를 안에 넣어야함, 원소를 넣지 않으면 집합이 아닌 딕셔너리 생성

✔ 중복된 값은 허락하지 않음

✔ 순서가 존재하지 않음

✔ 인덱스를 통한 값의 접근 불가능

✔ 값의 추가와 제거 가능

 

집합 생성 및 출력

set1={5,6,7}
set2=set([5,2,8,4,1])
set3=set("datasponge")

print(set1)     # {5,6,7} 출력
print(set2)     # {1,2,4,5,8} 출력
print(set3)     # {'n','g','t','e','o','s','a','p','d'} 출력

 

교집합 : & 기호, intersection 함수

set1={5,6,7,8,}
set2={1,5,6,8}

print(set1&set2)     # {8,5,6} 출력
print(set1.intersection(set2))     # {8,5,6} 출력

 

합집합 : | 기호, union 함수

set1={5,6,7,8,}
set2={1,5,6,8}

print(set1|set2)     # {1,5,6,7,8} 출력
print(set1.union(set2))     # {1,5,6,7,8} 출력

 

차집합 : - 기호, difference 함수

set1={5,6,7,8,}
set2={1,5,6,8}

print(set1-set2)     # {7} 출력
print(set1.difference(set2))     # {7} 출력

 

값의 추가 : add 함수, update 함수

set1={5,6,7,8}
set2={1,5,6,8}

set1.add(10)     # 하나의 값 추가
set2.update([9,10,15])     # 여러 개의 값 추가

print(set1)     # {5,6,7,8,10} 출력
print(set2)     # {1,5,6,8,9,10,15} 출력

 

값의 제거: remove 함수

set1={5,6,7,8}

set1.remove(7)

print(set1)     # {8,5,6} 출력

 

 

딕셔너리

 

✔ 중괄호({}) 안에 선언

✔ key:value 형태로 데이터 저장

✔ 인덱스로 접근 불가능

 

딕셔너리 생성 및 출력

dic1={1:"candy", 2: "chocolate", 3:"jelly"}
dic2={"a":"car","b":"bicycle","c":"bus"}

print(dic1)     # {1: 'candy', 2: 'chocolate', 3: 'jelly'} 출력
print(dic2)     # {'a': 'car', 'b': 'bicycle', 'c': 'bus'} 출력
print(dic2["a"])     # car 출력

 

딕셔너리에 데이터 추가

dic1={1:"candy", 2: "chocolate", 3:"jelly"}

# 하나의 key와 value 추가 : dict[key]=value 형태
dic1[4]="ice cream"
print(dic1)     # {1: 'candy', 2: 'chocolate', 3: 'jelly', 4: 'ice cream'} 출력

# 여러 개의 key와 value 추가 : dict.update({업데이트할 딕셔너리 내용}) 형태
dic1.update({2:"cake", 5:"bread"})
print(dic1)     # {1: 'candy', 2: 'cake', 3: 'jelly', 4: 'ice cream', 5: 'bread'} 출력

 

key-value 삭제

dic2={"a":"car","b":"bicycle","c":"bus"}

del dic2["b"]

print(dic2)     # {'a': 'car', 'c': 'bus'} 출력

 

key, value쌍 추출 : dict.keys() 함수, dict.values() 함수

dic2={"a":"car","b":"bicycle","c":"bus"}

print(dic2.keys())     # dict_keys(['a', 'b', 'c']) 출력
print(dic2.values())     # dict_values(['car', 'bicycle', 'bus']) 출력

 

추출한 key, value쌍을 리스트형으로 변환

dic2={"a":"car","b":"bicycle","c":"bus"}

k_lst=list(dic2.keys())
v_lst=list(dic2.values())

print(k_lst)     # ['a', 'b', 'c'] 출력
print(v_lst)     # ['car', 'bicycle', 'bus'] 출력

'코뮤니티 모각코' 카테고리의 다른 글

[Python] 크롤링 기초 (1)  (0) 2022.04.06
[Python] 기초 (5)  (0) 2022.04.05
[Python] 기초 (3)  (0) 2022.03.31
[Python] 기초 (2)  (0) 2022.03.30
[Python] 기초 (1)  (0) 2022.03.29