Python 기초 실습 C3

Python 기초 실습 C3입니다. 조건문, 반복문, list 처리, list comprehension, 사용자 입력 검증과 실행 방법을 정리했습니다.

Python 기초 실습 C3

C3 실습은 조건문, 반복문, list 처리 흐름을 다룬다. Python 기본 문법을 익힐 때 가장 중요한 지점은 입력값을 받고, 조건에 따라 분기하고, 여러 데이터를 반복 처리하는 구조를 손에 익히는 것이다.

조건문

score = 82

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"grade={grade}")

반복문과 list

ports = [22, 80, 443, 8080]

for port in ports:
    print(f"check port: {port}")

조건과 반복 조합

운영 스크립트에서는 특정 범위의 값만 골라 처리하는 일이 많다. 아래 예시는 유효한 TCP port만 추려낸다.

candidate_ports = [0, 22, 80, 443, 65535, 70000]
valid_ports = []

for port in candidate_ports:
    if 1 <= port <= 65535:
        valid_ports.append(port)

print(valid_ports)

list comprehension

candidate_ports = [0, 22, 80, 443, 65535, 70000]
valid_ports = [port for port in candidate_ports if 1 <= port <= 65535]

print(valid_ports)

사용자 입력 처리

raw = input("port> ").strip()

if raw.isdigit():
    port = int(raw)
    if 1 <= port <= 65535:
        print(f"{port} is valid")
    else:
        print("port range must be 1-65535")
else:
    print("number only")

실행

mkdir -p python-c3
cd python-c3
vi main.py
python main.py

정리

  • if/elif/else로 조건을 분기한다.
  • for로 list 값을 순서대로 처리한다.
  • append로 새 결과 list를 만든다.
  • 짧고 명확한 필터링은 list comprehension으로 표현할 수 있다.
  • 사용자 입력은 문자열이므로 숫자 변환 전에 검증한다.
BGM EVER