제로베이스_데이터스쿨_230407학습내용리뷰_파이썬중급문제풀이

김지태·2023년 4월 10일
0
post-thumbnail

05_041 함수 - 함수를 이용한 프로그래밍

이동 거리 반환하는 함수 만들기

def getDistance(speed, hour, minute):
distance = speed * (hour + minute/60 )
return distance

print('-' * 66)
s = float(input('속도(km/h) 입력: '))
h = float(input('시간(h) 입력: '))
m = float(input('시간(m) 입력: '))
d = getDistance(s, h, m)

print(f'{s} km/h 속도로 {int(h)}시간 {int(m)}분 동안 이동한 거리는 {round(d, 1)}km 이다.')
print('-' * 66)


90.0 km/h 속도로 2시간 30분 동안 이동한 거리는 225.0km 이다.

이동 시간 반환하는 함수 만들기 - try

def getTime(speed, distance):
hour = distance // speed
minute = (distance % speed) * (60 / speed)
return hour, minute

print('-' 66)
d = float(input('거리(km) 입력: '))
s = float(input('속도(km/h) 입력: '))
t = getTime(s, d)
print(f'{s}(km/h) 속도로 {d}(km) 이동한 시간은 {}')
print('-'
66)

실패
Cell In[5], line 13
print(f'{s}(km/h) 속도로 {d}(km) 이동한 시간은 {}')
^
SyntaxError: f-string: empty expression not allowed

이동 시간 반환하는 함수 만들기 - 해답

def getTime(speed, distance):
time = distance / speed
hour = int(time)
minute = int((time - hour) * (60/speed))
return [hour, minute] ##### 반환 값 두 개일 때는 리스트 활용

print('-' 66)
d = float(input('거리(km) 입력: '))
s = float(input('속도(km/h) 입력: '))
t = getTime(s, d)
print(f'{s}(km/h) 속도로 {d}(km) 이동한 시간은 {t[0]}시간 {t[1]}분이다.') ##### 반환값 첫번째 = t[0] / 두번째 t[1]
print('-'
66)

1번째 항의 값: 2
1 번째 항까지의 합: 2
2번째 항의 값: 5
2번째 항까지의 합: 7
3번째 항의 값: 8
3번째 항까지의 합: 15
4번째 항의 값: 11
4번째 항까지의 합: 26
5번째 항의 값: 14
5번째 항까지의 합: 40
6번째 항의 값: 17
6번째 항까지의 합: 57
7번째 항의 값: 20
7번째 항까지의 합: 77


90.0(km/h) 속도로 225.0(km) 이동한 시간은 2시간 0분이다.

05_042 함수 3

비행기 티켓 출력 기계 유아, 소아, 성인

childPrice = 18000
infantPrice = 25000
adultPrice = 50000
specialDC = 50

def printAirPlaneReceipt(c1, c2, i1, i2, a1, a2):
cp = c1 childPrice
cp_dc = int(c2
childPrice * 0.5)
print(f'유아 {c1}명 요금: {cp}원')
print(f'유아 {c2}명 요금: {cp_dc}원')

ip = i1 infantPrice
ip_dc = int(i2
infantPrice * 0.5)
print(f'소아 {i1}명 요금: {ip}원')
print(f'소아 {i2}명 요금: {ip_dc}원')

ap = a1 adultPrice
ap_dc = int(a2
adultPrice * 0.5)
print(f'성인 {a1}명 요금: {ap}원')
print(f'성인 {a2}명 요금: {ap_dc}원')

print(f'Total: {c1 + c2 + i1 + i2 + a1 + a2}원')
print(f'TotalPrice: {cp + cp_dc + ip + ip_dc + ap + ap_dc}원')

childCnt = int(input('유아 명수 입력: '))
specialDCchildCnt = int(input('할인 대상 유아 명수 입력: '))

infantCnt = int(input('소아 명수 입력: '))
specialDCinfantCnt = int(input('할인 대상 소아 명수 입력: '))

adultCnt = int(input('성인 명수 입력: '))
specialDCadultCnt = int(input('할인 대상 성인 명수 입력: '))

printAirPlaneReceipt(childCnt, specialDCadultCnt, infantCnt, specialDCinfantCnt, adultCnt, specialDCadultCnt)

1번째 항의 값: 2
1 번째 항까지의 합: 2
2번째 항의 값: 5
2번째 항까지의 합: 7
3번째 항의 값: 8
3번째 항까지의 합: 15
4번째 항의 값: 11
4번째 항까지의 합: 26
5번째 항의 값: 14
5번째 항까지의 합: 40
6번째 항의 값: 17
6번째 항까지의 합: 57
7번째 항의 값: 20
7번째 항까지의 합: 77

유아 14명 요금: 252000원
유아 11명 요금: 99000원
소아 23명 요금: 575000원
소아 4명 요금: 50000원
성인 8명 요금: 400000원
성인 11명 요금: 275000원
Total: 71원
TotalPrice: 1651000원

보완 - 가격 세 자리 마다 , 붙이는 법

childPrice = 18000
infantPrice = 25000
adultPrice = 50000
specialDC = 50

함수를 따로 만들자

def formatedNumber(n):
return format(n, ',')

def printAirPlaneReceipt(c1, c2, i1, i2, a1, a2):
cp = c1 childPrice
cp_dc = int(c2
childPrice * 0.5)
print(f'유아 {c1}명 요금: {formatedNumber(cp)}원')
print(f'유아 {c2}명 요금: {formatedNumber(cp_dc)}원')

ip = i1 infantPrice
ip_dc = int(i2
infantPrice * 0.5)
print(f'소아 {i1}명 요금: {formatedNumber(ip)}원')
print(f'소아 {i2}명 요금: {formatedNumber(ip_dc)}원')

ap = a1 adultPrice
ap_dc = int(a2
adultPrice * 0.5)
print(f'성인 {a1}명 요금: {formatedNumber(ap)}원')
print(f'성인 {a2}명 요금: {formatedNumber(ap_dc)}원')

print(f'Total: {formatedNumber(c1 + c2 + i1 + i2 + a1 + a2)}원')
print(f'TotalPrice: {formatedNumber(cp + cp_dc + ip + ip_dc + ap + ap_dc)}원')

childCnt = int(input('유아 명수 입력: '))
specialDCchildCnt = int(input('할인 대상 유아 명수 입력: '))

infantCnt = int(input('소아 명수 입력: '))
specialDCinfantCnt = int(input('할인 대상 소아 명수 입력: '))

adultCnt = int(input('성인 명수 입력: '))
specialDCadultCnt = int(input('할인 대상 성인 명수 입력: '))

printAirPlaneReceipt(childCnt, specialDCadultCnt, infantCnt, specialDCinfantCnt, adultCnt, specialDCadultCnt)

비행기 티켓 영수증 출력 self try

childPrice = 18000
infantPrice = 25000
adultPrice = 50000

def formatedNumber(n):
return format(n, ',')

def printAirplaneTicekt(c1, c2, i1, i2, a1, a2):

print('-' 66)
cp = c1
childPrice
cp_dc = int(c2 childPrice 0.5)
print(f'유아 {c1}명 요금: {formatedNumber(cp)}원')
print(f'유아 할인 대상 {c2}명 요금: {formatedNumber(cp_dc)}원')

ip = i1 infantPrice
ip_dc = int(i2
infantPrice * 0.5)
print(f'소아 {i1}명 요금: {formatedNumber(ip)}원')
print(f'소아 할인 대상 {i2}명 요금: {formatedNumber(ip_dc)}원')

ap = a1 adultPrice
ap_dc = int(a2
adultPrice 0.5)
print(f'성인 {a1}명 요금: {formatedNumber(ap)}원')
print(f'성인 할인 대상{a2}명 요금: {formatedNumber(ap_dc)}원')
print('-'
66)
print(f'Total 명수 : {c1 + c2 + i1 + i2 + a1 + a2}')
print(f'Total 금액 : {formatedNumber(cp + cp_dc + ip + ip_dc + ap + ap_dc)}')

print('-' * 66)

childCnt = int(input('일반 유아 명수는? : '))
childDCCnt = int(input('할인 유아 명수는? : '))

infantCnt = int(input('일반 소아 명수는? '))
infantDCCnt = int(input('할인 소아 명수는? '))

adultCnt = int(input('일반 성인 명수는? '))
adultDCCnt = int(input('할인 성인 명수는? '))

printAirplaneTicekt(childCnt, childDCCnt, infantCnt, infantDCCnt, adultCnt, adultDCCnt)


유아 11명 요금: 198,000원
유아 할인 대상 1명 요금: 9,000원
소아 11명 요금: 275,000원
소아 할인 대상 1명 요금: 12,500원
성인 11명 요금: 550,000원

성인 할인 대상1명 요금: 25,000원

Total 명수 : 36

Total 금액 : 1,069,500

비행기 티켓 구하기 self try 2 / 이번에는 함수 자체에 print 기능 실지 말고 리턴 값 받아서 출력헤보기

childPrice = 18000
infantPrice = 25000
adultPrice = 50000
discountRate = 0.5

def formatedNum(n):
return format(n, ',')

def printAirplaneticket(c1, c2, i1, i2, a1, a2): #### 함수에 어떤 기능을 추가해야 한다 /
cp = childPrice
cp_dc = childPrice discountRate
ip = infantPrice
ip_dc = infantPrice
discountRate
ap = adultPrice
ap_dc = adultPrice discountRate
return ['='
66, f'할인 미적용 유아 {c1}명 요금: {formatedNum(int(cp))}원', f'할인 적용 유아 {c2}명 요금: {formatedNum(int(cp_dc))}원', f'할인 미적용 소아 {i1}명 요금: {formatedNum(int(ip))}원', f'할인 적용 소아 {i2}명 요금: {formatedNum(int(ip_dc))}원', f'할인 미적용 성인 {a1}명 요금: {formatedNum(int(ap))}원', f'할인 적용 성인 {a2}명 요금: {formatedNum(int(ap_dc))}원', '='*66]

childCnt = int(input('할인 미적용 유아는 몇 명인가요?: '))
childDCCnt = int(input('할인 적용 유아는 몇 명인가요?: '))
infantCnt = int(input('할인 미적용 소아는 몇 명인가요?: '))
infantDCCnt = int(input('할인 적용 소아는 몇 명인가요?: '))
adultCnt = int(input('할인 미적용 성인은 몇 명인가요?: '))
adultDCCnt = int(input('할인 적용 성인은 몇 명인가요?: '))

receipt = printAirplaneticket(childCnt, childDCCnt, infantCnt, infantDCCnt, adultCnt, adultDCCnt)

print(f'비행기 티켓 영수증입니다.\n{receipt[0]}\n{receipt[1]}\n{receipt[2]}\n{receipt[3]}\n{receipt[4]}\n{receipt[5]}\n{receipt[6]}\n{receipt[7]}')

리턴 값이 여러 개일 경우 리스트로 받는다.

궁금한 점: 리스트 값 하나씩 말고 한꺼번에 받는 방법은 뭐가 있을까?

05_043

재귀 함수 - 팩토리얼 함수 만들기

def recursionFun(n):
if n == 1:
return n

return n * recursionFun(n-1) ##### else 없어도 'n 이 1이 아닌 경우'를 의미한다.

inputNumber = int(input('input number: '))
print(format(recursionFun(inputNumber), ','))

479,011,600

재귀 함수 만들기 셀프 연습1

def 재귀함수(n):
if n == 1:
return n

return n * 재귀함수(n-1)

inputNum = int(input('number: '))

print(format(재귀함수(inputNum), ','))

3,628,800

재귀함수 만들기 셀프 연습2

def formatedNum(n):
return format(n, ',')

def 재귀함수(n):
if n == 1:
return n

return n * 재귀함수(n-1) #### 재귀함수(n-1) 에서 또 함수 재귀함수() 가 발동된다. 그래서 결국 n 이 1이 될 때까지 반복되어 팩토리얼을 구할 수 있게 됨.

새로 얻어갈 포인트: [함수 내부에서 또 같은 함수를 발동 시킬 수 있다.]

입력값 = int(input('숫자를 입력하세요 : '))

print(formatedNum(재귀함수(입력값)))

3,628,800

셀프 연습

def 재귀함수(n):
if n == 1:
return n

return n * 재귀함수(n-1) #### n이 1인 경우와 1이 아닐 경우만 생각

셀프 연습

def formatedNum(n):
return format(n, ',')

def 재귀함수(n):

if n ==1 :
return 1

return n * 재귀함수(n-1)

inputNum = int(input('숫자를 입력하세요: '))

print(formatedNum(재귀함수(inputNum)))

단리 / 월 복리 계산기 함수를 만들어보자.

def formatedNumber(n):
return format(n, ',')

단리

def singleRateCalculator(m, t, r): ##### 원금, 기간, 이율

totalMoney = 0 # 돈 합계 ( 원금 + 이자 ) # Q. 그런데 왜 0 이지? 나중에 m 이랑 이자 총합이랑 더해줄 거임!
totalRateMoney = 0 # 이자 합계

for i in range(t):
totalRateMoney += m (r 0.01) ##### totalRateMoney = totalRateMoney + m (r 0.01) ##### 단리 이자니까 개월수 곱하기 이자. 그리고 totalRateMoney = 0 에다가 더해줌.

totalMoney = m + totalRateMoney
return int(totalMoney)

월 복리

def multiRateCalculator(m, t, r): ###### 원금, 거치 기간, 이율

거치 기간 연 단위에서 월 단위로 환산

t = t 12
rpm = (r / 12)
0.01 ##### 연 이자율을 12로 나누는 것이 맞나? (헷갈림) / 0.01 은 % 니까 해주는 거고.

totalMoney = m

for i in range(t):
totalMoney += (totalMoney * rpm) ##### 언제 FOR 문을 사용해야할지, WHILE 문을 사용해야할지 판단을 내리기가 참 어렵다.

##### 복리는 돈 전체에다가 이자율을 곱해야 하니까 totalMoney를 애초에 이자와 분리해서 0으로 두고 계산하기가 불가능. 

return int(totalMoney)

money = int(input('예치금(원): '))
term = int(input('기간(년)'))
rate = int(input('연 이율(%)'))

print('[단리 계산기]')
print(f'{term}년 후 총 수령액 : {formatedNumber(singleRateCalculator(money, term, rate))}')

print('[월 복리 계산기]')
print(f'{term}년 후 총 수령액: {formatedNumber(multiRateCalculator(money, term, rate))}')

[단리 계산기]
5년 후 총 수령액 : 57,500,000
[월 복리 계산기]
5년 후 총 수령액: 58,080,839

셀프 연습 - 이해가 완전히 안될 때는 그냥 연습하자 !!!

단리 함수

def formatedNum(n):
return format(n, ',')

def singleRateCalculator(m, t, r): # t, 시간은 월 단위가 아닌 연 단위이다..
totalMoney = m
totalRateMoney = 0

for i in range(t):
totalRateMoney += ( r 0.01 ) m

totalMoney = totalMoney + totalRateMoney
earnMoney = totalMoney - m #### 원금과 비교하여 결과적으로 얼만큼 더 벌리는지도 구해보자 !!

return [int(totalMoney), int(earnMoney)] # 리턴 값이 두 개니까 리스트

howLong = int(input('몇 년 동안 돈을 맡기실 건가요?: '))
howMuchMoney = int(input('얼마만큼의 돈을 맡기실 건가요?: '))
howMuchRate = int(input('얼마만큼의 이자율?: '))

단리이자율계산 = singleRateCalculator(howMuchMoney, howLong, howMuchRate)

print('='66, f'원금:{formatedNum(howMuchMoney)}, 기간:{howLong}, 이자율:{howMuchRate}', f'총 금액: {formatedNum(단리이자율계산[0])}, 늘어난 금액: {formatedNum(단리이자율계산[1])}', '='66, sep='\n')

==================================================================
원금:100,000,000, 기간:10, 이자율:3

총 금액: 130,000,000, 늘어난 금액: 30,000,000

복리 계산기

def formatedNum(n):
return format(n, ',')

def multiRateCalculator(m, t, r):
totalMoney = m
t = t * 12

rpm = r / 12

for i in range(t): # totalMoney = totalMoney (rpm 0.01) / = > 틀림
totalMoney += totalMoney (rpm 0.01)

earingMoney = totalMoney - m

return [int(totalMoney), int(earingMoney)]

howLong = int(input('몇 년 동안 돈을 맡기실 건가요?: '))
howMuchMoney = int(input('얼마만큼의 돈을 맡기실 건가요?: '))
howMuchRate = int(input('얼마만큼의 이자율?: '))

복리계산기 = multiRateCalculator(howMuchMoney, howLong, howMuchRate)

print('='66, f'원금:{formatedNum(howMuchMoney)}, 기간:{howLong}, 이자율:{howMuchRate}', f'총 금액: {formatedNum(복리계산기[0])}, 늘어난 금액: {formatedNum(복리계산기[1])}', '='66, sep='\n')

==================================================================
원금:100,000,000, 기간:10, 이자율:3

총 금액: 134,935,354, 늘어난 금액: 34,935,354

05_44 함수 5

함수를 이용해서 등차 수열 값, 합 구하기

초항 입력
공차 입력
몇 번째 수열 구하고 싶은지(n 항)
-- 출력 --
n 번째 항의 값
n 번째 항까지의 합

def sequenceCal(n1, d, n): #####초항이 n1, 공차가 d, n = 몇 항까지

valueN = 0; sumN = 0; ##### n 항의 값과 n 항까지의 합의 값

i = 1 ##### i 가 1인 경우
while i <= n :

if i == 1:
  valueN = n1
  sumN += valueN  ##### sumN = valueN 이나 똑같음 / 첫 항이니까.
  print(f'{i}번째 항의 값: {valueN}')
  print(f'{i} 번째 항까지의 합: {sumN}')
  
  i += 1 ##### i 가 하나씩 올라가야 함.
  continue ##### 바로 진행 / 이걸로 아래쪽이 진행되지 못하게 함

valueN += d     ##### 공차 만큼 계속 더해서 나가면 되니까 d를 계속 더해준다. ##### i 가 1이 아닌 경우

sumN += valueN ##### n 항의 값(=valueN)을 계속 더해주면 총합이 됨.
print(f'{i}번째 항의 값: {valueN}')
print(f'{i}번째 항까지의 합: {sumN}')

i += 1

inputN1 = int(input('a1 입력: '))
inputD = int(input('공차 입력: '))
inputN = int(input('몇 번째 항을 볼 것인지 입력: '))

sequenceCal(inputN1, inputD, inputN)

1번째 항의 값: 2
1 번째 항까지의 합: 2
2번째 항의 값: 5
2번째 항까지의 합: 7
3번째 항의 값: 8
3번째 항까지의 합: 15
4번째 항의 값: 11
4번째 항까지의 합: 26
5번째 항의 값: 14
5번째 항까지의 합: 40
6번째 항의 값: 17
6번째 항까지의 합: 57
7번째 항의 값: 20
7번째 항까지의 합: 77

05_046 모듈을 이용한 프로그래밍

모듈 부터 만들자

05_046 모듈을 이용한 프로그래밍

모듈 부터 만들자

def exampleResult(s1, s2, s3, s4, s5):

passAvgScore = 60; limitScore = 40

def getTotal():
totalScore = s1 + s2 + s3 + s4 + s5
print(f'총점: {totalScore}')
return totalScore # print가 있는데 왜 또 return이 되지?

def getAverage():
avg = getTotal() / 5
print(f'평균: {avg}')
return avg # print가 있는데 왜 또 return이 되지?

def printPassOrFail():
print(f'{s1}: pass') if s1 >= limitScore else print(f'{s1}: fail')
print(f'{s2}: pass') if s2 >= limitScore else print(f'{s2}: fail')
print(f'{s3}: pass') if s3 >= limitScore else print(f'{s3}: fail')
print(f'{s4}: pass') if s4 >= limitScore else print(f'{s4}: fail')
print(f'{s5}: pass') if s5 >= limitScore else print(f'{s5}: fail')

def printFinalPassOrFail():

if getAverage() >= passAvgScore:
  if s1 >= limitScore and s2 >= limitScore and s3 >= limitScore and s4 >= limitScore and s5 >= limitScore :
      print('Final Pass!!')
      
  else:
      print('Final Fail!!')
      
else:
    print('Final Fail!!')
    

getAverage()
printPassOrFail()
printFinalPassOrFail()

실행

import passOrFail as pf

if name == 'main':
sub1 = int(input('과목1 점수 입력: '))
sub2 = int(input('과목2 점수 입력: '))
sub3 = int(input('과목3 점수 입력: '))
sub4 = int(input('과목4 점수 입력: '))
sub5 = int(input('과목5 점수 입력: '))

pf.exampleResult(sub1, sub2, sub3, sub4, sub5)

총점: 476
평균: 95.2
94: pass
95: pass
96: pass
97: pass
94: pass
총점: 476
평균: 95.2
Final Pass!!

profile
데이터 분석가

0개의 댓글