num = 1 def printNum(): print('num:{}'.format(num)) printNum() print(num) #실행결과 num:1 1
num = 1 def printNum(): num = 2 print('num:{}'.format(num)) printNum() print(num) #실행결과 num:2 1
num = 1 def printNum(): global num num = 2 print('num:{}'.format(num)) printNum() print(num) #실행결과 num:2 2
def out_function(): print('나는 out함수!') def in_function(): print('나는 in함수!') in_function() out_function() #실행결과 나는 out함수! 나는 in함수!
예제
calculator()함수를 선언하고 calculator()안에 덧셈, 뺄셈, 곱셈, 나눗셈 함수를 선언하자.
함수안에 중첩함수, 조건문, 반복문이 모두 들어가있어 매우 좋은 문제라고 생각한다.(풀고나서도 소스코드를 보며 풀이과정을 몇번이고 봤던 문제)
def calculator(n1,n2,operator): def plus(): print(n1+n2) def minus(): print(n1-n2) def multiple(): print(n1*n2) def devision(): print(n1/n2) if operator == 1: plus() elif operator == 2: minus() elif operator ==3: multiple() elif operator == 4: devision() while True: num1 = float(input('실수(n1)입력:')) num2 = float(input('실수(n2)입력:')) operatorNum = int(input('1.덧셈, 2.뺄셈, 3.곱셈, 4.나눗셈, 5.종료')) if operatorNum == 5: print('종료') break calculator(num1,num2,operatorNum)
함수 선언을 보다 간단히 해주는 함수
형식은 간단.
함수명 = lambda 파라미터:함수내용
rectangularWidth =lambda n1,n2:n1*n2/2 width = int(input('밑변 입력:')) height = int(input('높이 입력:')) result = rectangularWidth(width, height) print(result)
import random a = random.sample(range(1,101),5) print(a) #실행결과 [24, 94, 55, 54, 58] #random모듈의 sample 함수를 사용하여 1부터 100까지 랜덤으로 5개 숫자를 뽑아내었다.
예제
국어, 영어, 수학 점수를 입력하면 총점, 평균을 출력하는 모듈을 만들어라.
모듈에서는 국어점수,영어점수,수학점수를 하나의 리스트 안에 출력을 하고자 'calculator =[]' 리스트를 생성하면서 시작하였다.
아직도 헷갈리는 부분은 인수와 매개변수이다. 아래의 경우 append() 함수에 a 인수를 넣었는데 그것이 calSum 함수의 매개변수로 할당되는것이다. 즉 calSum()함수 안에는 각각 국어점수,영어점수,수학점수가 a 라는 변수에 할당되어 추가되어(append)지는 것이다.(어째 써놓은게 더 이해안되게 쓴듯;)
#모듈 파일 화면 calculator = [] def calSum(a): calculator.append(a) def getScores(): return calculator def getTotalScore(): total = 0 for t in calculator: total += t return total def getAvgScore(): avg = getTotalScore() / len(calculator) return avg
#실행 파일 화면 import calculator as cal korScore = int(input('국어 점수 입력:')) endScore = int(input('영어 점수 입력:')) matScore = int(input('수학 점수 입력:')) cal.calSum(korScore) cal.calSum(endScore) cal.calSum(matScore) print(cal.getScores()) print(cal.getTotalScore()) print(cal.getAvgScore()) #실행결과 국어 점수 입력:80 영어 점수 입력:100 수학 점수 입력:90 [80, 100, 90] 270 90.0
어떤 프로젝트로 파이썬 파일을 여러개 만들다보면 어느 한 파일의 모듈을 가져와 사용할 때가 종종있는데 이런 경우 어느 한 파일의 특정한 모듈만 가져와야하는데 다른 실행코드까지 실행되는 것을 막기위해 사용한다.
참조할 모듈이 있는 파일의 실행부 이전에 다음과 같은 식을 써주면 다른 파일에서 이 파일의 어느 모듈을 가져다 쓰고 싶을때 원하는 식만 가져올 수 있다.
if __name__ == '__main__':
list = [1,2,3,4,5] print('sum:{}'.format(sum(list))) #sum : 합계 함수 print('max:{}'.format(max(list))) #max : 최댓값 print('min:{}'.format(min(list))) #min : 최소값 print('{}의 거듭제곱:{}'.format(4,pow(4,2))) #pow : 거듭제곱 print('{}의 반올림 결과:{}'.format(3.14,round(3.14,1))) #round : 반올림 import math print('{}의 절댓값은:{}'.format(-3.14,math.fabs(-3.14))) #math.fabs : 절댓값 print('{} 올림:{}'.format(3.14,math.ceil(3.14))) #math.ceil : 올림 print('{} 내림:{}'.format(3.14,math.floor(3.14))) #math.floor : 내림 print('{} 버림:{}'.format(3.14,math.trunc(3.14))) #math.trunc : 버림 print('{} 제곱근:{}'.format(16,math.sqrt(17))) #math.sqrt : 제곱근
import time lt = time.localtime() print(lt) print(lt.tm_year)
객체(object) = 속성(attribute)+기능(function)
객체는 Class 에서 생성할 수 있다.
장점은 코드를 재사용하거나 모듈화에 좋아서 확장성이 좋다고 할 수 있다.
객체지향 형식(아래)

예제
비행기 클래스를 만드록 비행기 객체를 5개 생성해보자.
class Airplane: def __init__(self,br,col,sp): self.brand = br self.color = col self.speed = sp def engineStart(self): print('엔진점화') def degreeHigh(self): print('고도상향') def degreelow(self): print('고도하향') airplane1 = Airplane('Korea','blue',950) airplane2 = Airplane('Japan','pink',800) airplane3 = Airplane('China','red',900) airplane4 = Airplane('Unite State','green',950) airplane5 = Airplane('Russia','black',900) airplane1.degreeHigh() #객체의 기능을 불러옴 airplane1.degreelow() print(airplane1.brand) #객체의 속성을 불러옴 print(airplane1.color) print(airplane1.speed) #실행결과 고도상향 고도하향 Korea blue 950
airplane1.color = 'orange' #실행결과 orange
일주일만에 파이썬을 print('hello python') 부터 객체지향프로그래밍까지 오니 머리가 너무 지끈거린다🤢
신기한건 어렵고 재미없다고 느끼려해도 하루에 해야할 목표분량이 많으니 그런 생각도 안들정도라는 것 이다.
하루 일과 패턴이 제로베이스취업스쿨을 시작하고 나서 완전히 달라져서 아직은 힘들지만 습관처럼 하다보면 내가 만들고 싶었던 것들을 언젠가 만들 수 있지 않을까
