Python/파이썬 기초

[Python] 모듈

isfp_yykkng 2023. 2. 19. 18:49

모듈

모듈 (module)

모듈 (module) : 프로그램의 기능을 독립적인 부품으로 분리한 것으로 미리 만들어진 코드를 가져와 쓰는 방법이다.

 

  • 모듈 불러오는 방법 : import <모듈이름>
  • 모듈 사용 방법 : <모듈이름> . <모듈 안의 구성요소>

모듈의 예

 

  • import math : 수학과 관련된 기능
  • import random : 무작위와 관련된 기능
  • import urllib.request : 인터넷의 내용을 가져오는 기능
  • import datetime : 날짜, 시간과 관련된 기능

예제) random 모듈을 이용한 숫자 맞추기 게임

from random import randint 

print("Welcome to Python Casino!")
pc_choice = randint(1,100)
playing = True
while playing :  
  user_choice = int(input("Choose number (1 - 100) : "))
  if user_choice == pc_choice :
    print("You won!")
    playing = False
  elif user_choice > pc_choice :
    print("Lower!")
  elif user_choice < pc_choice :
    print("Higher!")

모듈 만들기

⚠️ 사용자가 만든 모듈과 모듈을 쓸 파일이 같은 폴더에 있어야 한다!

 

1. 사용할 함수, 메소드 코드를 작성한 모듈 파일을 생성

2. 모듈이 쓰일 파일에 import를 사용하여 모듈을 호출

3. 사용 방법은 기존의 모듈과 동일하게 사용

미리 만들어진 모듈 검색하는 사이트

 

3.11.2 Documentation

Python 3.11.2 documentation Welcome! This is the official documentation for Python 3.11.2. Parts of the documentation: What's new in Python 3.11? or all "What's new" documents since 2.0 Tutorial start here Library Reference keep this under your pillow Lang

docs.python.org

 

PyPI · The Python Package Index

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

pypi.org

  • 구글에서 python 키워드와 함께 검색하기