한양과학기술고등학교

에듀테크 프로젝트 대시보드

표준 입출력

print input sys.argv sep end

input() 은 항상 문자열을 돌려주고, print() 는 여러 옵션을 받습니다.

1. print() 심화

print("a", "b", "c")                  # a b c
print("a", "b", sep="-")             # a-b
print("진행 중", end="")             # 줄바꿈 안 함
print("2024", "01", "15", sep="-")   # 2024-01-15

import sys
print("에러 메시지", file=sys.stderr)  # 표준 에러로
print("즉시 출력", flush=True)          # 버퍼 비우기

2. input()

name = input("이름: ")          # 반환값은 항상 str
age = int(input("나이: "))       # 숫자는 직접 변환

# EOF(파이프 끝)나 잘못된 입력 대비
try:
    n = int(input())
except (EOFError, ValueError):
    n = 0

3. 여러 값 한 줄 입력

# "10 20 30" 입력
a, b, c = input().split()               # 문자열 3개
a, b, c = map(int, input().split())     # 정수 3개
nums = list(map(int, input().split()))  # 개수 모를 때 리스트

# 여러 줄 (N줄) 읽기
n = int(input())
data = [input() for _ in range(n)]

4. sys — argv 와 스트림

import sys

# python script.py foo 42
sys.argv           # => ['script.py', 'foo', '42']
name = sys.argv[1] if len(sys.argv) > 1 else "default"

# 대량 입력은 sys.stdin 이 input() 보다 빠름
import sys
data = sys.stdin.read().split()
for line in sys.stdin:
    process(line.rstrip())

5. 서식 있는 출력

headers = ["이름", "점수"]
print(f"{headers[0]:<10}{headers[1]:>6}")
print("-" * 16)
for name, score in [("김", 92), ("이", 88)]:
    print(f"{name:<10}{score:>6}")

6. pprint 와 리다이렉트

from pprint import pprint
pprint({"users": [{"id": 1}, {"id": 2}], "count": 2})

# 파일로 출력
with open("out.txt", "w", encoding="utf-8") as f:
    print("로그 한 줄", file=f)
"가독성은 중요하다 (Readability counts)"