Language/Python

노마드코더 파이썬챌린지 6일차

은하윤슬 2023. 3. 19. 21:18

For

 

for문의 기본 구조는 다음과 같다.

for 변수 in 리스트(or tuple, string):
	수행할 문장1
	수행할 문장2
	...

리스트 혹은 튜플, 문자열의 첫번째 요소부터 마지막 요소까지 차례대로 변수에 대입되어 수행할 문장들이 실행된다.

websites = (
  "google.com",
  "airbnb.com",
  "https://twitter.com",
  "facebook.com",
  "https://tiktok.com"
)
for website in websites:
  if website.startswith("https://"):
	print("good to go")
  else:
	print("we have to fix it")

website에 들어가는 변수명은 자유롭게 작성 가능하다.

websites에 들어있는 요소들을 검사하여 만약 website 첫 문자에 "http://" 단어가 들어간다면 good to go,

그렇지 않다면 we haver to fix it 문장을 출력해주는 코드이다.

만약 모든 websites 변수들 앞에 http://단어를 추가해주려면 어떻게 해야할까?

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

for website in websites:
  if not website.startswith("https://"):
    website = f"https://{website}"
  print(website)

 

format 함수를 사용하여 website의 시작 단어가 http://가 아닌 경우 http://로 시작하게 수정해주면 된다.

 

다음 링크는 다른 사람들이 만든 프로젝트나 모듈을 볼 수 있는 곳이다.

 

https://pypi.org/

 

PyPI · The Python Package Index

The Python Package Index (PyPI) is a repository of software for the Python programming language.

pypi.org

파이썬은 다른 사람들이 만든 모듈을 다운받아와 사용할 수 있는데,

 

이 수업에서는 requrests의 get 메서드를 받아와 사용하였다.

 

from requests import get

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

for website in websites:
  if not website.startswith("https://"):
    website = f"https://{website}"
  response = get(website)
  print(response.status_code)

다음을 출력하면 response 200이 출력된다.

http response는 컴퓨터들이 소통하는 방식으로

request가 정상인지 아닌지 판단하는 방법으로 HTTP 코드를 사용한다.

 

response 200은 웹사이트가 성공적으로 응답했다는 것이다.

 

다음 코드와 모듈을 활용하여 딕셔너리로 묶어줄 수 있는데, 해당 코드는 다음과 같다.

 

results = {}

for website in websites:
  if not website.startswith("https://"):
    website = f"https://{website}"
  response = get(website)
  if response.status_code == 200:
    results[website] = "OK"
  else:
    results[website] = "FAILED"

print(results)