< previous | Table of Contents | järgmine > |
4.5 COMMON ERRORS
SYNTAX ERRORS
As with conditional statements, for functions, common syntax errors include missing colons :
and incorrect indentation. Here's a visualization of what Thonny would respond in the case of a SyntaxError
.
PARAMETER AND ARGUMENT ERRORS
Common errors in function usage include mismatches between the arguments provided and the parameters expected by the function. This can happen when a function is called with too many or too few arguments. Additionally, errors often arise from incorrectly naming parameters or arguments or providing arguments of incorrect types relative to what the function expects.
For example, if we call a function with too many arguments, we would get a TypeError
There can also be errors in calling wrong parameter names within a function or accidentally forgetting to define a parameter that you then still refer to in the function body. This would result in a NameError
You should also be make sure that there are no mismatches between the types of data that you pass in to the function for upon which operations will be conducted as this might result in unexpected behavior or errors. For example if you want to add two numbers together but end up passing them as strings, the function would concatenate the strings instead and you'd get a result you did not want. Or in other scenarios the result could also be a TypeError
as shown below.
WRONG SCOPE
Using local variables outside of their scope will result in an error. Take a look at the example in Thonny below. Here we try to use the result variable, that we define within the function, outside to print out the product of the multiplication. However, the result
variable has a local scope and is only accessible within that function. Hence, we get a NameError
.
< previous | Table of Contents | järgmine > |