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
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 != '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)
로그인에 성공했습니다!
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()
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 = '[' + 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()
file = open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/about_python.txt', 'r', encoding='UTF8')
str = file.read()
print(f'str = {str}')
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> 에서따온 것이다.
uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'
file = open(uri + 'hello.txt', 'w')
file.write('Hello Python')
file.close()
uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'
file = open(uri + 'hello.txt', 'a')
file.write('\nNice to meet u')
file.close()
uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'
file = open(uri + 'hello_01.txt', 'x')
file.write('\nNice to meet u')
file.close()
uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/'
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', '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)
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)
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 문 종료
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}
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
번호를 잘 못 입력했습니다.
계산기를 종료합니다.
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 이다.
이제 파이썬 중급 개념이 끝나고 중급 문제풀이로 접어섰다.
사실 개념 학습이 제대로 되지 않은 느낌이 들었다.
문제 풀이에서 많은 문제를 풀어보며 확실히 개념을 잡도록 하겠다.