기본적으로 알아두면 좋은 모듈
수학, 난수, 시간 모듈은 코딩할 때 유용하게 사용된다.
수학 관련 내장함수
sum( ) : 합
listVar = [2,5,6,2,3,30]
print(f'(합계) sum(listVar): {sum(listVar)}')
max( ) : 최대값
listVar = [2,5,6,2,3,30]
print(f'(최대값) max(listVar): {max(listVar)}')
min( ) : 최소값
listVar = [2,5,6,2,3,30]
print(f'(최소값) min(listVar): {min(listVar)}')
pow( ) : 거듭제곱
print(f'(거듭제곱) pow(2, 2): {pow(2, 2)}') #2제곱
print(f'(거듭제곱) pow(2, 3): {pow(2, 3)}') #3제곱
print(f'(거듭제곱) pow(2, 4): {pow(2, 4)}') #4제곱
round( ) : 반올림
print(f'(반올림) round(3.141592, 1): {round(3.141592, 1)}') #소수점 1번째 자리까지 표현
print(f'(반올림) round(3.141592, 2): {round(3.141592, 2)}') #소수점 2번째 자리까지 표현
print(f'(반올림) round(3.141592, 3): {round(3.141592, 3)}') #소수점 3번째 자리까지 표현
math 모듈
math.fabs( ) : 절대값
import math
print(f'(절대값) math.fabs(-10): {math.fabs(-10)}')
print(f'(절대값) math.fabs(-0.125845): {math.fabs(-0.125845)}')
math.ceil( ) : 올림
import math
print(f'(올림) math.ceil(10.2): {math.ceil(10.2)}')
print(f'(올림) math.ceil(-2.42): {math.ceil(-2.42)}')
math.floor( ) : 내림
import math
print(f'(내림) math.floor(10.6): {math.floor(10.6)}')
print(f'(내림) math.floor(-2.52): {math.floor(-2.52)}')
math.trunc( ) : 버림
import math
print(f'(버림) math.trunc(5.9): {math.trunc(5.9)}')
print(f'(버림) math.trunc(-3.56): {math.trunc(-3.56)}')
math.gcd( ) : 최대공약수
import math
print(f'(최대공약수) math.gcd(14, 21): {math.gcd(14, 21)}')
math.factorial( ) : 팩토리얼
import math
print(f'(팩토리얼) math.factorial(10): {math.factorial(10)}')
math.sqrt( ) : 제곱근
import math
print(f'(제곱근) math.sqrt(12): {math.sqrt(12)}')
print(f'(제곱근) math.sqrt(8): {math.sqrt(8)}')
random 모듈
random.randint( ) : 정수 중에서 난수 1개를 발생시킴
- 【 random.randint( 범위 시작 정수, 범위 끝 정수 ) 】
import random
print(f'(정수 난수 1개) random.randint(10, 100): {random.randint(10, 100)}')
#10~100사이의 정수 난수
random.sample( ) : 지정된 범위에서 지정된 개수의 난수를 발생시킴
결과값을 리스트로 반환
- 【 random.sample( 범위 지정, 발생시킬 난수 개수 or k) 】
- 범위 지정 : 리스트, 집합, range() 등 random의 범위가 될 sequence 입력
- k : 반환될 리스트의 크기 입력
#0~99 중 10개의 숫자를 랜덤으로 출력
import random
print(f'(랜덤 출력) random.sample(range(100), 10): {random.sample(range(100), 10)}')
#5개의 값들중에서 2개를 랜덤으로 출력
import random
mylist = ['apple', 'banana', 'orange', 'berry', 'cherry']
print(f'(랜덤 출력) random.sample(mylist, k=2): {random.sample(mylist, k=2)}')
time 모듈
time.localtime( ) : 현재 시스템의 시간을 반환
import time
lt = time.localtime()
print(f'(현재 시스템 시간) time.localtime(): {lt}')
print(f'(현재 시스템 시간 - 년도) lt.tm_year: {lt.tm_year}')
print(f'(현재 시스템 시간 - 월) lt.tm_mon: {lt.tm_mon}')
print(f'(현재 시스템 시간 - 일) lt.tm_mday: {lt.tm_mday}')
print(f'(현재 시스템 시간 - 분) lt.tm_min: {lt.tm_min}')
print(f'(현재 시스템 시간 - 초) lt.tm_sec: {lt.tm_sec}')
print(f'(현재 시스템 시간 - 요일) lt.tm_wday: {lt.tm_wday}') #숫자로 출력, 0부터 시작