[Python] 기초 문법 메모장

roses16·2023년 3월 26일
0

참조할만한 사이트 링크


출력

print('Hello World')

변수 선언, 대입

a = 1
b = True	# Boolean형은 첫자를 대문자로 기재한다.

javascript와 같은 동적타입 언어로 선언 시 자료형을 명시하지 않는다.

연산

a**b 	# a^b

사칙 연산과 나머지 연산은 생략한다.

String

name = 'kim'+'name'	# kimname
a = 2+'hello'		# TypeError

text = 'abcdefghijk'
len(text)			# 11		문자열 길이출력
text[:3]			# abc		index 3번까지 출력(3 미포함)
text[3:]			# defghijk	index 3번부터 출력
text[3:6]			# de 		index 3번부터 6번까지 출력(6미포함)
text[:]				# 동일한 텍스트 복사

text.split('c')		# ['ab', 'defghijk ']

List

a_list = ['A', 'B', 'C']
a_list[0]					# 'A'
a_list[1:2]					# 'B' index 1번부터 2번까지 출력(2 미포함)
len(a_list)					# List의 길이 출력
a_list.append('D')			# List의 가장 마지막에 'D'추가
a_list.sort()				# 정렬
a_list.sort(reverse=True)	# 정렬 역순
result = ('A' in a_list)	# 'A'가 a_list 내에 있는지를 Boolean값으로 반환

Dictionaty

a_dict = {'name':'bob', 'age':10}
a_dict['height'] = 170			# 값 추가
result = ('height' in a_dict)	# 'height'가 a_dict 내에 있는지를 Boolean으로 반환

조건문

if a < 1000:
	print('1,000보다 작음')
elif a < 2000:
	print('1,000보다 크고 2,000보다 작음')
else:
	print('2,000보다 큼')

대부분의 언어는 일반적으로 {}를 사용하여 실행 구문을 구분하나, Python은 들여쓰기로 구분한다.

반복문

a_list = ['A', 'B', 'C']

for a in a_list:
	print(a)
    
for i, a in enumerate(a_list):
	print(i, a)		# i에 index를 출력한다.
    if(i > 2):
    	break;

함수

def hello(str='Stranger!'):	# 함수 선언 Default 값 설정
	print('Hello')
    print(str)
    return 'Bye '+str
    
result = hello('World!')	# Hello World!	함수 호출
print(result)				# Bye World!	리턴 값 출력

hello(str='World!')			# 매개변수 명을 지정하여 전달할 수 있다.

args, kwargs

def hello(*args)
	for e in args
    	print(e)
        
# 매개변수를 갯수의 제한없는 list로 받을 때 사용한다.
def hello(*kwargs)
	print(kwargs)
    
hello(name='Bob', age=25, weight=70)
# 매개변수를 dictionary로 받을 때 사용한다.

Tuple

a_tuple = ('A', 'B', 'C')

a_tuple[0] = 'Z'		# TypeError

List와 동일한 형태이나 값을 변경할 수 없다.

Set

a_list = [1, 2, 3, 4, 5, 1, 2, 3]
b_list = [4, 4, 5, 6, 7]

a_set = set(a_list)		# 1, 2, 3, 4, 5
b_set = set(b_list)		# 4, 5, 6, 7
# List를 통해 생성되며 중복을 제거한 값을 반환한다.

a_set & b_set		# 교집합 4, 5
a_set | b_set		# 합집합 1, 2, 3, 4, 5, 6, 7
a_set - b_set		# 차집합 1, 2, 3
b_set - a_set		# 차집합 6, 7

f-string

name = 'Bob'
age = 18

print(f'{name}{age}세 이다.')	# Bob은 18세이다.

예외처리, try-except 문

try:
	# 실행할 내용
except:
	# 위 try구문에서 Error 발생 시 실행할 내용

파일 불러오기

# a_func.py
def say_hello():
	print('hello')
from a_func import *	# 함수명으로 import도 가능하다. from a_func import say_hello 

say_hello()

삼항연산자

'짝수' if num % 2 == 0 else '홀수'

True일 경우 값 if 조건문 else False일 경우 값

한 줄 반복문

a_list = [1, 2, 3, 4, 5]
b_list = [a*2 for a in a_list]	# [2, 4, 6, 8, 10]

map

list_people = [{'name', 'bob', 'age': 25}, ...]

def check_adult(person):
	return '성인' if person['age'] else '청소년'
    
result = map(check_adult, list_people)
print(list(result))	# ['성인', ...]

map(함수명, List명) 의 형태로 작성한다.
list_people 내 각각의 요소를 check_adult의 매개변수 person에 대입한 값을 반환한다.

filter

list_people = [{'name', 'bob', 'age': 25}, ...]

def check_adult(person):
	return person['age'] > 20
    
result = filter(check_adult, list_people)
print(list(result))	# [{'name', 'bob', 'age': 25}, ...]

filter(함수명, List명) 의 형태로 작성한다.
함수의 return값이 True인 요소만 반환한다.

result = filter(lambda x: x['age'] > 20, list_people)

람다식을 사용할 때에는 관용적으로 매개변수 명을 x로 사용한다.

lambda

(lambda x, y: x + y)(10, 20)

함수 선언을 단순화 하는 형태의 구문. lambda 매개변수 : 표현식 형태로 선언한다.

list_people = [{'name', 'bob', 'age': 25}, ...]
result = map(lambda person: '성인' if person['age'] else '청소년', list_people)
# ['성인', ...]

위 map 예제를 위와 같이 작성할 수 있다.

Class

class Monster():	# 클래스 선언
    hp = 100

    def damage(self, attack):		# self, JavaScript의 this와 같은 역할
        self.hp = self.hp - attack

m = Monster()		# 인스턴스 생성
m2 = Monster()

m.damage(120)
m2.damage(90)

📌 출처

  • Sparta coding club 강의
profile
frontend developer 📚

0개의 댓글