Exception 클래스를 상속해서 사용자 예외 클래스를 만들 수 있다.
class PasswordLengthShortException(Exception):
def __init__(self, str):
super().__init__(f'{str}: 길이 5미만')
class PasswordLengthLongtException(Exception):
def __init__(self, str):
super().__init__(f'{str}: 길이 10초과')
class PasswordWrongException(Exception):
def __init__(self, str):
super().__init__(f'{str}: 잘못된 비밀번호!!')
adminPw = input('input admin password: ')
try:
if len(adminPw) < 5:
raise PasswordLengthShortException(adminPw)
elif len(adminPw) > 10:
raise PasswordLengthLongtException(adminPw)
elif adminPw != 'admin1234':
raise PasswordWrongException(adminPw)
elif adminPw == 'admin1234':
print('빙고!')
except PasswordLengthShortException as e1:
print(e1)
except PasswordLengthLongtException as e2:
print(e2)
except PasswordWrongException as e3:
print(e3)
=========================================================================
input admin password: admin1234
빙고!
open(), read(), write(), close()를 이용한 텍스트 파일 다루기
file = open('C:/pythonEx/pythonTxt/test.txt', 'w') #C:\pythonEx\pythonTxt > /로 바꿔줘야함
strCnt = file.write('Hello world')
print(f'strCnt: {strCnt}')
file.close()
===============================
strCnt: 11

import time
lt = time.localtime()
dateStr = '[' + str(lt.tm_year) + '년' + \
str(lt.tm_mon) + '월' + \
str(lt.tm_mday) + '일]'
todaySchedule = input('오늘 일정: ')
file = open('C:/pythonEx/pythonTxt/test.txt', 'w')
file.write(dateStr + todaySchedule)
file.close()
====================================================
오늘 일정: python study

file = open('C:/pythonEx/pythonTxt/test.txt', 'r')
str = file.read()
print(f'str: {str}')
file.close()
==============================================
str: [2023년12월6일]python study
파일을 어떤 목적으로 open할지 정한다.
파일 닫기(close)를 생략할 수 있다.
uri = 'C:/pythonTxt/'
file = open(uri + '5_037.txt', 'a')
file.write('python study!!')
file.close()
------------------------------------
with open(uri + '5_037.txt', 'a') as f:
f.write('python study!!'
import random
uri = 'C:/pythonEx/pythonTxt'
def writeNumbers(nums):
for idx, num in enumerate(nums):
with open(uri + 'lotto.txt', 'a') as f:
if idx < (len(nums) - 2): #마지막에 , 안나오게 하려고 한것
f.write(str(num) + ',')
elif idx == (len(nums) - 2):
f.write(str(num))
elif idx == (len(nums) - 1):
f.write('\n')
f.write('bonus: ' + str(num))
f.write('\n')
rNums = random.sample(range(1, 46), 7)
print(f'rNums: {rNums}')
writeNumbers(rNums)
===================================================
rNums: [25, 2, 39, 18, 12, 29, 1]
===================================================
25,2,39,18,12,29
bonus: 1
scoreDic = {'kor': 85, 'eng': 90,'mat': 92,'sci': 79,'his': 82}
uri = 'C:/pythonEx/pythonTxt'
for key in scoreDic.keys():
with open(uri + 'scoreDic.txt', 'a') as f:
f.write(key + '\t: ' + str(scoreDic[key]) + '\n')

파일의 모든 데이터를 읽어서 리스트 형태로 반환한다.
한 행을 읽어서 문자열로 반환한다.
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return n1 * n2
def div(n1, n2):
return n1 / n2
def mod(n1, n2):
return n1 % n2
def flo(n1, n2):
return n1 // n2
def exp(n1, n2):
return n1 ** n2
while True:
print('-' * 60)
selectNum = int(input('1.덧셈, 2.뺄셈, 3.곱셈, 4.나눗셈, 5.나머지, 6.몫, 7.제곱승, 8.종료 '))
if selectNum == 8:
print('Bye~!')
break
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
if selectNum == 1:
print(f'{num1} + {num2} = {add(num1, num2)}')
elif selectNum == 2:
print(f'{num1} - {num2} = {sub(num1, num2)}')
elif selectNum == 3:
print(f'{num1} * {num2} = {mul(num1, num2)}')
elif selectNum == 4:
print(f'{num1} / {num2} = {div(num1, num2)}')
elif selectNum == 5:
print(f'{num1} % {num2} = {mod(num1, num2)}')
elif selectNum == 6:
print(f'{num1} // {num2} = {flo(num1, num2)}')
elif selectNum == 7:
print(f'{num1} ** {num2} = {exp(num1, num2)}')
else:
print('잘못 입력했습니다. 다시 입력하세요.')
print('-' * 60)
================================================================
------------------------------------------------------------
1.덧셈, 2.뺄셈, 3.곱셈, 4.나눗셈, 5.나머지, 6.몫, 7.제곱승, 8.종료 2
첫 번째 숫자 입력: 2.15
두 번째 숫자 입력: 0.15
2.15 - 0.15 = 2.0
------------------------------------------------------------
------------------------------------------------------------
1.덧셈, 2.뺄셈, 3.곱셈, 4.나눗셈, 5.나머지, 6.몫, 7.제곱승, 8.종료 8
Bye~!
def getDistance(speed, hour, minute):
distance = speed * (hour + minute / 60)
return distance
# 100:75 = 60:x ---> 75 * 60 / 100
def getTime(speed, distance):
time = distance / speed
print(f'time: {time}')
h = int(time)
m = int((time - h) * 100 * 60 / 100)
return [h, m]
print('-' * 60)
s = float(input('속도(km/h) 입력 : '))
h = float(input('시간(h) 입력 : '))
m = float(input('시간(m) 입력 : '))
d = getDistance(s, h, m)
print(f'{s}(km/h)속도로 {h}(h)시간 {m}(m)분 동안 이동한 거리: {d}(km)')
print('-' * 60)
print('-' * 60)
s = float(input('속도(km/h) 입력 : '))
d = float(input('거리(km) 입력 : '))
t = getTime(s, d)
print(f'{s}(km/h)속도로 {d}(km)이동한 시간: {t[0]}(h)시간 {t[1]}(m)분')
print('-' * 60)
==========================================================================
------------------------------------------------------------
속도(km/h) 입력 : 90
시간(h) 입력 : 2
시간(m) 입력 : 45
90.0(km/h)속도로 2.0(h)시간 45.0(m)분 동안 이동한 거리: 247.5(km)
------------------------------------------------------------
------------------------------------------------------------
속도(km/h) 입력 : 90
거리(km) 입력 : 247.5
time: 2.75
90.0(km/h)속도로 247.5(km)이동한 시간: 2(h)시간 45(m)분
------------------------------------------------------------
childPrice = 18000
infantPrice = 25000
adultPrice = 50000
specialDC = 50
def formatedNumber(n):
return format(n, ',')
def printAriPlaneReceipt(c1, c2, i1, i2, a1, a2):
print('=' * 40)
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('=' * 40)
print(f'Total: {formatedNumber(c1 + c2 + i1 + i2 + a1 + a2)}명')
print(f'TotalPrice : {formatedNumber(cp + cp_dc + ip + ip_dc + ap + ap_dc)}원')
print('=' * 40)
childCnt = int(input('유아 입력: '))
specialDCChildCnt = int(input(f'할인대상 유아 입력: '))
infantCnt = int(input('소아 입력: '))
specialDCInfantCnt = int(input(f'할인대상 소아 입력: '))
adultCnt = int(input('성인 입력: '))
specialDCAdultCnt = int(input(f'할인대상 성인 입력: '))
printAriPlaneReceipt(childCnt, specialDCChildCnt,
infantCnt, specialDCInfantCnt,
adultCnt, specialDCAdultCnt)
=======================================================================
유아 입력: 1
할인대상 유아 입력: 1
소아 입력: 2
할인대상 소아 입력: 1
성인 입력: 2
할인대상 성인 입력: 0
========================================
유아 1명 요금: 18,000원
유아 할인 대상 1명 요금: 9,000원
소아 2명 요금: 50,000원
소아 할인 대상 1명 요금: 12,500원
성인 2명 요금: 100,000원
성인 할인 대상 0명 요금: 0원
========================================
Total: 7명
TotalPrice : 189,500원
========================================
def formatedNumber(n):
return format(n, ',')
def recursionFun(n):
if n == 1:
return n
return n * recursionFun(n - 1)
inputNumber = int(input('input number: '))
inputNumberFormated = formatedNumber(recursionFun(inputNumber))
print(inputNumberFormated)
====================================================================
input number: 10
3,628,800
def formatedNumber(n):
return format(n, ',')
def singleRateCalculator(m, t, r):
totalMoney = 0
totalRateMoney = 0
for i in range(t):
totalRateMoney += m * (r * 0.01)
totalMoney = m + totalRateMoney
return int(totalMoney)
def multiRateCalculator(m, t, r):
t = t * 12
rpm = (r / 12) * 0.01 #월이자.
totalMoney = m
for i in range(t):
totalMoney += totalMoney * rpm
return int(totalMoney)
money = int(input('예치금(원): '))
term = int(input('기간(년): '))
rate = int(input('연 이율(%): '))
print()
print('[단리 계산기]')
print('=' * 30)
print(f'예치금\t: {formatedNumber(money)}원')
print(f'예치기간\t: {term}년')
print(f'연 이율\t: {rate}%')
print('-' * 30)
amount = formatedNumber(singleRateCalculator(money, term, rate))
print(f'{term}년 후 총 수령액: {amount}원')
print('=' * 30)
print()
print('[월복리 계산기]')
print('=' * 30)
print(f'예치금\t: {formatedNumber(money)}원')
print(f'예치기간\t: {term}년')
print(f'연 이율\t: {rate}%')
print('-' * 30)
amount = formatedNumber(multiRateCalculator(money, term, rate))
print(f'{term}년 후 총 수령액: {amount}원')
print('=' * 30)
===============================================================
예치금(원): 10000000
기간(년): 3
연 이율(%): 3
[단리 계산기]
==============================
예치금 : 10,000,000원
예치기간 : 3년
연 이율 : 3%
------------------------------
3년 후 총 수령액: 10,900,000원
==============================
[월복리 계산기]
==============================
예치금 : 10,000,000원
예치기간 : 3년
연 이율 : 3%
------------------------------
3년 후 총 수령액: 10,940,514원
==============================
def sequenceCal(n1, d, n):
valueN = 0
sumN = 0
i = 1
while i <= n:
if i == 1:
valueN = n1
sumN += valueN
print('{}번째 항의 값: {}'.format(i, valueN))
print('{}번째 항까지의 합: {}'.format(i, sumN))
i += 1
continue
valueN += d
sumN += valueN
print('{}번째 항의 값: {}'.format(i, valueN))
print('{}번째 항까지의 합: {}'.format(i, sumN))
i += 1
def sequenceCal01(n1, d, n):
# 등차 수열(일반항) 공식: an = a1 + (n-1) * d
valueN = n1 + (n-1) * d
print('{}번째 항의 값: {}'.format(n, valueN))
# 등차 수열(합) 공식: sn = n(a1 + an) / 2
sumN = n * (n1 + valueN) / 2
print('{}번째 항까지의 합: {}'.format(n, int(sumN)))
inputN1 = int(input('a1 입력: '))
inputD = int(input('공차 입력: '))
inputN = int(input('n 입력: '))
sequenceCal(inputN1, inputD, inputN)
print('-' * 50)
sequenceCal01(inputN1, inputD, inputN)
=================================================================
a1 입력: 2
공차 입력: 3
n 입력: 7
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
--------------------------------------------------
7번째 항의 값: 20
7번째 항까지의 합: 77
이 글은 제로베이스 데이터 분석 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.
점점 더 어려워지는것같다..
이번주는 샘플프로젝트/일 + 진도(1.5) 분량으로 진행해야되다보니 복습이 부실해보인다.😭
밀린 진도를 어느정도 따라잡으면 다시 복습을 여러번 해야될것같고, 코드를 달달 외우는게 좋을것같다..! 아직 한달도 안됐으니 어려운게 당연하다고 생각하고 해야될것부터 해보자!