포시코딩

파이썬 기본 문법 본문

Python

파이썬 기본 문법

포시 2022. 11. 21. 17:50
728x90
# 자주 쓰이는 파이썬 문법 한눈에 보기

str.isalpha()  # 문자열이 알파벳인지 확인하는 함수

# 알파벳의 ASCII code 변환
ord('a')  # 97
chr(97)  # 'a'

# 숫자 내림(몫만 남기기)
print((4 + 5) / 2)  # 4.5
print((4 + 5) // 2)  # 4

# 서로 swap하기
a, b = b, a

 

문자로 바꿀땐

str()

숫자로 바꿀땐

int()

 

len()

-> 문자열 길이

 

문자열 슬라이싱

f="abcdefghijklmnopqrstuvwxyz"

f[4:15]  # efghijklmno           f[4]부터 f[15] 전까지, 총 15-4=11개!

f[8:]    # ijklmnopqrstuvwxyz    f[8]부터 끝까지, 앞의 8개 빼고!
f[:7]    # abcdefg               시작부터 f[7] 전까지, 앞의 7개!

f[:]     # abcdefghijklmnopqrstuvwxyz  처음부터 끝까지

 

str.split('a')

-> js와 동일

 

리스트(list)

-> Array

-> list.append(a)  # 추가

-> list.sort()  # 정렬

-> (a in list)  # a가 list에 있는지 확인 가능

 

딕셔너리(dictionary)

-> Object

-> ('name' in dictionary)  # list와 마찬가지로 사용 가능

 

if문

if False:

elif False:

else True:

 

반복문

fruits = ['사과', '배', '감', '귤']

for fruit in fruits:
    print(fruit)

enumerate를 통해 인덱스 받기

for i, person in enumerate(people):
    name = person['name']
    age = person['age']
    print(i, name, age)
    
fruits = ['사과', '배', '감', '귤','귤','수박','참외','감자','배','홍시','참외','오렌지']
for i, fruit in enumerate(fruits):
    print(i, fruit)
    if i == 4:
        break

break를 통해 멈출 수도 있다.

 

튜플 (tuple)

-> list와 똑같은 순서가 있는 자료형

-> [] 대신 () 를 쓴다. 

-> 불변형이라 값을 바꿀 수 없다.

딕셔너리와 비슷하게 값을 만들어 사용할 때 사용하기도 한다.

a_dict = [{'name': 'bob', 'age': 24}, {'name': 'john', 'age': 29}]
a_dict = [('bob',24),('john',29)]

 

집합 (set)

-> 중복 제거

-> 교집합, 합집합 구할 수 있다.

a = ['사과','감','수박','참외','딸기']
b = ['사과','멜론','청포도','토마토','참외']

print(a & b)  # 교집합
print(a | b)  # 합집합

# A에 대한 B의 차집합
print(a - b)

 

f-string

# 원래라면
print(name+'는 '+score+'점 입니다')
# f-string을 쓸 경우
print(f'{name}은 {score}점입니다')

 

에러처리

for person in people:
    try:
        if person['age'] > 20:
            print (person['name'])
    except:
        name = person['name']
        print(f'{name} - 에러입니다')

js에서의 try-catch와 같다. 

 

파일 불러오기

from main_func import *
from 불러올_파이썬_파일_이름 import 블러올_함수

 

삼항연산자 - if문 한 번에 쓰기

result = "짝수" if num%2 == 0 else "홀수"
# (참일 때 값) if (조건) else (거짓일 때 값)

 

for문 한 번에 쓰기

a_list  = [1, 3, 2, 5, 1, 2]

# before
b_list = []
for a in a_list:
    b_list.append(a*2)

# after
b_list = [a*2 for a in a_list]

 

map

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

def check_func(person):
    return '성인' if person['age'] > 20 else '청소년'

result = list(map(check_func, people))
# map을 통해 나온 결과는 아직 map 타입이기 때문에 list에 넣어준다.
print(result)

 

람다 (lambda)

위에서 map을 쓸 때 함수를 만들어 사용했는데 js의 콜백함수 처럼 lambda를 이용해 표현할 수 있다.

# (lambda x: x, function)
result = list(map(lambda person: '성인' if person['age'] > 20 else '청소년', people))
# 처음 써보는 예제라 person이라 칭했고 보통은 x로 많이 쓴다. 
result = list(map(lambda x: '성인' if x['age'] > 20 else '청소년', people))

 

필터 (filter)

result = list(filter(lambda person: person['age'] > 20, people))
result = list(filter(lambda x: x['age'] > 20, people))

 

함수 심화

# 매개변수 지정
def cal(a, b):
    return a + 2 * b

print(cal(a=3, b=5))
print(cal(b=5, a=3))

# 디폴트 값 지정
def cal2(a, b=3):
    return a + 2 * b
    
# js의 rest parameter
def call_names(*args):
    for name in args:
        print(f'{name}야 밥먹어라~')

call_names('철수','영수','희재')

# 키워드 인수를 여러 개 받는 방법
def test(**kwargs):
    print(kwargs)

test(name='bob', age=5)  # {'name': 'bob', 'age': 5}

 

클래스

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()
728x90