모듈 호출 : import 모듈명
import random
rNums = random.sample(range(101), 10)
print(f'rNums = {rNums}')
rNums = [0, 93, 50, 37, 82, 41, 15, 84, 68, 7]
<모듈파일>
def reverseStr(str):
reversedString = ''
for c in str:
reversedString = c + reversedString
return reversedString
<실행파일>
import reverseStr
userInputStr = input('문자열 입력: ')
reversedString = reverseStr.reverseStr(userInputStr)
print(f'reversedString: {reversedString}')
as: 모듈 이름 단축
import calculator as cal
form~as: 모듈의 특정 기능만 사용
from calculaotor import add from calculator import sub add(10,20) sub(10,20) from calculator import add, mul ->콤마로 연결
<모듈>
scores = []
def addScore(s):
scores.append(s)
def getScores():
return scores
def getTotalScore():
total = 0
for s in scores:
total += s
return total
def getAvgScore():
avg = getTotalScore() / len(scores)
return avg
<실행>
import scores as sc
korScore = int(input('국어 점수 입력: '))
matScore = int(input('수학 점수 입력: '))
engScore = int(input('영어 점수 입력: '))
sc.addScore(korScore)
sc.addScore(engScore)
sc.addScore(matScore)
print(sc.getScores())
print(sc.getTotalScore())
print(sc.getAvgScore())
💥return을 자꾸 빼먹는다 ㅠㅠ 복습하자 !!!!
**전역번수
__name__
을 이용한 실행
__name__
: 모듈 이름이 저장되거나(모듈파일),__main__
이 저장된다(실행파일)
def mul(n1, n2):
return int(n1*n2)
if __name__ == '__main__':
print(mul(3.14, 1.2))
->실행파일일 때만 실행
패키지: 관련 있는 모듈 그룹으로 관리 가능
site-ackages
import sys
for path in sys.path:
print(path)
project\venv\lib\site-packages
-> 같은 디렉토리 내에 있는 모듈만 실행 가능하나, site-packages에 있는 모듈은 어디서나 사용할 수 있다
자주 사용하는 모듈
import math
#절대값
print(f'math.fabs(-10): {math.fabs(-10)}')
#올림
print(f'math.ceil(-10): {math.ceil(5.1431)}')
#내림
print(f'math.ceil(-5.21): {math.floor(-24243)}')
#버림
print(f'math.trunc(5.21):{math.trunc(5.21)}')
#최대공약수
print(f'math.gcd(14,21): {math.gcd(14,21)}')
#팩토리얼
print(f'math.factorial(10): {math.factorial(10)}')
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_hour: {lt.tm_hour}')
print(f'lt.tm_min: {lt.tm_min}')
print(f'lt.tm_sec: {lt.tm_sec}')
print(f'lt.tm_wday: {lt.tm_wday}') #요일
객체지향 프로그래밍: 객체를 이용한 프로그램,
객체=속성(attribute) + 기능(function)
1. 클래스만들기: class키워드 / 속성(변수) / 기능(함수)
2. 객체 생성: 객체는 클래스의 생성자를 호출
class Car:
def __init__(self, col, len): #__init__: 객체 초기화하는데 사용
self.color = col
self.length = len
def doStop(self): #self: Car라는 class 안에 포함된 기능
print('STOP!!')
def doStart(self):
print('START!!')
def printCarInfo(self):
print(f'self.color: {self.color}')
print(f'self.length: {self.length}')
car1 = Car('red', 200)
car2 = Car('blue', 300)
car1.printCarInfo()
car2.printCarInfo()
self.color: red
self.length: 200
self.color: blue
self.length: 300
객체 속성 변경
class NewGenerationPC:
def __init__(self, name, cpu, memory, ssd):
self.name = name #앞 name: class로부터 생성된 객체에 속해있는 속성 / 뒤 name: 매개변수에서 받은 name
self.cpu = cpu
self.memory = memory
self.ssd = ssd
def doExcel(self):
print('EXCEL RUN!!')
def doPhotoshop(self):
print('PHOTOSHOP RUN!!')
def printPCInfo(self):
print(f'self.name: {self.name}')
print(f'self.cpu: {self.cpu}')
print(f'self.memory: {self.memory}')
print(f'self.ssd: {self.ssd}')
myPC = NewGenerationPC('myPc','i5','16GB','256GB')
yourPC = NewGenerationPC('yourPc','i7','32GB','512GB')
myPC.printPCInfo()
yourPC.printPCInfo()
myPC.cpu = 'i9'
myPC.memory = '64GB'