λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸ“πŸ’ͺ/Python

Python νŠΉκ°•(5) (try-except, stacktrace, comprehension)

by μˆ˜μ¨”μ•™ 2022. 9. 14.

μ˜€λŠ˜λ„ νŠΉκ°•κ³Ό 

점프 투 νŒŒμ΄μ¬μ„ 같이 κ³΅λΆ€ν•΄λ³΄μŸ!

https://wikidocs.net/30

 

05-4 μ˜ˆμ™Έ 처리

ν”„λ‘œκ·Έλž¨μ„ λ§Œλ“€λ‹€ 보면 μˆ˜μ—†μ΄ λ§Žμ€ 였λ₯˜λ₯Ό λ§Œλ‚˜κ²Œ λœλ‹€. λ¬Όλ‘  였λ₯˜κ°€ λ°œμƒν•˜λŠ” μ΄μœ λŠ” ν”„λ‘œκ·Έλž¨μ΄ 잘λͺ» λ™μž‘ν•˜λŠ” 것을 막기 μœ„ν•œ 파이썬의 배렀이닀. ν•˜μ§€λ§Œ λ•Œλ•Œλ‘œ μ΄λŸ¬ν•œ 였λ₯˜ ...

wikidocs.net

 


try / except

μ˜ˆμ™Έμ²˜λ¦¬!

μ—λŸ¬κ°€ λ°œμƒν•  경우 μ—λŸ¬κ°€ μ•ˆλ‚˜κ³  except둜 λ„˜μ–΄κ°„λ‹€!

 

 

1. try, except 기본ꡬ쑰

try:
    ...
except [λ°œμƒ 였λ₯˜[as 였λ₯˜ λ©”μ‹œμ§€ λ³€μˆ˜]]:
    ...

였λ₯˜κ°€ λ°œμƒν•˜λ©΄ exceptκ°€ μˆ˜ν–‰λ˜μ§€λ§Œ 였λ₯˜κ°€ λ°œμƒν•˜μ§€ μ•ŠμœΌλ©΄ μˆ˜ν–‰λ˜μ§€ μ•ŠλŠ”λ‹€!

 

2. except ꡬ문 μ‚¬μš©λ²•

예λ₯Ό 듀어보면

였λ₯˜λ³„λ‘œ λ‹€λ₯΄κ²Œ 찍어쀄 μˆ˜λ„ μžˆλŠ”λ° μ–΄λ–€ μ’…λ₯˜κ°€ μžˆλŠ”μ§€ λ¨Όμ € μ•Œμ•„λ³΄μž

 

 

3. 였λ₯˜μ˜ μ’…λ₯˜

1) FileNotFoundError 였λ₯˜

λ¨Όμ € 디렉터리 μ•ˆμ— μ—†λŠ” νŒŒμΌμ„ μ—΄λ €κ³  μ‹œλ„ν–ˆμ„ λ•Œ

>>> f = open("λ‚˜μ—†λŠ”νŒŒμΌ", 'r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'λ‚˜μ—†λŠ”νŒŒμΌ'

 

2) ZeroDivisionError 였λ₯˜

0으둜 λ‹€λ₯Έ 숫자λ₯Ό λ‚˜λˆ„λŠ” 경우

>>> 4 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

 

3) IndexError 였λ₯˜

aλŠ” 리슀트 [1, 2, 3]인데 a[4]λŠ” a λ¦¬μŠ€νŠΈμ—μ„œ 얻을 수 μ—†λŠ” 값이닀. λ”°λΌμ„œ IndexError 였λ₯˜κ°€ λ°œμƒ

>>> a = [1,2,3]
>>> a[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

 

4) ValueError 였λ₯˜

int둜 λ³€ν™˜ν•˜λŠ” κ³Όμ •μ—μ„œ μ—λŸ¬κ°€ λ°œμƒν•  λ•Œ

 

이외에 더 λ§Žμ€ μ—λŸ¬λŠ” μ°Έκ³ !

https://docs.python.org/ko/3/library/exceptions.html

 

λ‚΄μž₯ μ˜ˆμ™Έ — Python 3.10.7 λ¬Έμ„œ

λ‚΄μž₯ μ˜ˆμ™Έ νŒŒμ΄μ¬μ—μ„œ, λͺ¨λ“  μ˜ˆμ™ΈλŠ” BaseException μ—μ„œ νŒŒμƒλœ 클래슀의 μΈμŠ€ν„΄μŠ€μ—¬μ•Ό ν•©λ‹ˆλ‹€. νŠΉμ • 클래슀λ₯Ό μ–ΈκΈ‰ν•˜λŠ” except μ ˆμ„ κ°–λŠ” try λ¬Έμ—μ„œ, κ·Έ μ ˆμ€ κ·Έ ν΄λž˜μŠ€μ—μ„œ νŒŒμƒλœ λͺ¨λ“  μ˜ˆμ™Έ 클래슀

docs.python.org

 

 

4. μ—¬λŸ¬κ°œμ˜ 였λ₯˜μ²˜λ¦¬ν•˜κΈ°

 

try:
    ...
except λ°œμƒ 였λ₯˜1:
   ... 
except λ°œμƒ 였λ₯˜2:
   ...

μ΄λŸ°μ‹μœΌλ‘œ μ—¬λŸ¬κ°œλ₯Ό 적을 수 μžˆλ‹€!

예λ₯Ό λ“€λ©΄ 

 

try:
    a = [1,2]
    print(a[3])
    4/0
except ZeroDivisionError:
    print("0으둜 λ‚˜λˆŒ 수 μ—†μŠ΅λ‹ˆλ‹€.")
except IndexError:
    print("인덱싱 ν•  수 μ—†μŠ΅λ‹ˆλ‹€.")

 

μ΄λ ‡κ²Œ!!!

while True:
    number = input()

    #μ‹ ν…μŠ€ μ—λŸ¬λŠ” 문법적 였λ₯˜λΌ μ˜ˆμ™Έμ²˜λ¦¬κ°€ λΆˆκ°€λŠ₯함
    try:
        number = int(number)
        print(10/number)
    except ValueError: # int둜 λ³€ν™˜ν•˜λŠ” κ³Όμ •μ—μ„œ μ—λŸ¬κ°€ λ°œμƒν–ˆμ„ λ•Œ
        print(f"{number}은(λŠ”) μˆ«μžκ°€ μ•„λ‹™λ‹ˆλ‹€.")

    except ZeroDivisionError: # 0으둜 λ‚˜λˆ„λ©΄μ„œ μ—λŸ¬κ°€ λ°œμƒν–ˆμ„ λ•Œ
        print("0으둜 λ‚˜λˆŒ 수 μ—†μŠ΅λ‹ˆλ‹€")

    except Exception as e: # μœ„μ—μ„œ μ •μ˜ν•˜μ§€ μ•Šμ€ μ—λŸ¬κ°€ λ°œμƒν–ˆμ„ λ•Œ(ꢌμž₯ν•˜μ§€ μ•ŠμŒ -> 파이썬 pep에 λ‚˜μ™€μžˆλ‹€!)
        print(f"μ˜ˆμƒν•˜μ§€ λͺ»ν•œ μ—λŸ¬κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. error: {e}")
# except 문법 λ˜ν•œ if / elif 와 같이 μ—°λ‹¬μ•„μ„œ μž‘μ„±ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

 

였λ₯˜κ°€ λ°œμƒν–ˆμ„ λ•Œ 아무것도 μ•ˆν•˜κ³  λ„˜μ–΄κ°€λ €λ©΄ passλ₯Ό μ‚¬μš©ν•˜λ©΄ λœλ‹€! return도 κ°€λŠ₯!

number = input()

try:
    number = int(number)
    print(10/number)
    
except:
    pass

 


좕약식(comprehension)

좕약식은 κΈ΄ μ½”λ“œλ₯Ό κ°„λž΅ν•˜κ²Œ μ€„μΌμˆ˜ μžˆλ‹€λŠ” μž₯점이 μžˆμ§€λ§Œ, λ‚¨μš©ν•  경우 가독성이
λ–¨μ–΄μ§€κ³  μΆ”ν›„ μ½”λ“œ 관리가 νž˜λ“€μˆ˜ 있기 λ•Œλ¬Έμ— ν•„μš”ν•  λ•Œλ§Œ μ‚¬μš©ν•˜λŠ” 것을 ꢌμž₯ν•©λ‹ˆλ‹€.

list, set, tuple, dict μžλ£Œν˜•μ΄ 좕약식을 μ§€μ›ν•©λ‹ˆλ‹€.

기본적인 κ΅¬μ‘°λŠ” λ˜‘κ°™μœΌλ©°, μ–΄λ–€ κ΄„ν˜Έ 기호λ₯Ό μ‚¬μš©ν•˜λŠ”μ§€ / μ–΄λ–€ ν˜•νƒœλ‘œ μ‚¬μš©ν•˜λŠ”μ§€μ—
따라 μ €μž₯λ˜λŠ” μžλ£Œν˜•μ΄ λ‹¬λΌμ§‘λ‹ˆλ‹€.

좕약식은 λͺ¨λ‘ λ™μΌν•œ ꡬ쑰λ₯Ό κ°€μ§€κ³  있기 λ•Œλ¬Έμ— ν•œ κ°€μ§€ μžλ£Œν˜•μ— μ΅μˆ™ν•΄μ§€λ©΄ λ‹€λ₯Έ
μžλ£Œν˜•μ—λ„ μ μš©ν•΄μ„œ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

κ·Έλ ‡λ‹€κ³  ν•œλ‹€!

가독성이 λ–¨μ–΄μ§ˆ 수 μžˆλ‹€κ³ ν•˜λŠ”λ° κ·ΈλŸ΄λ§Œν•˜λ‹€ μ²˜μŒμ— λ³΄λ‹ˆκΉŒ 이게 λ­”κ°€ μ‹Άμ—ˆλ‹€

μ–΄λ €μš΄ μ½”λ“œλ₯Ό μž‘μ„±ν• λ•ŒλŠ” μ‚¬μš© μ•ˆν•˜λŠ”κ²Œ μ’‹λ‹€!

 

 

# 기본적인 ν™œμš© 방법
# [list에 λ‹΄κΈΈ κ°’ for μš”μ†Œ in 리슀트]
numbers = [x for x in range(5)] # [0, 1, 2, 3, 4]
number = [2 for _ in range(5)] # [2, 2, 2, 2, 2]

# 쑰건문은 좕약식 뒷뢀뢄에 μž‘μ„±ν•˜λ©°, 좕약식이 True인 경우 list에 값이 λ‹΄κΈ΄λ‹€.
even_numbers = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]

 

리슀트 좕약식과 for 문을 λΉ„κ΅ν•΄λ³΄μž!

people = [
    ("lee", 32),
    ("kim", 23),
    ("park", 27),
    ("hong", 29),
    ("kang", 26)
]

####
sum_age = 0
for i in people:
	sum_age += i[1]
average_age = sum_age / len(people)
print(average_age) # 27.4

####
ages = [x[1] for x in people]
sum_ages = sum(ages)
average_age = sum_ages / len(people)
print(average_age) # 27.4

####
average_age = sum([x[1] for x in people]) / len(people)
print(average_age) # 27.4


#list μΆ•μ•½μ‹μ˜ []λ₯Ό ()ν˜Ήμ€ {}둜 λ°”κΏ”μ£Όλ©΄ tuple, set 좕약식을 μ‚¬μš©ν• μˆ˜ μžˆλ‹€!

 


lambda / map / filter / sort

 

1. lambda

 

lambda λ§€κ°œλ³€μˆ˜ : ν‘œν˜„μ‹

lambda x, y : x + y

λžŒλ‹€ν•¨μˆ˜μ˜ 기본ꡬ쑰와 μ˜ˆμ‹œμ΄λ‹€

 

pythonμ—μ„œ lambda ν•¨μˆ˜λŠ” λ‹€λ₯Έ 말둜 읡λͺ… ν•¨μˆ˜(anonymous function)라고도 λΆˆλ¦¬λŠ”λ°
lambda ν•¨μˆ˜λŠ” 주둜 map / filter / sort ν•¨μˆ˜μ™€ ν•¨κ»˜ μ‚¬μš©λœλ‹€.

λ‹¨λ…μœΌλ‘œλŠ” 잘 μ‚¬μš©λ˜μ§€ μ•ŠλŠ”λ‹€!

 

 

2. map

 

map(ν•¨μˆ˜, 리슀트)

 

 

map ν•¨μˆ˜λŠ” ν•¨μˆ˜μ™€ 리슀트λ₯Ό 인자둜 λ°›μ•„μ„œ λ¦¬μŠ€νŠΈλ‘œλΆ€ν„° μ›μ†Œλ₯Ό ν•˜λ‚˜μ”© κΊΌλ‚΄μ„œ ν•¨μˆ˜λ₯Ό μ μš©μ‹œμΌœμ€€λ‹€μŒ

μƒˆλ‘œμš΄ ν•¨μˆ˜μ— λ‹΄μ•„μ€€λ‹€!

 

numbers = [1, 2, 3, 4]
double_numbers = list(map(lambda x: x*2, numbers))
print(double_numbers) # [2, 4, 6, 8]

 

μ΄λŸ°μ‹μœΌλ‘œ!

 

map을 μ‚¬μš©ν• λ•Œμ™€ μ‚¬μš©ν•˜μ§€ μ•Šμ„λ•Œλ₯Ό λΉ„κ΅ν•΄λ³΄μž

# map
string_numbers = ["1", "2", "3"]
integer_numbers = list(map(int, string_numbers))
print(integer_numbers) # [1, 2, 3]

# for
string_numbers = ["1", "2", "3"]
integer_numbers = []
for i in string_numbers:
    integer_numbers.append(int(i))
print(integer_numbers) # [1, 2, 3]

# list 좕약식
string_numbers = ["1", "2", "3"]
integer_numbers = [int(x) for x in string_numbers]
print(integer_numbers) # [1, 2, 3]

 

λ°±μ€€ μ•Œκ³ λ¦¬μ¦˜ ν’€λ•Œ 

a, b, c = map( int, input().split() ) 이런 ꡬ쑰 정말 많이 μ‚¬μš©ν–ˆμ—ˆλ‹€!

 

 

3. filter

 

λ¦¬μŠ€νŠΈμ— λ“€μ–΄μžˆλŠ” μ›μ†Œλ“€μ„ ν•¨μˆ˜μ— μ μš©μ‹œν‚€κ³  κ²°κ³Όκ°€ 참인 κ°’λ“€λ‘œ μƒˆλ‘œμš΄ 리슀트λ₯Ό λ§Œλ“€μ–΄μ€€λ‹€!

# filter ν•¨μˆ˜λŠ” mapκ³Ό μœ μ‚¬ν•œ ꡬ쑰λ₯Ό κ°€μ§€κ³  있으며, 쑰건이 참인 경우 μ €μž₯ν•©λ‹ˆλ‹€.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]

even_numbers = list(filter(lambda x: x%2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8]

# filter ν•¨μˆ˜ λ˜ν•œ list μΆ•μ•½μ‹μœΌλ‘œ λ™μΌν•œ κΈ°λŠ₯을 κ΅¬ν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]

even_numbers = [x for x in numbers if x%2 == 0]
print(even_numbers) # [2, 4, 6, 8]

 

 

4. sort

# sort ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜λ©΄ listλ₯Ό μˆœμ„œλŒ€λ‘œ μ •λ ¬ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
numbers = [5, 3, 2, 4, 6, 1]
numbers.sort()
print(numbers) # [1, 2, 3, 4, 5, 6]

# sort와 lambda ν•¨μˆ˜λ₯Ό 같이 μ‚¬μš©ν•˜λ©΄ λ³΅μž‘ν•œ ꡬ쑰의 list도 μ •λ ¬ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
people = [
    ("lee", 32),
    ("kim", 23),
    ("park", 27),
    ("hong", 29),
    ("kang", 26)
]

# λ‚˜μ΄ 순으둜 μ •λ ¬ν•˜κΈ°
people.sort(key=lambda x: x[1])
print(people)

# result print
"""
[
    ("kim", 23),
    ("kang", 26),
    ("park", 27),
    ("hong", 29),
    ("lee", 32)
]
"""

 

 

 

 


stacktrace

 

stacktraceλŠ” python 뿐만이 μ•„λ‹Œ λŒ€λΆ€λΆ„μ˜ 개발 μ–Έμ–΄μ—μ„œ μ‚¬μš©λ˜λŠ” κ°œλ…μž…λ‹ˆλ‹€.

μ—λŸ¬κ°€ λ°œμƒν–ˆμ„ λ•Œ μ—λŸ¬κ°€ λ°œμƒ ν•œ μœ„μΉ˜λ₯Ό μ°Ύμ•„λ‚΄κΈ° μœ„ν•΄ 호좜 된 ν•¨μˆ˜μ˜ λͺ©λ‘μ„ 보여주고
κ°œλ°œμžλŠ” stacktraceλ₯Ό 따라가며 μ—λŸ¬κ°€ λ°œμƒν•œ μœ„μΉ˜λ₯Ό 좔적할 수 μžˆμŠ΅λ‹ˆλ‹€.

 

μ–΄λ””μ„œ λ°œμƒν•œ μ—λŸ¬μΈμ§€ 찾을 수 μžˆλ‹€!

μ—λŸ¬κ°€ μ™œ μ–΄λ–»κ²Œ λ°œμƒλλŠ”μ§€ μ’€ 더 μ§κ΄€μ μœΌλ‘œ 확인할 수 μžˆλ‹€!

 

 

728x90

λŒ“κΈ€