Errors in Python

In this tutorial we will talk about how to fix errors in Python.

Clearly at the beginning of programming in Python some mistakes will be made, but gradually they will decrease more and more.

It is important to understand how to manage them right away.

There are therefore various types of errors:

Lexical errors in Python

Lexical errors arise from the use of terms that do not belong to the language.

Let’s take an example immediately:

>>> a = integ(input())

Traceback (most recent call last):

File “<pyshell#31>”, line 1, in <module>

a = integ(input())

NameError: name ‘integ’ is not defined

In this case the integ doesn’t belong to the language, in fact the interpreter warns that it is not defined.

Syntactic errors in Python

Syntactic errors occur in many cases:

  • For example, when language keywords are used for other purposes.
  • When you forget to close a parenthesis (, [or {.
  • If within a condition there is only one = instead of the double equal ==.
  • If a colon (:) is missing at the end of the header of each compound statement, including the for, while, if and def statements (instructions that we will study later).
  • It can happen that the delimiters of the strings are not paired correctly or that the strings do not terminate properly.
  • Indentation errors. In fact, in Python we will see that indentation is fundamental. In my opinion, this is good because it allows you to write code that is clean and easily readable by other programmers.

Some examples of syntax errors in Python

Here is an example of using for as a variable to hold an integer value. For is in fact a keyword and cannot be used as a variable.

>>>for = 15

SyntaxError: invalid syntax


Here’s another example where we forget to open a round bracket:

>>>side = int(input))

SyntaxError: invalid syntax

Logical or semantic errors in Python

In this case, the error must be found in the algorithm resolution. Certainly from a logical point of view there will be something wrong, so we need to review the possible resolution again.

In the meantime, a simple suggestion is to understand which part is not working, going step by step, so as to focus only on that.

Runtime errors in Python

Runtime errors are execution errors, that is, they occur during program execution.

It can happen when exceptions occur, or if you throw an infinite loop or recursion for example.

We will see some cases in detail below.

Conclusioni

In this lesson we have covered some examples of possible programming errors in Python

Useful links

Python tutorial

Python Compiler

Install Python

Variables

Casting in Python

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *