- assert
If a condition in your code returns True, if not, the program will raise an AssertionError.
def cal(nums):
assert len(nums)>0, "list must not be empty"
total=sum(nums)
avg=total/len(nums)
return avg
data=[5, 10, 15, 20]
result=cal(data)
result
>>>
12.5
You can write a message to be written if the code returns False.
def cal(nums):
assert len(nums)>0, "list must not be empty"
total=sum(nums)
avg=total/len(nums)
return avg
data=[]
result=cal(data)
result
>>>
AssertionError Traceback (most recent call last)
/var/folders/x2/28kczyld7b702fsq79qmmgcm0000gn/T/ipykernel_33502/3200075429.py in <module>
6
7 data=[]
----> 8 result=cal(data)
9 result
/var/folders/x2/28kczyld7b702fsq79qmmgcm0000gn/T/ipykernel_33502/3200075429.py in cal(nums)
1 def cal(nums):
----> 2 assert len(nums)>0, "list must not be empty"
3 total=sum(nums)
4 avg=total/len(nums)
5 return avg
AssertionError: list must not be empty
'Basic Python' 카테고리의 다른 글
pickle, dump, load (0) | 2023.10.24 |
---|---|
sys.path, getcwd (0) | 2023.10.19 |
return vs yield, yield vs yield from (0) | 2022.11.30 |
lambda (0) | 2022.11.29 |
vars (0) | 2022.08.25 |