[데이터분석]파이썬 스터디노트5

bin·2023년 2월 7일
0

파이썬

목록 보기
5/12
post-thumbnail

모듈 호출 : 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)

  • 객체의 장점: 코드 재사용, 모듈화에 좋다 (like 부품 결합도 낮음)

1. 클래스만들기: class키워드 / 속성(변수) / 기능(함수)

2. 객체 생성: 객체는 클래스의 생성자를 호출

  • 객체 생성에 필요한 매개변수 정확하게 짝지어서 입력
  • 입력된 값은 객체의 속성 초기화
  • 객체가 생성된 다음 이를 변수에 담음(car1, car2 ->레퍼런스변수)
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()
  • 같은 class에 속하지만 myPC와 yourPC는 다른 객체
myPC.cpu = 'i9'
myPC.memory = '64GB'
  • 도트 접근 연산자를 통해 속성 변경

0개의 댓글