Skip to content

Latest commit

 

History

History
180 lines (135 loc) · 3.54 KB

basics.md

File metadata and controls

180 lines (135 loc) · 3.54 KB

기본 문법

파이썬 문법이 가물가물할 때 빠르게 훑는 기본 문법 문서입니다.

기본 형태

import sys

input = sys.stdin.readline  # -> 빠른 입력으로 대체


def solve():
    pass  # -> 풀이 함수 자리


if __name__ == "__main__":
    solve()  # -> 프로그램 시작점

변수와 형변환

x = 10  # -> 10
y = 3.14  # -> 3.14
name = "python"  # -> "python"
flag = True  # -> True

int("123")  # -> 123
str(123)  # -> "123"
float("3.14")  # -> 3.14
bool(1)  # -> True

입력과 출력

n = int(input())  # -> "3\n" 입력 시 3
a, b = map(int, input().split())  # -> "10 20\n" 입력 시 a=10, b=20
arr = list(map(int, input().split()))  # -> "1 2 3\n" 입력 시 [1, 2, 3]
s = input().strip()  # -> "hello\n" 입력 시 "hello"
digits = list(map(int, input().strip()))  # -> "123\n" 입력 시 [1, 2, 3]

print(answer)  # -> answer 값 출력
print(*arr)  # -> [1, 2, 3] 이면 "1 2 3"
print("\n".join(result))  # -> ["a", "b"] 이면 "a\nb"

연산자

7 + 3  # -> 10
7 - 3  # -> 4
7 * 3  # -> 21
7 / 3  # -> 2.3333333333333335
7 // 3  # -> 2
7 % 3  # -> 1
2 ** 5  # -> 32

3 == 3  # -> True
3 != 4  # -> True
5 > 2  # -> True
5 >= 5  # -> True
2 < 5  # -> True
2 <= 2  # -> True

조건문

if x > 0:
    print("positive")  # -> x가 양수면 출력
elif x == 0:
    print("zero")  # -> x가 0이면 출력
else:
    print("negative")  # -> x가 음수면 출력

result = "YES" if flag else "NO"  # -> flag=True 이면 "YES"

반복문

for i in range(5):  # -> 0, 1, 2, 3, 4
    print(i)

for x in [10, 20, 30]:  # -> 10, 20, 30
    print(x)

for i, x in enumerate(["a", "b"]):  # -> (0, "a"), (1, "b")
    print(i, x)

for x, y in zip([1, 2], [3, 4]):  # -> (1, 3), (2, 4)
    print(x, y)

while n > 0:  # -> n이 0이 될 때까지 반복
    n -= 1

리스트

arr = [1, 2, 3]  # -> [1, 2, 3]
zeros = [0] * 5  # -> [0, 0, 0, 0, 0]
matrix = [[0] * m for _ in range(n)]  # -> n x m 2차원 리스트

arr[0]  # -> 첫 번째 값
arr[-1]  # -> 마지막 값
arr[1:4]  # -> 인덱스 1부터 3까지
arr[::-1]  # -> 뒤집힌 리스트

arr.append(4)  # -> 끝에 4 추가
arr.pop()  # -> 마지막 값 제거 후 반환
len(arr)  # -> 원소 개수
sum(arr)  # -> 원소 합
max(arr)  # -> 최댓값
min(arr)  # -> 최솟값

주의:

matrix = [[0] * m] * n  # -> 내부 리스트가 같은 객체를 공유함

문자열

s = "hello"  # -> "hello"
len(s)  # -> 5
s[0]  # -> "h"
s[-1]  # -> "o"
s[:3]  # -> "hel"
s[1:4]  # -> "ell"
s[::-1]  # -> "olleh"

s.split()  # -> 공백 기준 분리
" ".join(["a", "b", "c"])  # -> "a b c"
s.replace("l", "x")  # -> "hexxo"
s.lower()  # -> "hello"
s.upper()  # -> "HELLO"

딕셔너리와 집합

d = {}  # -> 빈 딕셔너리
d["a"] = 1  # -> {"a": 1}
d.get("a", 0)  # -> 1
d.get("x", 0)  # -> 0

s = set()  # -> 빈 집합
s.add(1)  # -> {1}
s.add(2)  # -> {1, 2}
1 in s  # -> True
3 not in s  # -> True
s.discard(3)  # -> 없어도 에러 없음

함수

def add(a, b):
    return a + b  # -> add(2, 3)은 5


def solve():
    n = int(input())  # -> 정수 하나 입력
    print(n)  # -> 그대로 출력

assert

assert x > 0  # -> 조건이 거짓이면 AssertionError
assert len(arr) == n  # -> 길이가 다르면 AssertionError
  • 입력 가정이나 디버깅 중 확인하고 싶은 조건을 빠르게 검사할 때 쓴다.
  • 제출 코드에서는 없어도 되는 검사는 제거하는 편이 보통 더 안전하다.