In Python, there are (at least) two kinds of errors: syntax errors and exceptions.
A syntax error, also known as a parsing error, is when your code does not follow rules for writing Python code. Python interpreter shows an error message when it encounters a syntax error.
The code below has a syntax error because it breaks the Python rule that requires a :
to follow the condition of an if
statement.
| → |
|
Some Python editors (e.g., repl.it) flag syntax errors even before you run the code.
Note how replt.it Python editor points out the syntax error using a red ❌ in the of the editor.
Errors detected during execution are called exceptions. Even if the code is syntactically correct, it may cause an error during execution. Python different types of exceptions; the type of exception used depends on the tye nature of the error.
The code below raises an exception when it attempts to divide a number by 0
. The type of the exception raised is ZeroDivisionError
, as mentioned in the last line of the error message.
| → |
|
It is not desirable for programs to 'crash' every time an exception occurs. You can use the try-except
syntax to specify how to handle exceptions. The try
clause contains the code that can possibly raise an exception while the except
clause contains the code that handles the exception.
The code below specifies what to do if the ZeroDivisionError
is raised, thereby avoiding a program crash in such an event.
| → |
|
When the code in a try
clause raises an error, the program execution immediately moves to the code in the except
clause, provided the exception that happened matches the exception the except
clause is supposed to . After running the code in the except
clause, the execution continues as normal.
If the exception does not match the except
clause, the program crashes.
The code below crashes because the actual exception (caused by passing a string when an floating point number is expected) does not match the specified exception ZeroDivisionError
.
| → |
|
You can specify multiple except
clauses, one for each type of exception expected.
The code below handles two types of exceptions: ZeroDivisionError
and ValueError
.
The ValueError
is raised when the string abc
is being converted to a float using float(divisor)
.
| → |
|
It is possible to specify multiple exception types in one except
clause.
The code below handles both ZeroDivisionError
and ValueError
in the same except
clause.
| → |
|
IndexError
is an exception thrown when you try to access an index (e.g., when reading values form a list) that does not exist.
In this example, calling get_head
on an empty list causes an IndexError
.
| → |
|
It is also possible to use except Exception
to catch any kind of exception. However, that practice is discouraged.
The code below handles both ZeroDivisionError
and ValueError
and any other exception in the same except
clause.
| → |
|
📎 Resources:
You can raise
an exception yourself to indicate an error.
The get_body(items)
function below raises an exception when it receives a list that has fewer than 3 items. That exception is 'caught' and handled by the hide_ends(items)
function.
Also note how an except
clause can assign a name to the exception using as temporary_name
(as done by except ValueError as e:
) so that the exception object can be referenced later (as done in print('Cannot hide ends', str(e))
)
| → |
|
It is also possible to catch an exception, do something, and then raise it again so that the exception propagates to the caller.
The code hide_ends2(items)
function below catches the ValueError
exception, prints an error message, and raises it again so that the code that called the function can catch the exception again. Also note how the line hide_ends2([0, 1, 2, 3, 4])
is never executed due to the exception raised by the line just above it.
| → |
|
Here are some commonly used built-in exceptions (full list) you can raise/handle in your code:
IndexError
: Indicates an index of a sequence (e.g., a list) is out of range.RuntimeError
: Indicates an error that does not fall under any other category.ValueError
: Indicates when a function gets argument of correct type but improper value.ZeroDivisionError
: Indicates an attempt to divide by zero.It is also possible to define your own user-defined exceptions but that requires more advanced programming techniques. It will be covered elsewhere.
A can normally be specified by enclosing it within a pair of ''
or a pair of ""
e.g., 'How is life?'
. However, this will not work if the string has a in it e.g., 'How's life?'
is not acceptable to Python because it contains a '
which has the special meaning 'end of string', confusing Python as to which '
of the string literal indicates the end of the string. This is similarly confusing: "Say "wow""
.
An escape sequence is a sequence of characters in a string literal that is taken together and interpreted in a special way. You can use an escape sequence to include a special character in a string literal without interpreting it as a special character. Given below are some examples:
Escape Sequence | Meaning | Example | Output |
---|---|---|---|
\' | single quote | print('How\'s Life') | How's Life? |
\" | double quote | print("Say \"wow\"") | Say "wow" |
\\ | back slash | print('files\\text') | files\text |
Another use of escape sequences is to give a special meaning to a character that normally does not have a special meaning. Here are some examples:
Escape Sequence | Meaning | Example | Output |
---|---|---|---|
\t | horizontal tab | print('aaa\tbbb') | aaa bbb |
\n | line break | print('hi\nthere!') | hi there! |
You can use a pair of triple quotes to indicate a multi-line string literal.
Here is an example multi-line string that uses triple quotes.
| → |
|
def get_email_body():
body = '''This is the first line of the email.
This is the second line.
This is the third line.
- bye!'''
return body
print(get_email_body())
This is the first line of the email.
This is the second line.
This is the third line.
- bye!
It is optional to escape '
and "
inside a mult-line string within triple quotes e.g., How's life?
in the example above.
Triple double-quotes ("""
) are commonly used to show documentation of code. Such comments are called docstrings.
The remove_head(items)
function below has a docstring that explains its behavior.
def remove_head(items):
"""Remove the first item of the items.
The list should have at least one item.
Arguments:
items -- (type: list) the list of items to be modified
"""
print('removing head of list ', items)
del items[0]
📎 Vist this page to learn more about docstrings
As you have seen before, you can use +
and *
operators to concatenate and replicate strings
e.g., 'abc' + '!'*5
evaluates to 'abc!!!!!'
.
You can use indexes and slices to access characters of a string, just like if a string is a simply a list of characters.
i.e., 'Hi there'
is same as a list:
H | i | t | h | e | r | e | ! | |
---|---|---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
The code below shows how to use index and slice notations to get parts of a string.
| → |
|
Strings are immutable. The following code will not work: s[0] = 'h'
You can use the in
and not in
operator to see if one string is a sub-string of another.
Examples of checking for the existence of a sub-string:
| → |
|
String objects have many methods (the full list is here).
Here are some string methods related to the nature of the string.
upper()
: returns a string with all characters in upper caselower()
: returns a string with all characters in lower caseisupper()
: returns True
if all characters are in upper caseislower()
: returns True
if all characters are in lower caseisalpha()
: returns True
if the string consists only of letters and is not blank.isalnum()
: returns True
if the string consists only of letters and numbers and is not blank.isdecimal()
: returns True
if the string consists only of numeric characters and is not blank.isspace()
: returns True
if the string consists only of spaces, tabs, and new-lines and is not blank.startswith(s)
: returns True
if the substring s
appears at the start of the stringendswith(s)
: returns True
if the substring s
appears at the end of the stringExamples of string methods mentioned above:
| → |
|
| → |
|
| → |
|
The find(s)
method gives index of s
in the string, if it is found. It returns -1
if s
is not found.
Examples of the find()
method:
| → |
|
The join()
method joins a list of string items while using the as a .
Examples of the join()
method:
| → |
|
The split()
method is the opposite of join()
. It splits a string into a list of strings based on a given delimiter string. If no delimiter is given, any in the string are used as delimiters.
Some examples of using the split()
method:
| → |
|
There are some string methods to help you to strip trailing/leading spaces.
Examples of stripping leading/trailing spaces from a string:
| → |
|
The replace()
method can replace a character (or a phrase) with another character/phrase.
Some examples of using replace()
method:
print('face to face'.replace(' ', '-')) # replace space with a dash
print('1,2,3,4'.replace(',', '\t')) # replace comma with a tab
print('Yup, Yup, I agree'.replace('Yup', 'Yes'))
face-to-face
1 2 3 4
Yes, Yes, I agree
There are some string methods to help you to align text.
Examples of aligning text using string methods:
| → |
|