함수란?
함수의 선언
def addCal(): # 함수 선언
n1 = int(input('n1 입력: '))
n2 = int(input('n2 입력: '))
print(f'n1 + n2 = {n1 + n2}')
addCal() # 함수 호출
함수에서 또 다른 함수 호출하기
def fun1():
print('fun1 호출!')
fun2()
def fun2():
print('fun2 호출!')
fun3()
def fun3():
print('fun3 호출!')
fun1()
인수와 매개변수
- 함수 호출 시 함수에 데이터를 전달할 수 있다.
- 인수와 매개변수 개수는 일치해야 한다.
def greet(customer): # 매개변수
print('{}님, 안녕하세요'.format(customer))
greet('홍길동') # 인수
def printNum(*numbers):
# print(type(numbers)) -> 튜플 타입
for number in numbers:
print(number, end=' ')
print()
printNum()
printNum(10)
printNum(10, 20)
printNum(10, 20, 30)
def divideNumber(n):
if n % 2 == 0:
return '짝수'
else:
return '홀수'
returnValue = divideNumber(4)
print(f'returnValue : {returnValue}')
변수의 종류
num_out = 10
def printNum1():
print(f'num_out1 : {num_out}')
printNum1()
print(f'num_out1 : {num_out}')
def printNum2():
num_out = 20
print(f'num_out2 : {num_out}')
printNum2()
print(f'num_out2 : {num_out}')
def printNum3():
global num_out
num_out = 30
print(f'num_out3 : {num_out}')
printNum3()
print(f'num_out3 : {num_out}')
중첩함수란?
lambda 키워드
def calculator(n1, n2):
return n1 + n2
returnValue = calculator(10, 20)
print(returnValue)
calculator2 = lambda n1, n2: n1 + n2
returnValue2 = calculator2(10, 20)
print(returnValue2)
모듈이란?
모듈 종류
import random
for i in range(10):
rNum = random.randint(1, 10)
print(f'rNum: {rNum}')
print()
rNums = random.sample(range(1, 101), 10)
print(f'rNums: {rNums}') # 리스트로 반환
실행 파일
패키지란?
객체지향 프로그래밍
클래스 만들기
class Car:
def __init__(self, color, length):
self.color = color
self.length = length
def doStop(self):
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()
객체 속성 변경
class NewGenerationPC:
def __init__(self, name, cpu, memory, ssd):
self.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', '16G', '256G')
myPC.printPCInfo()
friendPC = NewGenerationPC('friendPC', 'i7', '32G', '512G')
friendPC.printPCInfo()
myPC.cpu = 'i9'
myPC.memory = '64G'
myPC.ssd = '1T'
myPC.printPCInfo()