Assert Statements in Python
Asserts and Exceptions
Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen.
Assertions
assert
is a keyword in Python
Syntax:If condition is
False
raiseAssertError
exception
- Assertions can be disabled at runtime using parameters, and are disabled by default, so don’t count on them except for debugging purposes.
- Using -O ( O is for Optimized)
- Assertions are used for debugging purposes only.
type()
vs.isinstance()
Note
In this class, we will use
assert
,type()
,isinstance()
to validate function parametersThis is not recommended in production code.
callable()
Check if something is a function
all()
The
all()
function returnsTrue
if all items in an iterable are true, otherwise it returnsFalse
.
any()
The
any()
function returnsTrue
if at least one item in the iterable is true, otherwise it returnsFalse
.
Can't check for integers in list before checking if it is actually a list
Realistic example of assert
General rules
Don’t use asserts for data validation
- can be disabled
- homeworks: for grading/learning purposes
Asserts that never fail
Strings
Representing data
Representing language
Representing program
Escape characters
\a
Bell escape characterMakes noise?
Originated to alert programmers when their programs finished
String operations
str * int
:str
writtenint
times
str[int]
: character atint
index ofstr
str[int:int]
: substring fromint
index toint
index
Slicing
str[int:int:int]
Can omit indices, use negative indices, specify step
String modification
str[16] = ""
‘str’ item does not support item assignment (immutable)
str = str[:16] + " " + str[17:]
str.replace()