반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Python
- array
- gas
- Google Spreadsheet
- Google Excel
- 파이썬
- matplotlib
- numpy
- django
- Java
- list
- Tkinter
- SQL
- PySpark
- google apps script
- Mac
- string
- hive
- dataframe
- GIT
- PostgreSQL
- math
- Kotlin
- Redshift
- c#
- Github
- Excel
- PANDAS
- Apache
Archives
- Today
- Total
달나라 노트
Python Basic : assert (True, False 확인하고 False인 경우 코드 중단하기) 본문
Python/Python Basic
Python Basic : assert (True, False 확인하고 False인 경우 코드 중단하기)
CosmosProject 2020. 11. 23. 18:37728x90
반응형
assert
assert 조건식, message
assert는 위처럼 사용할 수 있습니다.
뒤에 나오는 조건식의 결과가 False라면 AssertError를 반환시시키고 코드를 중단합니다.
AssertError가 발생할 때 콤마(,)로 구분된 message가 같이 출력됩니다. 이 message는 생략할 수 있습니다.
assert는 python 코드를 진행하다가 어떤 조건이 맞는지 체크하기 위해 사용할 수 있습니다.
사실 일반적인 if 문을 이용해서 위와 같은 기능을 구현할 수도 있지만 assert를 사용하면 좀 더 간단해질 수 있다는 장점이 있기도 하죠.
아래 예시를 봅시다.
print('Start line')
a = 1
assert a == 1
print('End line')
- Output
Start line
End line
a에 1을 할당했고 assert의 조건으로서 a == 1을 주었으니 이는 True가 됩니다.
따라서 assert는 어떠한 Error도 발생시키지 않으며, End line 텍스트가 잘 출력됩니다.
아래 예시는 assert가 에러를 일으키는 경우입니다.
print('Start line')
a = 1
assert a == 2
print('End line')
- Output
Start line
Traceback (most recent call last):
File "/Users/Documents/GUIDE/tistory_test/python_assert.py", line 4, in <module>
assert a == 2
AssertionError
a에 1을 할당했고 assert의 조건으로서 a == 2을 주었으니 이는 False가 됩니다.
따라서 assert는 AssertionError를 발생시키며, 코드가 중단되어 End line 텍스트가 출력되지 않습니다.
print('Start line')
a = 1
assert a == 2, 'Different number'
print('End line')
- Output
Start line
Traceback (most recent call last):
File "/Users/Documents/GUIDE/tistory_test/python_assert.py", line 4, in <module>
assert a == 2
AssertionError: Different number
위 예시는 assert 구문에 message를 추가했습니다.
그래서 결과를 보면 AssertionError 부분에 Different number라는 제가 적어준 message가 같이 출력되는걸 볼 수 있죠.
728x90
반응형
'Python > Python Basic' 카테고리의 다른 글
Python Basic : enumerate() (0) | 2020.12.09 |
---|---|
Python Basic : class 상속과 super() (0) | 2020.11.29 |
Python Basic : set.intersection (set 교집합 구하기) (2) | 2020.11.23 |
Python Basic : set.union (set 합집합 구하기) (0) | 2020.11.23 |
Python Basic : break, pass, continue (0) | 2020.11.18 |
Comments