Search

기본적인 모듈

random
math
time
이렇게, 3가지 모듈들은 자주 사용하니 사용방법을 잘 알고 있어야 한다.

math 모듈

fabs() : 절댓값
import math print(math.fabs(-10))
Python
복사
ceil() : 올림
math.ceil(5.21) # -> 6 math.ceil(-5.21) # -> -5
Python
복사
floor() : 내림
math.floor(5.21) # -> 5 math.floor(-5.21) # -> -6
Python
복사
trunc() : 버림
math.trunc(5.21) # -> 5 math.trunc(-5.21) # -> -5
Python
복사
gcd() : 최대공약수
math.gcd(14,21) # -> 7
Python
복사
factorial() : 팩토리얼
math.factorial(10) # -> 10!
Python
복사
sqrt() : 제곱근
math.sqrt(4) # -> 2
Python
복사

random 모듈

random() : 0 ~ 1 사이의 아무 난수를 무작위 출력
import random random.random()
Python
복사
randrange(start,stop,step) : 특정 범위에서 정수를 무작위 출력
random.randrange(1,7) # 1 ~ 6의 범위에서 무작위 정수 출력
Python
복사
shuffle() : 특정 시퀀스 변수를 무작위 순서로 섞어준다
abc = ['a', 'b', 'c', 'd', 'e'] random.shuffle(abc) # ['a', 'd', 'e', 'b', 'c']
Python
복사
choice() : 아무 원소를 뽑아준다
random.choice(abc) # 'a' random.choice('abcdefghijk') # 'c'
Python
복사
uniform() : 두 범위에서 임의의 실수 출력
random.uniform(1,10) # 1.1800146073117523
Python
복사
randint() : 두 범위에서 임의의 정수 출력(마지막 범위에 있는 숫자도 포함한다) randrange()
random.randint(1,10) # 1~10까지의 범위에서 임의의 정수 출력 # 7
Python
복사
sample() : 랜덤하게 여러 개의 원소를 선택
random.sample([1,2,3,4,5], 3) # 3개의 원소를 선택 # [4,1,5]
Python
복사

time 모듈

localtime() : 현재 로컬 시간을 반환
import time time.localtime() # -> time.struct_time(tm_year, tm_mon, tm_mday,...) # year 만 출력 lt = time.localtime() lt.tm_year # month 만 출력 lt.tm_mon # day만 출력 lt.tm_mday # hour 만 출력 lt.tm_hour # min lt.tm_min # sec lt.tm_sec # 요일 lt.tm_wday
Python
복사

중급 문제 풀이_모듈

import passOrfail as pf # 과목별 점수를 입력하면 합격 여부를 출력하는 모듈을 만들어보자. # (평균 60이상 합격, 과락 40으로 한다) if __name__ == '__main__': sub1 = int(input('과목1 점수 입력: ')) sub2 = int(input('과목2 점수 입력: ')) sub3 = int(input('과목3 점수 입력: ')) sub4 = int(input('과목4 점수 입력: ')) sub5 = int(input('과목5 점수 입력: ')) pf.exampleResult(sub1, sub2, sub3, sub4, sub5) # 아래는 모듈 파일이라고 하자. # 모듈 파일 이름: passOrfail def exampleResult(s1,s2,s3,s4,s5): total = s1 + s2 + s3 + s4 + s5 avg = round(total / 5,1) score_list = [s1,s2,s3,s4,s5] cnt = 0 for i in score_list: if i >= 40: print(f'{i} : Pass') elif i < 40: print(f'{i} : Fail') cnt += 1 print(f'총점 : {total}') print(f'평균 : {avg}') if avg >= 60 and cnt == 0: print('Final Pass!!') else: print('Final Fail!!')
Python
복사
# 상품 구매 개수에 따라 할인율이 결정되는 모듈을 만들고, 계산 결과를 나타내자. # 1개 : 5%, 2개 : 10%, 3개 : 15%, ... 5개 이상: 25% import discount as dc if __name__ == '__main__': flag = True n = [] while flag: selectNum = int(input('1.구매, 2.종료')) if selectNum == 1: goodsPrice = int(input('상품 가격 입력: ')) n.append(goodsPrice) elif selectNum == 2: result = dc.discountPrice(n) flag = False print(f'할인율: {result[0]}%'} print(f'합계: {result[1]}원') # -------------------------------------------------------------------- # 모듈 discount.py 파일이라고 하자 def discountPrice(n): # 인자로 상품의 가격 개수가 들어간다. # 할인율 설정 rate = 25 totalPrice = 0 rates = {1:5, 2:10, 3:15, 4:20} if len(n) in rates: # 구매한 상품의 개수가 rates 안에 key값에 있다면 rate = rates[len(n)] # 총 가격을 설정 totalPrice += sum(n) * (1 - rate * 0.01) return [rate, int(totalPrice)]
Python
복사
# 로또 모듈을 만들고 로또 결과가 출력될 수 있도록 프로그램을 만들자 lottoNum = [] for i in range(1,7): # 6번 반복해서 번호를 입력 inputNum = int(input('번호(1~45) 입력: ')) lottoNum.append(inputNum) # 여기서부터 함수 #---------------------------------------------------- # 로또 번호 모듈 당첨인지 확인하기 import random target = random.sample((1,46), 6) collectNum = [] # 일치하는 숫자를 담을 리스트 def jackpotOrNot(lotto): # 들어오는 값은 리스트
Python
복사