제로베이스_데이터스쿨_리뷰노트_230406학습내용복습_파이썬중급7,8_파이썬문풀1

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

Git

05 033 사용자 예외 클래스 / 내가 직접 예외를 처리하자

exception 클래스 상속 -> 사용자

class NotUseZeroException(Exception):

def init(self, n):
super().init(f'{n}은 사용할 수 없습니다!!')

def divCalculator(num1, num2):

if num2 == 0:
raise NotUseZeroException(num2)
else:
print(f'{num1} / {num2} = {num1 / num2}')

num1 = int(input('input number1: '))
num2 = int(input('input number2: '))

try:
divCalculator(num1, num2)
except NotUseZeroException as e: # 왜 클래스 이름 다음에 ()를 안 넣지?
print(e)

55 / 11 = 5.0

실습 관리자 암호를 입력하고 암호가 5 미만인 경우 / 10 초과인 경우 / 암호가 틀린 경우 예외처리하는 클래스 만들기

암호가 5미만인 경우

class PasswordLengthShortException(Exception):
def init(self, str):
super().init(f'{str}: 길이 5미만입니다. 다시 입력하세요.')

암호가 10 초과인 경우

class PasswordLengthLongException(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 PasswordLengthLongException(adminPw)

elif adminPw != 'admin1234':
raise PasswordWrongException(adminPw)

elif adminPw == 'admin1234':
print('로그인에 성공했습니다!')

except PasswordLengthShortException as e1:
print(e1)

except PasswordLengthLongException as e2:
print(e2)

except PasswordWrongException as e3:
print(e3)

로그인에 성공했습니다!

05 034 기본 함수 파일쓰기

open -> read / write -> close

open(디렉토리명, 파일모드 : w -> 쓰기 모드 / r -> 읽기 모드)

file = open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/test.txt', 'w')

strCnt = file.write('Hello world!')

print(f'몇 글자 쓰여졌는지 = {strCnt}')

file.close()

몇 글자 쓰여졌는지 = 12

import time

lt = time.localtime()

dateStr = '[' + str(lt.tm_year) + '년' + str(lt.tm_mon) + '월' + str(lt.tm_mday) + '일] '

todaySchedule = input('오늘 일정: ')

file = open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/test.txt', 'w')

file.write(dateStr + todaySchedule)
file.close()

05 035 텍스트 파일 읽기

read() 함수

file = open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/test.txt', 'r')

str = file.read()
print(f'str = {str}')

file.close()

str = [2023-04-06 02:07:21 PM]쓰레기 버리기

포맷이라는 함수 이용하기

import time

lt = time.localtime()

dateStr = '[' + str(lt.tm_year) + '년' + str(lt.tm_mon) + '월' + str(lt.tm_mday) + '일] '

dateStr = '[' + time.strftime('%Y-%m-%d %I:%M:%S %p') +']'

todaySchedule = input('오늘 일정: ')

file = open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/test.txt', 'w')

file.write(dateStr + todaySchedule)
file.close()

실습 텍스트 파일에서 Python을 파이썬으로 변경해서 파일에 다시 저장하자

file = open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/about_python.txt', 'r', encoding='UTF8')

str = file.read()
print(f'str = {str}')

str.replace('Python', '파이썬') -> 이렇게 하면 모든 문자가 다 바뀜 / 우리가 하고자하는 건 앞 쪽 두 개만 바꾸는 것

file.close()

str = str.replace('Python', '파이썬', 2)
print(f'changed str = {str}')

file = open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/about_python.txt', 'w')

file.write(str)

file.close()

str = Python은 1991년 프로그래머 귀도 반 로섬이 발표한 고급 프로그래밍 언어로,
플랫폼에 독립적이며 인터프리터식, 객체지향적, 동적 타이핑(dynamically typed) 대화형 언어이다.
Python이라는 이름은 귀도가 좋아하는 코미디 <Monty Python's Flying Circus> 에서따온 것이다.
changed str = 파이썬은 1991년 프로그래머 귀도 반 로섬이 발표한 고급 프로그래밍 언어로,
플랫폼에 독립적이며 인터프리터식, 객체지향적, 동적 타이핑(dynamically typed) 대화형 언어이다.
파이썬이라는 이름은 귀도가 좋아하는 코미디 <Monty Python's Flying Circus> 에서따온 것이다.

05 036 텍스트 파일 열기 모드

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

'w' 파일 모드

file = open(uri + 'hello.txt', 'w')
file.write('Hello Python')
file.close()

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

'a' 파일 모드 - 덧붙임

file = open(uri + 'hello.txt', 'a')
file.write('\nNice to meet u')
file.close()

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

'x' 파일 모드 -> 기존에 파일이 있으면 에러 남

file = open(uri + 'hello_01.txt', 'x')
file.write('\nNice to meet u')
file.close()

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

'r' 파일 모드

file = open(uri + 'hello_01.txt', 'r')
str = file.read()
print(f'str = {str}')
file.close()

str =
Nice to meet u

실습 / 사용자가 입력한 숫자에 대한 소수를 구하고 이를 파일에 작성해보자

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

def writePrimeNumber(n):
file = open(uri + 'prime_numbers.txt', 'a')
file.write(str(n))
file.write('\n')
file.close()

inputNumber = int(input('0보다 큰 정수 입력: '))
for number in range(2, (inputNumber + 1)):
flag = True
for n in range(2, number):
if number % n == 0:
flag = False
break

if flag:
writePrimeNumber(number)

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

file = open(uri + '05_037.txt', 'a')
file.write('python study!!')
file.close()

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

file = open(uri + '05_037.txt', 'r')
print(file.read())
file.close()

python study!!

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + '연습1.txt', 'w') as f:
f.write('python easy!')

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'practice_without_complex.txt', 'w') as f:

f.write('practice is not shame thing')

with open(uri + 'practice_without_complex.txt', 'r') as f:
print(f.read())

practice is not shame thing

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'practice.txt', 'w') as gg:
gg.write('today, my day')

with open(uri + 'practice.txt', 'r') as read:
print(read.read())

today, my day

로또 번호 생성기 프로그램 / 파일에 번호 출력하기

import random

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

def writeNumbers(nums):
for idx, num in enumerate(nums): # enumerate?
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)

05 038 writelines() / 반복 가능한 자료형의 데이터를 파일에 쓰자!

writelines()는 리스트 또는 튜플 테이터를 파일에 쓰기 위한 함수이다.

languages = ['a', 'b', 'c', 'd', 'e']

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

for item in languages:
with open(uri + 'languages.txt', 'a') as f:
f.write(item)
f.write('\n')

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

languages = ['a', 'b', 'c', 'd', 'e']

with open(uri + 'languages_writelines.txt', 'w') as f:
f.writelines(item + '\n' for item in languages)

with open(uri + 'languages_writelines.txt', 'r') as read:
print(read.read())

a
b
c
d
e

실습 딕셔너리에 저장된 과목별 점수를 파일에 저장하는 코드 작성

scoreDic = {'kor' : 85, 'eng' : 90, 'mat' : 92, 'sci' : 79, 'his' : 82}

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

for key in scoreDic.keys():
with open(uri + 'scoreDic.txt', 'a') as f:
f.write(key + '\t: ' + str(scoreDic[key]) + '\n')

딕셔너리 통째로 쓰기

scoreDic = {'kor' : 85, 'eng' : 90, 'mat' : 92, 'sci' : 79, 'his' : 82}

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'scores.txt', 'a') as f:
print(scoreDic, file = f)

리스트 통째로 쓰기

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

scoreList = [85, 90, 92, 79, 82]

with open(uri + 'scoreList.txt', 'a') as f:
print(scoreList, file = f)

05 039 여러 읽기와 한 줄 읽기

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'lans.txt', 'r') as f:
lanList = f.readlines() # readlines는 모든 것을 읽어서 리스트로 반환해줌 그래서 list에 담는다

print(f'lanList: {lanList}')
print(f'lanList type: {type(lanList)}')

lanList: ['c/c++\n', 'java\n', 'python\n', 'javascript\n', 'R']
lanList type: <class 'list'>

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'lan.txt' , 'r') as f:
line = f.readline()

while line != '':
print(f'line: {line}') # -> 자동 개행
line = f.readline() # 계속해서 내려가 읽고 싶으면 또 한 번 다음 행으로 가서 읽게 함 / R 까지 다 읽고 line = '' 이 되면 자동으로 while 문 종료

프린트 자체가 하나의 개행을 하는 경우가 있다. / 그런데 lan.txt 파일 자체에 개행하는 기능이 있어 두 줄씩 띄어서 출력이 되는 것이다.

line: c/c++
line: java
line: python
line: javascript
line: R

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'lan.txt' , 'r') as f:
line = f.readline()

while line != '':
print(f'line: {line}', end = '') # 두 줄씩 띄는 것을 막고자
line = f.readline()

line: c/c++
line: java
line: python
line: javascript
line: R

실습 파일에 저장된 과목별 점수를 파이썬에 읽어, 딕셔너리에

scoreDic = {}

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'scores.txt', 'r') as f:
line = f.readline()

while line != '':
tempList = line.split(':') # 구분자를 정해주면 구분자를 기점으로 리스트로 다 분리를 시켜준다 / 'kor:85' 면 kor 따로, 85 따로 분리 / 구분해준 데이터는 리스트에 담아서 반환
print(f'tempList : {tempList}')
line = f.readline()

결과 값==============================
tempList : ['kor', '85\n']
tempList : ['eng', '90\n']
tempList : ['mat', '92\n']
tempList : ['sic', '79\n']
tempList : ['his', '82'] -> 결과 값이 이렇게 나오는데, '\n' 지워줘야 하고 숫자들을 문자형이 아닌 숫자형으로 다 캐스팅 해줘야 한다.

scoreDic = {}

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'

with open(uri + 'scores.txt', 'r') as f:
line = f.readline()

while line != '':
tempList = line.split(':')
scoreDic[tempList[0]] = int(tempList[1].strip('\n')) # tempList의 인덱스 0 값이 scoreDic의 키 값이 되어야 한다. 그리고 그 키 값에 저장되는 벨류 값을 넣어준다 / 벨류 값은 tempList의 인덱스 1, but 그냥 넣지 않고 strip 써서 \n 없애줘야함 / 그리고 그걸 int로 캐스팅한다 !

# print(f'tempList : {tempList}')
line = f.readline()

print(f'scoreDic: {scoreDic}')

scoreDic: {'kor': 85, 'eng': 90, 'mat': 92, 'sic': 79, 'his': 82}

파이썬 중급 문풀 시작 ~

05 040 함수 / 함수를 이용한 프로그래밍

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('굳 바이')
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:8

print('잘 못 입력했습니다. 다시 입력하세요.')

print('-' * 60)


99.0 % 11.0 = 0.0


99.0 // 11.0 = 9.0


잘 못 입력했습니다. 다시 입력하세요.


굳 바이

재 연습

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('-'*66)
selectNum = int(input('1. 덧셈, 2. 뺄셈, 3. 곱셈, 4. 나눗셈, 5. 나머지, 6. 몫, 7. 제곱승, 8. 종료'))
if selectNum == 8:
print('계산기를 종료합니다.')
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('-'*66)


99.0 % 8.0=3.0


8.0 ** 2.0=64.0


99.0 // 55.0=1.0


번호를 잘 못 입력했습니다.


계산기를 종료합니다.

05 041 함수

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

def getDistance(s, h, m):
return s h (m/60 * 10)

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)


99.24 km/h 속도로 11시간 12분 이동한 거리는 2183.28km 이다.

이제 파이썬 중급 개념이 끝나고 중급 문제풀이로 접어섰다.

사실 개념 학습이 제대로 되지 않은 느낌이 들었다.

문제 풀이에서 많은 문제를 풀어보며 확실히 개념을 잡도록 하겠다.

profile
데이터 분석가

0개의 댓글