#정상 실행
print("오류는 아주 사소한것부터 발생합니다.")
#예외 발생
dogs.append("말티즈") # 리스트가 없음
# x=3, y=5
x, y = map(int, input("밑변과 높이를 입력해주세요").split(" "))
# map(int,~) : 여러개의 값을 받는 것들을 한번에 정수형으로 변환
# split(" ") : 입력되는 두개의 값을 각각 띄어쓰기로 구분 = 3 5
# 계산결과 출력
print(f'삼각형의 넓이는 {x*y/2}입니다.')
위의 예시는 정상적으로 작동하는데, 만약 입력값을 x=3cm ,y=5cm로 입력한다면
isdigit() 를 사용합니다.isdigit()
# x=3cm, y=5cm
x, y = input("밑변과 높이를 입력해주세요").split(" ")
if x.isdigit() and y.isdigit():
# 계산결과 출력
x , y = int(x), int(y)
print(f'삼각형의 넓이는 {x*y/2}입니다.')
else:
print("정수로 입력하지 않아 계산이 불가합니다.")
isdigit(): 문자열(str)의 메서드(method)라서 x.isdigit()처럼 점(.)을 찍고 호출
isdigit(x) : isdigit()은 독립적인 함수가 아니라, 문자열(str)의 메서드이기 때문에 불가
try:
예외가 발생할 가능성이 있는 코드
except
예외가 발생했을 때 실행할 코드
# x=3, y=5
try:
x, y = map(int, input("밑변과 높이를 입력해주세요").split(" "))
# 계산결과 출력
print(f'삼각형의 넓이는 {x*y/2}입니다.')
except:
print("정수로 입력하지 않아 계산이 불가합니다.")
try:
예외가 발생할 가능성이 있는 코드
except
pass
list_input = ["1", "7", "3", "마피아", "4"]
list_number = []
for item in list_input:
try:
int(item)
list_number.append(item)
except:
pass
print(f'{list_input} 내부에 있는 숫자는')
print(f'{list_number}입니다.')
int(item) : item에 있는 값들을 정수로 바꿀 수 있는지 확인 int() : "숫자 모양의 문자열"만 정수로 바꿀 수 있음 → 제한이 있음.str() : 웬만한 자료형을 다 문자열로 바꿈 → 제한이 거의 없음.else 구문을 붙여서 사용하면 예외가 발행하지 않았을 때 실행할 코드를 지정가능try:
예외가 발생할 가능성이 있는 코드
except:
예외가 발생했을 때 실행할 코드
else:
예외가 발생하지 않았을 때 실행할 코드
# x=3cm, y=5cm
try:
x, y = map(int, input("밑변과 높이를 입력해주세요").split(" "))
except:
print("정수로 입력하지 않아 계산이 불가합니다.") # 이 줄 출력
else:
# 계산결과 출력
print(f'삼각형의 넓이는 {x*y/2}입니다.')
try:
예외가 발생할 가능성이 있는 코드
except:
예외가 발생했을 때 실행할 코드
else:
예외가 발생하지 않았을 때 실행할 코드
finally:
무조건 실행할 코드
# x=3, y=5
try:
x, y = map(int, input("밑변과 높이를 입력해주세요").split(" "))
# 계산결과 출력
print(f'삼각형의 넓이는 {x*y/2}입니다.') # ~7.5 입니다.
except:
print("정수로 입력하지 않아 계산이 불가합니다.")
else:
print("계산이 정상적으로 되었습니다.") # ~ 되었습니다
finally:
print("프로그램이 종료 되었습니다.") # ~ 되었습니다.
Exception을 사용하면 예외의 종류에 대해 알 수 있습니다.except를 일일이 안 써도 웬만한 에러를 한 번에 처리 가능# x=3cm, y=5cm
try:
x, y = map(int, input("밑변과 높이를 입력해주세요").split(" "))
# 계산결과 출력
print(f'삼각형의 넓이는 {x*y/2}입니다.')
except Exception as exception:
# 예외에 대한 정보 출력
print("type(exception):", type(exception))
print("exception:", exception)
# type(exception): <class 'ValueError'>
# exception: invalid literal for int() with base 10: '3cm'
Exception :파이썬에서 모든 예외의 최상위 클래스.as exception : 발생한 예외 객체를 exception이라는 변수에 담아서 쓸 수 있음.as 사용 안하면 예외가 발생했다는것은 알 수 있지만 어떤 에러인지는 알 수 없음try:
예외가 발생할 가능성이 있는 구문
except 예외 키워드1:
예외 키워드1가 발생했을 때 실행할 구문
except 예외 키워드2:
예외 키워드2가 발생했을 때 실행할 구문
except 예외 키워드3:
예외 키워드3이 발생했을 때 실행할 구문
numbers = [23, 11, 7, 4, 12]
try:
number_input = int(input("찾고싶은 값의 위치를 입력해주세요"))
print(f'{number_input}번째 요소 : {numbers[number_input]}')
except ValueError: # 정수로 입력하지 않아서 발생한 에러
print("정수로 입력해주세요")
except IndexError: # 리스트에 없는거 입력해서 발생한 에러
print("리스트의 범위를 벗어났습니다. 입력값을 다시 확인해주세요")
numbers = [23, 11, 7, 4, 12]
try:
number_input = int(input("찾고싶은 값의 위치를 입력해주세요"))
print(f'{number_input}번째 요소 : {numbers[number_input]}')
문제를.만들자 # 여기서 에러 발생
except ValueError as exception:
print("정수로 입력해주세요")
print("exception:", exception)
except IndexError as exception:
print("리스트의 범위를 벗어났습니다. 입력값을 다시 확인해주세요")
print("exception:", exception)
# 위의 2가지로 예외처리가 불가능한 경우 모든 예외처리가 가능한 Exception을 이용하면 가능
except Exception as exception:
print("대처 불가한 예외가 발생했습니다.")
print(type(exception), exception)
1 을 입력해서 1번째 요소 : 11 이 출력 -> 문제를.만들자 여기서 에러 발생 Exception으로 대처1번째 요소 : 11
대처 불가한 예외가 발생했습니다.
<class 'NameError'> name '문제를' is not defined
class NegativeNumberError(Exception):
pass
try:
number = int(input("양수를 입력하세요: "))
if number < 0:
raise NegativeNumberError("음수가 입력되었습니다. 양수를 입력해주세요!")
except NegativeNumberError as er:
print(er)
class NegativeNumberError(Exception):
number = input("숫자를 입력해주세요")
number = int(number)
#조건문 사용
if number > 0:
#양수일 때: 아직 미구현 상태
raise NotImplementedError
else:
#음수일 때: 아직 미구현 상태
raise NotImplementedError
| 함수 | 설명 | 사용 예시 |
|---|---|---|
| sin(x) | 사인 값을 구함 | print(math.sin(5)) |
| cos(x) | 코사인 값을 구함 | print(math.cos(5)) |
| ceil(x) | 올림 | print(math.ceil(3.4)) |
| floor(x) | 내림 | print(math.floor(5.2)) |
from 모듈 이름 import 가져오고 싶은 변수 또는 함수from math import sin, cos, ceil, floor
print(sin(5))
print(cos(5))
print(ceil(3.4))
print(floor(5.2))
from math import * : math 모듈의 모든 함수를 가져오는 방법으로 import에 * import math as mimport math as m
print(m.sin(5))
print(m.cos(5))
print(m.ceil(3.4))
print(m.floor(5.2))
import os
#기본 정보 출력
print("현재 운영체제:", os.name)
print("현재 폴더:", os.getcwd())
print("현재 운영체제:", os.listdir())
os.mkdir("oz") : 폴더 생성
os.rmdir("oz") : 폴더 제거
with open("food.txt", "w") as file: 파일생성(이름,"w":write:내용 쓸거임)
file.write("배가 고프네요") : 쓸 내용
os.rename("food.txt", "hungry.txt") (기존이름 , 바꿀이름 ) 이름변경
파일 제거
os.remove("hungry.txt")
시스템 명렁어 사용
mac
os.system("ls")
window
os.system("dir")
import datetime
print("오늘 날짜와 시간 출력")
now = datetime.datetime.now() # (모듈이름,클래스,함수이름) 현재날짜와 시간 출력
print(now.year, "년")
print(now.month, "월")
print(now.day, "일")
print(now.hour, "시")
print(now.minute, "분")
print(now.second, "초")
print()
import datetime
print("다양한 시간 포맷")
output_1 = now.strftime("%Y.%m.%d %H:%M:%S")
output_2 = f'{now.year}년 {now.month}월 {now.day}일 {now.hour}시 {now.minute}분 {now.second}초'
output_3 = now.strftime("%Y{} %m{} %d{} %H{} %M{} %S{}").format(*"년월일시분초")
print(output_1)
print(output_2)
print(output_3)
print()
import time
print("3초 뒤에 어떤일이 일어날까요?")
time.sleep(3)
print("아무일도 없었다")
from urllib import request
target = request.urlopen("https://www.naver.com")
web_code = target.read()
print(web_code)
from urllib import request
from bs4 import BeautifulSoup
target = request.urlopen("https://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108")
soup = BeautifulSoup(target, "html.parser")
for location in soup.select("location"):
print("도시:", location.select_one("city").string)
print("날씨:", location.select_one("wf").string)
print("최저기온:", location.select_one("tmn").string)
print("최고기온:", location.select_one("tmx").string)
print()
def test(function):
def wrapper():
print("허언증이 재발했습니다.")
function()
print("격리 되었습니다.")
return wrapper
@test
def oz():
print("파이썬 진짜 재미있엉 하하")
oz()
#oz_module.py
pi = 3.141592
#반지름 값을 받아오는 함수
def number_input():
value = input("반지름을 입력해주세요")
return float(value)
#원의 둘레
def get_circum(radius):
return 2 * pi * radius
#원의 넓이
def get_circle(radius):
return pi * radius * radius
#oz.py
import oz_module as oz
radius = oz.number_input()
print(oz.get_circum(radius))
print(oz.get_circle(radius))
# oz_module_1.py
val_1 = "module_1의 변수"
# oz_module_2.py
val_2 = "module_2의 변수"
# main.py
import oz_package.oz_module_1 as one
import oz_package.oz_module_2 as two
print(one.val_1)
print(two.val_2)