변수 선언
# 기본 변수 선언
x = 10 # 정수
name = "데브선" # 문자열
is_dev = True # 불리언
# 다중 변수 선언
a, b, c = 1, 2, 3 # 동시 선언
x = y = z = 0 # 동일 값 선언
# 타입 변환
int("25") # 문자열 → 정수
float(10) # 정수 → 실수
타입 |
설명 |
예시 |
int |
정수 |
1, 100, -10 |
float |
실수 |
3.14, -2.5 |
str |
문자열 |
"Hello" |
list |
리스트 |
[1, 2, 3] |
tuple |
튜플 |
(1, 2, 3) |
dict |
딕셔너리 |
{"name": "seon", "age": 25} |
set |
집합 |
{1, 2, 3} |
bool |
참/거짓 |
True, False |
함수 정의
def 함수이름(매개변수1, 매개변수2 = 기본값):
# 들여쓰기
실행할_코드
return 반환값
------------------------------
def add(a, b):
return a + b
print(add(1, 2)) # 3
------------------------------
def greet(name = "Seon"):
print(f"Hello, {name}!")
greet() # Hello, Seon!
greet("Dev") # Hello, Dev!
------------------------------
# 람다 함수
add = lambda a, b: a + b
print(add(1, 2)) # 3
조건문
x = 10
if x > 0: # if: 조건이 참일 때 실행
print("양수")
elif x == 0: # elif: 두 번째 조건
print("0")
else: # else: 나머지 경우
print("음수")
# 삼항 연산자
result = "성인" if age >= 20 else "미성년자"
반복문
#range ()
for i in range(5):
print(i) # 0, 1, 2, 3, 4
def solution():
result = []
for i in range(5):
result.append(i)
return result
print(solution()) # [0, 1, 2, 3, 4]
--------------------------------------
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
def solution():
result = []
for i in range(1, 6):
result.append(i)
return result
print(solution()) # [1, 2, 3, 4, 5]
--------------------------------------
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
def solution():
result = []
for i in range(0, 10, 2):
result.append(i)
return result
print(solution()) # [0, 2, 4, 6, 8]
--------------------------------------
text = "Hello"
for char in text:
print(char) # H, e, l, l, o
def solution():
result = []
text = "Hello"
for char in text:
result.append(char)
return result
print(solution()) # ['H', 'e', 'l', 'l', 'o']
----------------------------------------------
fruits = ['apple', 'grape', 'cherry']
for fruit in fruits:
print(fruit) # apple, grape, cherry
def solution():
result = []
fruits = ['apple', 'grape', 'cherry']
for fruit in fruits:
result.append(fruit)
return result
print(solution()) # ['apple', 'grape', 'cherry']
--------------------------------------------------
# 한 줄 반복문
def solution():
arr = [i for i in range(5)]
return arr
print(solution()) # [0, 1, 2, 3, 4]
리스트
arr = [1, 2, 3]
arr.append(4) # 끝에 추가 [1, 2, 3, 4]
arr.pop() # 마지막 요소 제거 및 반환 [1, 2, 3]
arr.remove(2) # 값이 2인 첫 번째 항목 제거 [1,3]
arr.sort() # 오름차순 정렬 [1,3]
arr.reverse() # 내림차순 정렬 [3,1]
arr.sort(reverse=True) # 내림차순 정렬 [3.1]
--------------------------------------------------------
numbers = [0, 1, 2, 3, 4, 5]
first_three = numbers[:3] # [0, 1, 2]
last_two = numbers[-2:] # [4, 5]
middle = numbers[1:4] # [1, 2, 3]
클래스
class 클래스이름:
# 클래스 변수 (모든 인스턴스가 공유)
클래스_변수 = 값
# 생성자 메서드 (객체 초기화)
def __init__(self, 매개변수들):
# 인스턴스 변수 (각 객체마다 고유)
self.인스턴스_변수 = 매개변수
# 일반 메서드
def 메서드_이름(self, 매개변수들):
# 메서드 내용
return 값
--------------------------------------
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce_name(self):
return f"제 이름은 {self.name}입니다."
def introduce_age(self):
return f"저는 {self.age}살입니다."
kim = Person("데브선", 25)
print(kim.introduce_name()) # "제 이름은 데브선입니다."
print(kim.introduce_age()) # "저는 25살입니다."