def add(n1, n2):
print(n1 + n2)
def div(n1, n2):
print(n1 / n2)
fn = int(input('input firstNum: '))
sn = int(input('input secondNum: '))
add(fn,sn)
div(fn,sn)
# 예외 예시
print(int('hello'))
print(3/0)
lists = [1, 2, 3, 4, 5, 6]
print(lists[5])
- 예외 처리: 예외가 프로그램 전체 영향이 없도록 처리
# 사용자로부터 숫자 5개를 입력했을 때 숫자가 아닌 자료형이 입력되면 예외 처리하는 프로그램
nums = []
n = 1
while n < 6:
try:
num = int(input('input number: '))
except:
print('예외 발생!')
continue
nums.append(num)
n += 1
print(f'nums: {nums}')
nums = []
n = 1
while n < 6:
try:
num = int(input('input number: '))
except:
print('예외 발생!!')
continue
else:
if num % 2 == 0:
nums.append(num)
n += 1
else:
print('홀수입니다.', end='')
print('다시 입력하세요.')
continue
print(f'nums: {nums}')
# 실습: 사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수와 입력한 모든 데이터를 각각 출력하는 프로그램을 만들어보자.
evenList = []; oddList = []; floatList = []; dataList = []
n = 1
while n < 6:
try:
data = input('input number: ')
floatNum = float(data)
except:
print('exception rise!')
print('not number!')
continue
else:
if floatNum - int(floatNum) != 0:
print('float number!')
floatList.append(floatNum)
else:
if floatNum % 2 == 0:
print('even number!')
evenList.append(floatNum)
else:
print('odd number!')
oddList.append(floatNum)
n += 1
finally:
dataList.append(data) #에러가 뜨든 말든 사용자가 입력한 데이터를 모두 수집
print(f'evenList: {evenList}')
print(f'oddList: {oddList}')
print(f'floatList: {oddList}')
print(f'dataList: {dataList}')
num1 = int(input('input number1: '))
num2 = int(input('input number2: '))
try:
print(f'num1/num2 = {num1 / num2}')
except Exception as e:
print(f'exception: {e}')
print(f'num1*num2 = {num1 * num2}')
print(f'num1+num2 = {num1 + num2}')
print(f'num1-num2 = {num1 - num2}')
def divCalculator(n1,n2):
if n2 != 0:
print(f'{n1}/{n2}: {n1/n2}')
else:
raise Exception('0으로 나눌 수 없습니다.')
num1 = int(input('input number1: '))
num2 = int(input('input number2: '))
try:
divCalculator(num1,num2)
except Exception as e:
print(f'Exception: {e}')
class NotUSeZeroException(Exception):
def __init__(self, n):
super().__init__(f'{n}은 사용할 수 없습니다.')
def divCalculator(n1,n2):
if n2 == 0:
raise NotUSeZeroException(n2)
else:
print(f'{n1}/{n2}: {n1/n2}')
num1 = int(input('input number1: '))
num2 = int(input('input number2: '))
try:
divCalculator(num1, num2)
except NotUSeZeroException as e:
print(e)
# 실습: 관리자 암호를 입력하고 다음 상태에 따라 예외 처리하는 예외 클래스를 만들어보자.
class PasswordLengthShortException(Exception):
def __init__(self, str):
super().__init__(f'{str}: 길이 5미만!')
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 != 'adminPw':
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)
open() -> read() or write() -> close()
file = open('/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt/test.txt', 'w')
strCnt= file.write('Hello python!')
print(f'strCnt: {strCnt}')
file.close()
예제)
import time
lt = time.localtime()
# dateStr = '[' + str(lt.tm_year) + '년' + str(lt.tm_mon) + '월'+ str(lt.tm_mday) + '일]'
dateStr = '[' + time.strftime('%Y-%m-%d %H:%M:%S %p') + ']'
todaySchedule = input('오늘 일정: ')
file = open('/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt/test.txt', 'w')
file.write(dateStr + todaySchedule)
file.close()
file = open('/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt/test.txt', 'r')
str = file.read()
print(f'str: {str}')
file.close()
str.replace('Python' , '파이썬', 2)
- 내가 읽은 파일 중에 Python 이라고 되어있는 것 2개를 파이썬 으로 바꾸겠다.
file = open('파이썬 파일 주소', 'r') str = file.read() print(f'str: {str}') str = str.replace('Python', '파이썬', 2) print(f'str: {str}') file.close()
- 파일을 다양한 방식으로 open 할 수 있다.
- 쓰기 모드: w, a, x
- 읽기 모드: r
uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'
# 'w' 모드
file = open(uri + 'hello.txt', 'w')
file.write('hello python')
file.close()
# 'a' 모드
file = open(uri + 'hello.txt', 'a')
file.write('\nnice to meet you')
file.close()
# 'x' 모드
# file = open(uri + 'hello.txt', 'x')
# file.write('\nnice to meet you')
# file.close()
# 'r' 모드
file = open(uri + 'hello.txt', 'r')
str = file.read()
print(f'str: {str}')
file.close()
예제 1) 사용자가 입력한 숫자에 대한 소수를 구하고 이를 파일에 작성해보자.
uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'
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)
1) 기본적인 파일 쓰기, 읽기
file = open(uri + '5_037.txt', 'a')
file.write('python study')
file.close()
file = open(uri + '5_037.txt', 'r')
print(file.read())
file.close()
2) with ~ as 를 이용한 파일 닫기가 생략된 과정
with open(uri + '5_037.txt', 'a') as f:
f.write('python study!!')
with open(uri + '5_037.txt', 'r') as f:
print(f.read())
# 실습: 로또 번호 용지 만들기
import random
uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/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)
languages = ['c/c++', 'java', 'c#', 'python', 'javascript']
uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'
for item in languages:
with open(uri + 'languages.txt', 'a') as f:
f.write(item)
f.write('\n')
# writelines()를 이용하면 훨씬 쉽게 리스트 반복 가능
with open(uri + 'languages.txt', 'a') as f:
f. writelines(languages)
# 개행을 하려면
with open(uri + 'languages.txt', 'a') as f:
f.writelines(item + '\n' for item in languages)
with open(uri + 'languages.txt', 'r') as f:
print(f.read())
# 실습: 딕셔너리에 저장된 과목별 점수를 파일에 저장하는 코드 작성
uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'
scoreDic = {'kor': 85, 'eng': 90, 'mat': 92, 'sci': 79, 'his': 82}
for key in scoreDic.keys():
with open(uri + 'scoreDic.txt', 'a') as f:
f.write(key + '\t:' + str(scoreDic[key]) + '\n')
# scoreDic 모양 그대로 텍스트 파일에 입력
with open(uri + 'scores.txt', 'a') as f:
print(scoreDic, file=f)
with open(uri + 'lans.txt', 'r') as f:
lanList = f.readlines()
print(f'lanList: {lanList}')
print(f'lanList type: {type(lanList)}')
with open(uri + 'lans.txt', 'r') as f:
line = f.readline()
while line != '':
print(f'line: {line}', end='')
line = f.readline()
# 실습(list, split, strip, dictionary 개념 필요)
scoresDic = {}
with open(uri + 'scores.txt', 'r') as f:
line = f.readline()
while line != '':
tempList= line.split(':')
scoresDic[tempList[0]] = int(tempList[1].strip('\n'))
line = f.readline()
print(f'scoresDic: {scoresDic}')
파이썬 중급 문제풀이를 조금이나마 수월하게 하기 위해, 기초수학 파트를 먼저 공부하고 돌아왔는데, 돌아오니 파이썬 중급 개념을 다 까먹었다 ㅋㅋㅋㅋㅋ
반복, 또 반복만이 유일한 방법이지 않을까 싶다..