7 Common Python Beginner Mistakes. What Should You Not Do?
--
There are common Python mistakes that beginner developers make. In this tutorial we will cover a few so you know what not to do in your code.
Common Python mistakes when you are getting started with coding are: not using the correct indentation, forgetting colons at the end of certain lines of code, using variables before assigning a value to them. Other examples of errors are trying to change immutable objects and trying to modify a list while iterating through it.
These are some of the errors I will explain in this tutorial (and not only).
So, let’s begin!
1. Is Correct Indentation Always Required in Python?
Correct indentation is a must in Python. Incorrect indentation in a Python program represents a syntax error.
You might not be used to it if you come from a different programming language that doesn’t enforce indentation in the same way Python does.
Let’s take, for example, the following code:
for i in range(10):
print("The next number is", i)
The Python interpreter will throw an exception because the print statement inside the for loop has to be indented.
File "python_common_mistakes.py", line 2
print("The next number is", i)
^
IndentationError: expected an indented block
Wait…
But we said that an indentation error is a syntax error.
We can confirm that the exception type IndentationError is a subclass of SyntaxError (it’s basically a type of syntax error).
We will use the issubclass() built-in function:
>>> issubclass(IndentationError, SyntaxError)
True
The Python interpreter returns a boolean with value True that confirms that IndentationError is a type of SyntaxError.
To fix this error indent the print statement (this is something that Python IDEs will help you with).
for i in range(10):
print("The next number is", i)[output]
The next number is 0
The next number is 1
The next number is 2
The next number is 3
The…