Week2-1. function(함수)
#예제:속도와 이동 거리를 입력하면 소요 시간을 출력하는 코드 (시간 = 거리/속도)
def returnTime(v,l): #v,l은 parameter(매개변수)로 함수 호출 시 입력된 값을 전달받는다.
t = round(l/v,2)
h = int(t)
m = (t -int(t)) * 60
print('If you go {}km at {}km/h, it takes {}hours {}minute'.format(v,l,h,round(m,2)))
v = float(input('Velocity(km/h) : '))
l = float(input('Length(km) : '))
returnTime(v,l) #v,l은 arguments(인수)로 정해진 값이다. 함수를 호출 할 때 입력한 값으로 해당함수의 매개변수에 할당된다.
#예제: 재귀함수를 이용해서 팩토리얼 함수 코드 작성(재귀함수:함수를 정의하는 단계에서 자기 자신을 재참조 하는 함수)
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n-1) #재귀함수
n = int(input('Number : '))
print('{}! : {}'.format(n,formated(factorial(n))))
global_variable(전역변수):함수 밖에서 선언된 변수로 어디에서나 사용은 가능하지만 함수 안에서 수정할 수는 없다.
local_variable(지역변수):함수 안에서 선언된 변수로 함수 안에서만 사용이 가능하다.
#예제:수입과 공과금을 입력하면 공과금 총액과 수입대비 공과급 비율을 계산하는 모듈 선언
income = 0 #전역변수(global variable)로 함수 내에서 수정이 불가능하다.
water = 0
electric = 0
gas = 0
def setIncome(ic):
global income #global keyword를 선언하여 전역변수인 'income'을 함수 내에서 수정할 수 있게 한다.
income = ic
def getIncome():
return income
def setWater(w):
global water
water = w
def getWater():
return water
def setElectric(e):
global electric
electric = e
def getElectric():
return electric
def setGas(g):
global gas
gas = g
def getGas():
return gas
def getUtilityTotal():
return water + electric + gas
def getPortionOfUtility():
return getUtilityTotal() / getIncome() * 100
print('-'*20)
income = int(input('Income : '))
setIncome(income)
water = int(input('Water bill : '))
setWater(water)
electric = int(input('Electronic bill : '))
setElectric(electric)
gas = int(input('Gas bill : '))
setGas(gas)
print('Utility total : {}'.format(getUtilityTotal()))
print('Portion of utility in income : {}'.format(round(getPortionOfUtility(),2)))