변수 선언과 자료형
- 변수 선언
a = 3 # 3을 a에 넣는다.
print(a)
b = a # a에 들어 있는 값인 3을 b에 넣는다.
print(b)
a = 5 # a에 5라는 새로운 값을 넣는다.
print(a, b) # 5 3
- 숫자형
a = 7
b = 2
a+b # 9
a-b # 5
a*b # 14
a/b # 3.5
a%b # 1(나머지)
a**b # 49
- Boolean
x = True # 참
y = False # 거짓
# 보통 비교연산자의 결과로 나타내기 위에 쓰인다
4 > 2 # True 크다
5 < 1 # False 작다
6 >= 5 # True 크거나 같다
4 <= 4 # True 작거나 같다
3 == 5 # False 같다
4 != 7 # True 같지 않다
문자열
- 문자열 기초
# 작은 따옴표 또는 큰 따옴표를 붙인다
a = 'aa'
b = "bb"
- 문자열 연산
first_name = "Jungmin"
last_name = "Kim"
first_name + last_name # JungminKim
first_name + " " + last_name # Jungmin Kim
a = "3"
b = "5"
a + b # 35
a = "3"
a + 5 # 문자열과 숫자형은 더할 수 없어서 에러가 난다
# 문자열의 길이는 len() 함수를 써서 구할 수 있다.
print(len("abcde")) # 5
print(len("Hello, Sparta!")) # 14
print(len("안녕하세요.")) # 6
- 모든 알파벳을 대문자/소문자로 바꾸기
sentence = 'Python is FUN!'
sentence.upper() # PYTHON IS FUN!
sentence.lower() # python is fun!
- split()을 사용해 문자열 나누기
# 이메일 주소에서 도메인 'gmail'만 추출하기
myemail = 'test@gmail.com'
result = myemail.split('@') # ['test','gmail.com']
result[0] # test (리스트의 첫번째 요소)
result[1] # gmail.com (리스트의 두 번째 요소)
result2 = result[1].split('.') # ['gmail','com']
result2[0] # gmail -> 우리가 알고 싶었던 것
result2[1] # com
# 한 줄로 한번에 할 수 있습니다
myemail.split('@')[1].split('.')[0]
- 특정 문자를 다른 문자로 바꾸기
txt = '서울시-마포구-망원동'
print(txt.replace('-', '>')) # '서울시>마포구>망원동'
- 슬라이싱
f="abcdefghijklmnopqrstuvwxyz"
f[1] # b
f[4:15] # efghijklmno f[4]부터 f[15] 전까지 출력
f[8:] # ijklmnopqrstuvwxyz f[8]부터 끝까지 출력
f[:7] # abcdefg 시작부터 f[7] 전까지 출력
f[:] # abcdefghijklmnopqrstuvwxyz 처음부터 끝까지 출력
리스트와 딕셔너리
- 리스트
# 순서가 있는 다른 자료형들의 모임
# 덧붙이기
a = [1, 2, 3]
a.append(5)
print(a) # [1, 2, 3, 5]
a.append([1, 2])
print(a) # [1, 2, 3, 5, [1, 2]]
# 정렬하기
a = [2, 5, 3]
a.sort()
print(a) # [2, 3, 5]
a.sort(reverse=True)
print(a) # [5, 3, 2]
# 요소 찾기
a = [2, 1, 4, "2", 6]
print(1 in a) # True
print("1" in a) # False
print(0 not in a) # True
- 딕셔너리
# 키(key)와 벨류(value)로 이루어진 자료의 모임
# 순서가 없기 대문에 인덱싱을 사용할 수 없다
person = {"name":"Bob", "age": 21}
print(person["name"])
# 값을 업데이트 하거나 새로운 자료 삽입
person = {"name":"Bob", "age": 21}
person["name"] = "Robert"
print(person) # {'name': 'Robert', 'age': 21}
person["height"] = 174.8
print(person) # {'name': 'Robert', 'age': 21, 'height': 174.8}
#딕셔너리의 밸류로는 아무 자료형이나 삽입 가능하다
person = {"name":"Alice", "age": 16, "scores": {"math": 81, "science": 92, "Korean": 84}}
print(person["scores"]) # {'math': 81, 'science': 92, 'Korean': 84}
print(person["scores"]["science"]) # 92
# 해당 키가 존재하는지 알고 싶을 때 in을 쓴다
person = {"name":"Bob", "age": 21}
print("name" in person) # True
print("email" in person) # False
print("phone" not in person) # True
- 리스트와 딕셔너리의 조합
# 딕셔너리는 리스트와 함께 자료를 정리하는데 쓰일 수 있다
people = [{'name': 'bob', 'age': 20}, {'name': 'carry', 'age': 38}]
# people[0]['name']의 값은? 'bob'
# people[1]['name']의 값은? 'carry'
person = {'name': 'john', 'age': 7}
people.append(person)
# people의 값은? [{'name':'bob','age':20}, {'name':'carry','age':38}, {'name':'john','age':7}]
# people[2]['name']의 값은? 'john'
조건문
- if문
# 조건을 만족했을 때 특정 코드를 실행하도록 하는 문법
money = 5000
if money > 3800: # money > 3800은 True
print("택시 타자!") # 택시 타자!
# 삼항연산자를 한 줄에 적을 수 있다
num = 3
result = "짝수" if num%2 == 0 else "홀수"
print(f"{num}은 {result}입니다.")
- else와 elif
# 조건을 만족하지 않을 때 다른 코드를 실행하고 싶을 때 쓰는 문법
money = 2000
if money > 3800:
print("택시 타자!")
else:
print("걸어가자...")
# 다양한 조건을 판달할 때는 elif를 쓰는 게 좋다
age = 27
if age < 20:
print("청소년입니다.")
elif age < 65:
print("성인입니다.")
else:
print("무료로 이용하세요!")
반복문
- for문
fruits = ['사과', '배', '감', '귤']
for fruit in fruits:
print(fruit) # 사과, 배, 감, 귤
for i, fruit in enumerate(fruits):
print(i,fruit) # 1 사과, 2 배, 3 감, 4 귤
# 앞에 3개만 출력
for i, fruit in enumerate(fruits):
print(i, fruit)
if i == 2:
break # 1 사과, 2 배, 3 감
# 한방에 써버리는 방법
a_list = [1, 3, 2, 5, 1, 2]
b_list = []
for a in a_list:
b_list.append(a*2)
print(b_list)
# b_list를 한줄로 변경하게 되면
a_list = [1, 3, 2, 5, 1, 2]
b_list = [a*2 for a in a_list]
print(b_list)
함수
# 함수는 반복적으로 사용하는 코드들에 이름을 붙여놓은 것
# 조건문에 넣을 값을 바꿔가면서 결과를 확인할 때 쓰면 편하다
def bus_rate(age):
if age > 65:
print("무료로 이용하세요")
elif age > 20:
print("성인입니다")
else:
print("청소년입니다")
bus_rate(27) # 성인입니다
bus_rate(10) # 청소년입니다
bus_rate(72) # 무료로 이용하세요
# 결과 값을 돌려주도록 함수를 만들 수도 있다
def bus_fee(age):
if age > 65:
return 0
elif age > 20:
return 1200
else:
return 0
money = bus_fee(28)
print(money) # 1200
튜플, 집합
- 튜플(tuple)
# 리스트와 비슷하지만 불변인 자료형
# 순서가 존재한다
a = (1,2,3)
print(a[0]) # 1
a = (1,2,3)
a[0] = 99 # 오류
- 집합(set)
# 중복이 제거되고 교집합, 합집합, 차집합을 구할 수 있다
a = [1,2,3,4,5,3,4,2,1,2,4,2,3,1,4,1,5,1]
a_set = set(a)
print(a_set) # 1, 2, 3, 4, 5
a = set(['사과','감','수박','참외','딸기'])
b = set(['사과','멜론','청포도','토마토','참외'])
print(a & b) # 교집합 # '사과', '참외'
print(a | b) # 합집합 # '토마토', '사과', '감', '딸기', '청포도', '멜론', '참외', '수박'
f-string
- 변수로 더 직관적인 문자열 만들기
scores = [
{'name':'영수','score':70},
{'name':'영희','score':65},
{'name':'기찬','score':75},
{'name':'희수','score':23},
{'name':'서경','score':99},
{'name':'미주','score':100},
{'name':'병태','score':32}
]
for s in scores:
name = s['name']
score = str(s['score'])
print(name+'는 '+score+'점 입니다')
for s in scores:
name = s['name']
score = str(s['score'])
print(f'{name}은 {score}점입니다')
예외처리
- try-except
# 어디서 에러가 났는지 알 수 없기 때문에 남용은 금물
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby'}, # age가 없는 상태
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
for person in people:
if person['age'] > 20:
print (person['name']) # 오류
for person in people:
try:
if person['age'] > 20:
print (person['name'])
except:
name = person['name']
print(f'{name} - 에러입니다') # bobby - 에러입니다
map, filter, lambda식
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7}
]
# map - 리스트의 모든 원소를 조작하기
def check_adult(person):
return ('성인' if person['age'] > 20 else '청소년')
result = map(check_adult, people)
print(list(result)) # '청소년', '성인', '청소년'
# lambda x:x
# 짧은 함수를 한 줄로 쓰고싶을 때 사용
result = map(lambda person: ('성인' if person['age'] > 20 else '청소년'), people)
print(list(result)) # '청소년', '성인', '청소년'
# filter - 리스트의 모든 원소 중 특별한 것만 뽑기
# True인 것들만 뽑기
result = filter(lambda x: x['age'] > 20, people)
print(list(result)) # {'name': 'carry', 'age': 38}
클래스
# 중앙에서 모든 것을 관리하기 힘들 때 사용
# 객체지향적
class Monster():
hp = 100
alive = True
def damage(self, attack):
self.hp = self.hp - attack
if self.hp < 0:
self.alive = False
def status_check(self):
if self.alive:
print('살아있다')
else:
print('죽었다')
m = Monster()
m.damage(120)
m2 = Monster()
m2.damage(90)
m.status_check() # 죽었다
m2.status_check() # 살아있다
'Language > Python' 카테고리의 다른 글
Python - set(), round(), str.isalpha(), list.sort() (0) | 2022.11.23 |
---|