#Python - 20. 파이썬 모듈 사용하기
본문 바로가기
Programming/Python

#Python - 20. 파이썬 모듈 사용하기

by 권가 2020. 1. 22.

이번 시간은 Python의 다양한 모듈을 사용해보도록 하겠습니다.


import math
r = 10
print('반지름이', r, '인 원의 넓이는', 2*math.pi*r)
random_no = 2.41253
print('{}내림={}'.format(random_no, math.floor(random_no)))
print('{}올림={}'.format(random_no, math.ceil(random_no)))

C: #include<math.h>

자바: import java.lang.Math;

이와 같이 파일을 가져와 사용할 수 있습니다.

Line 3: Python에서 제공하는 math.pi(3.1415926535897)를 사용해 원의 넓이를 구해보았고

Line 5: Python에서 제공하는 math.floor(내림)를 사용해 내림 연산을 실행해보았고

Line 6: Python에서 제공하는 math.ceil(올림)를 사용해 올림 연산을 실행해보았습니다.


import random
random_list = [1, 2, 3, 4, 5, 6]
selected = random.choice(random_list)
print('첫 번째:', selected)
selected = random.choice(random_list)
print('두 번째:', selected)
selected = random.choice(random_list)
print('세 번째:', selected)
selected = random.choice(random_list)
print('네 번째:', selected)
selected = random.choice(random_list)
print('다섯 번째:', selected)

random 모듈을 가져와 사용해보았습니다.

리스트(random_list)를 만들고 random.choice(무작위 선택) 메서드를 이용해 무작위로 수를 뽑아보았습니다.

매번 selected = random.choice(random_list)를 실행 후 selected 값이 바뀌는 것은 당연한 것이죠!


def get_web(url):
    import urllib.request
    response = urllib.request.urlopen(url)
    data = response.read()
    decoded = data.decode('utf-8')
    return decoded

url = input('웹 페이지 주소: ')
content = get_web(url)
print(content)

웹의 html 코드를 가져오는 모듈을 사용해보았습니다.

http://example.com url(주소)의 소스를 가져오는 코드를 작성해보았습니다.


모듈이란?

만들어진 코드의 묶음을 가져와 사용하는 것

import <모듈이름>

사용 법: 모듈이름.내장메서드

댓글