logoRawon_Log
홈블로그소개

Built with Next.js, Bun, Tailwind CSS and Shadcn/UI

Python

Python beginner - Data Structure

Rawon
2025년 9월 3일
목차
Python 기초 문법 - Data Structure
List
Tuple
Dictionary
For Loops
URL Formatting
Requests
Status Code

목차

Python 기초 문법 - Data Structure
List
Tuple
Dictionary
For Loops
URL Formatting
Requests
Status Code

Python 기초 문법 - Data Structure

List

python
days_of_week = ["Mon", "Tue", "Wed", "Thu", "Fri"]

days_of_week.count("Wed") # 1, value가 List 내부에 몇개 존재하는지 count
days_of_week.clear() # List 내부 아이템을 모두 삭제, 빈배열로 만듦.
days_of_week.reverse() # ["Fri", "Thu", "Wed" ...] 과 같이 배열 요소의 순서를 역순으로 만듦
days_of_week.append("Sat") # List의 마지막 부분에 value 추가
days_of_week.remove("Fri") # List에서 value 와 일치하는 아이템을 삭제

print(days_of_week[0]) # Mon
  • 잠깐! 메서드에 대해 소개하자면 아래와 같음
  • ⭐️ 메서드는 데이터에 결합된 function 을 의미함! 그러므로 메서드만 단독으로 사용할 수 없음.
  • docs.python.org/ko/3/library
python
# 예시) 문자열 메서드
name = "Jung"

print(name.upper())  # JUNG
print(name.capitalize()) # Jung
print(name.startswith("j")) # True
print(name.replace("j", "k")) # kung
# upper() 메서드는 소문자를 대문자로 변환해주는 기능을 갖고 있음
# capitalize() 메서드는 문자열의 첫번째 문자만 대문자로 변환
# startswith() 메서드는 문자열의 첫번째 문자가 () 안에 들어가는 문자와 일치하는지 판단
# replace() 메서드는 old string을 첫번째 파라미터로 받아 이를 두번째 인자로 대체

Tuple

  • List와 비슷하지만 차이점이 있음.
    • Tuple은 불변성을 갖음. 즉, 생성한 후 튜플의 값을 변경할 수 없다는 의미.
    • 그렇기 때문에 append, remove 등과 같은 메서드가 없고 딱 2개(count, index) 밖에 없음
  • 선언 방법은 간단함.
    • List는 대괄호[]를 사용하는 대신, Tuple은 소괄호()로 감싸주면 됨.
python
days = ["Mon", "Tue", "Wen"]  # List

days = ("Mon", "Tue", "Wen")  # Tuple

Dictionary

  • dict 즉, 백과사전을 떠올려보면 무수히 많은 단어와 그 정의가 적혀있는걸 연상할 수 있음.
  • 그대로 그 단어와 정의가 key - value pair 로 되어있는 자료구조가 Dictionary {} 임!
  • dict 도 메서드가 있음! 예를 들어 copy, get 등
python
player = {
  'name' : 'jung',
  'age' : 12,
  'alive' : True,
  'fav_food' : ["pizza", "burger"]
}

print(player) # {'name' : 'jung', 'age' : 12, 'alive' : True, 'fav_food' : ["pizza", "burger"]}
print(player.get('age'))  # 12
print(player.get('fav_food')) # ['pizza', 'burger']
print(player['fav_food']) # ['pizza', 'burger']

print(player.pop('age')) # 'age' 쌍만 제거, {'name' : 'jung', 'alive' : True, 'fav_food' : ["pizza", "burger"]}
player['xp'] = 1500  # dict에 xp라는 키와 1500이라는 value를 추가
print(player)  # {'name' : 'jung', 'alive' : True, 'fav_food' : ["pizza", "burger"], 'xp' : 1500}

For Loops

  • for 반복문
python
numbers = [0,1,2,3,4,5]
for x in numbers:
  print("hello", x)
  • 예시) tuple 안에 있는 각각의 item을 사용해서 코드를 실행
python
websites= (
  "google.com",
  "aribnb.com",
  "twitter.com",
  "facebook.com"
)

# for 반복문이 실행될 때, for는 각각의 item이 실행될 때 placholder를 만드는 것을 허락해줌
for website in websites:
  print("hello", website)  #   hello google.com, hello aribnb.com, hello twitter.com, hello facebook.com

# 관습적으로 list나 tuple은 복수형 이름을 붙이고 반복문의 placeholder는 단수형을 사용함.

URL Formatting

  • if not : 무언가가 True가 아닌 경우가 True
  • string에 변수를 넣는 방법 : f"{변수}"
python
websites= (
  "google.com",
  "aribnb.com",
  "https://twitter.com",
  "facebook.com",
  "https://tiktok.com"
)

for website in websites:
  if not websit.startswith("https://"):  # website가 https://로 시작하지 않는 경우
    website = f"https://{website}"  # string에 변수를 넣는 방법 : f"{변수}"

Requests

  • 이번엔 Python Standard Library에 기본으로 포함되어 있지 않은 모듈을 사용해보려 함.
  • pypi 는 다른 사람이 만든 projects나 modules 를 모아놓은 곳임.
  • 이 중에서 requests 를 사용해보려 함. requests는 내 Python 코드에서 웹사이트로 request를 보내는 걸 할 수 있게 해줌
  • 예를 들어 내가 구글로 이동한다는건 브라우저가 Google 서버에 request를 보내고 Google 서버는 브라우저에게 웹사이트를 보내준 결과이며, 이러한 작업을 request가 수행.
python
from requests import get # 패키지 import

Status Code

  • get function은 response를 return 함.
  • 인터넷은 HTTP Protocol에 기반함. 그래서 컴퓨터들이 서로 소통하는 방식은 당연하게도 HTTP request임
  • 그래서 request 가 정상인지 아닌지를 알 수 있는 수단이 있어야 하는데, 이러한 결과를 확인하는 방법으로 HTTP 코드를 사용함
  • 이를 Status Code 라고 하며, 100번~500번대까지 있으며, 각각 다른 의미를 가짐.
python
from requests import get

websites= (
  "google.com",
  "aribnb.com",
  "https://twitter.com",
  "facebook.com",
  "https://tiktok.com"
)

for website in websites:
  if not websit.startswith("https://"):  
    website = f"https://{website}"  
  response = get(website)
  print(response.status_code) # 200 200 200 200 200, 웹사이트가 성공적으로 응답함을 의미

이 링크를 통해 구매하시면 제가 수익을 받을 수 있어요. 🤗

https://inf.run/Trxxf