< previous | Table of Contents | < järgmine |
3.7 COMMON ERRORS
PUNCTUATION AND INDENTATION
Commonly, missing colons cause errors. Every if
, elif
, else
statement must end with a colon :
.
Another common error with conditional statements is incorrect indentation. It can be caused by accidentally entering an extra space, nesting blocks incorrectly, etc.
# Missing colon after the if statement has_drivers_license = True if has_drivers_license print("You are eligible to drive.")
Here's what Thonny would communicate to you in case there is a colon missing at the end of the if
statement condition.
Also, remember that if you don't correctly indent your if
blocks, Python will throw an error.
# Incorrect indentation of the if-statement body has_drivers_license = True if has_drivers_license: print("You are eligible to drive.")
Here's what Thonny would communicate to you in case the indentation is incorrect.
CHECKING EQUALITY
Using an assignment operator =
instead of the equality operator ==
. It's important to use ==
to check if two values are equal or not.
x = 2.4 if x = 2: print("x is equal to two!")
Here's how this error would show in Thonny. As you can see, Thonny gives you a pretty clear hint as to what's causing the problem that you can then find in your program and quickly fix.
TYPE ERRORS
Trying to compare data types that aren't directly comparable, like string and an integer will lead to a TypeError
.
In this example, as we've forgotten to convert the string value that the input()
function takes to an integer, we will be trying to calculate the modulo of a data type string instead of type integer. Python does not supporting strings to numerical values.
integer_value = input(“Enter an integer value: “) if integer_value % 2 == 0: print("The integer entered by the user is an even number.")
Here's what you'd see in the Thonny console.
< previous | Table of Contents | < järgmine |