Table of contents
- 1. Using keywords as Variable Names
- 2. Incorrect indentation
- 3. Incorrect Data Types
- 4. Not Handling Exceptions
- 5. Mutable vs Immutable Data Types
- 6. Mistakes when using slicing and indexing
- 7. Variable Scope
- 8. Spelling Mistakes when using keywords
- 9. Confusing Built-in Methods
- 10. Difference between == and is
- Conclusion
This story was originally posted on realpythonproject.com
Python is a popular and powerful programming language, but it can be easy for beginners to make mistakes when they are first learning the language. Read along to know more about some Common mistakes Python Developers make and how to avoid them
1. Using keywords as Variable Names
This can cause confusion and errors in your code. To avoid this mistake, make sure to use descriptive and unique variable names that do not conflict with Python keywords or built-in functions. For example, instead of using the variable name "list" for a list, you could use a name like "my_list" to avoid confusion:
# I want to create a new list variable
# Incorrect
list = [1, 2, 3]
# Correct
my_list = [1, 2, 3]
2. Incorrect indentation
In Python, indentation is used to define code blocks, such as loops and conditional statements. If your indentation is incorrect, your code will not work as expected. To avoid this mistake, make sure to use consistent indentation throughout your code and always use the correct amount of indentation for each code block. For example, the code below will not work because the indentation for the "if" statement is incorrect:
# I want to print two statements only if `x` > 0
# Incorrect
if x > 0:
print("x is positive")
print("this line will always be printed irrespective of whether x>0")
# Correct
if x > 0:
print("x is positive")
print("this line will only be printed when x>0")
3. Incorrect Data Types
If you use the wrong data type for a variable, your code may not work as expected. To avoid this mistake, make sure to use the correct data types for your variables and check their values before using them in your code. For example, the code below will not work because the variable "my_number" is assigned a string value instead of an integer:
# Incorrect
my_number = "42"
print(my_number + 1) # this will cause an error
# Correct
my_number = 42
print(my_number + 1) # this will work as expected
4. Not Handling Exceptions
Exceptions are errors that occur when your code is executed, and they can cause your program to crash if they are not handled properly. To avoid this mistake, make sure to use try-except blocks to catch exceptions and handle them gracefully, rather than letting them crash your program. For example, the code below will not work because it does not handle the "ZeroDivisionError" exception that may occur when the variable "x" is zero:
# Incorrect
x = 0
print(1 / x) # this will cause an error
# Correct
try:
x = 0
print(1 / x)
except ZeroDivisionError:
print("Cannot divide by zero")
Avoid Pokemon Exception Handling
5. Mutable vs Immutable Data Types
In Python, some data types, such as lists and dictionaries, are mutable, which means that their values can be changed after they are created. Other data types, such as strings and tuples, are immutable, which means that their values cannot be changed. If you try to modify an immutable data type, you will get an error. To avoid this mistake, make sure to understand the difference between mutable and immutable data types and use the appropriate data type for your needs. For example, the code below will not work because strings are immutable and you cannot change their values:
# Incorrect
my_string = "hello"
my_string[0] = "H" # this will cause an error
# Correct
my_string = "hello"
my_string = "Hello" # this will work as expected
6. Mistakes when using slicing and indexing
In Python, you can use the square bracket notation to slice and index sequences, such as strings, lists, and tuples. If you use the wrong syntax for slicing or indexing, your code will not work as expected. To avoid this mistake, make sure to carefully read the documentation and examples for slicing and indexing, and always use the correct syntax when working with sequences in your code. For example, the code below will not work because the slicing syntax is incorrect:
# I want to print the last 4 elements
# Incorrect
my_list = [1, 2, 3, 4, 5]
print(my_list[1::5]) # this will return [2]
# Correct
my_list = [1, 2, 3, 4, 5]
print(my_list[1:5]) # this will work as expected
print(my_list[1:5:]) # this will work as expected
7. Variable Scope
In Python, the scope of a variable refers to the parts of your code where the variable is visible and can be accessed. If you try to access a variable outside of its scope, you will get an error. To avoid this mistake, make sure to understand the scope of your variables and only access them within their defined scope. For example, the code below will not work because the variable "x" is defined inside the "foo" function and cannot be accessed outside of it:
# Incorrect
def foo():
x = 42
print(x) # this will cause an error
# Correct
def foo():
x = 42
return x
print(foo()) # this will work as expected
8. Spelling Mistakes when using keywords
In Python, you can define your own functions to organize and reuse your code. If you use the wrong syntax for defining a function, your code will not work as expected. To avoid this mistake, make sure to carefully read the documentation and examples for defining functions, and always use the correct syntax when creating your own functions. For example, the code below will not work because the "def" keyword is misspelled and the function signature is incorrect:
# Incorrect
de foo(x, y):
return x + y
print(foo(1, 2)) # this will cause an error
# Correct
def foo(x, y):
return x + y
print(foo(1, 2)) # this will work as expected
In Python, you can import modules to use their functions and objects in your code. If you use the wrong syntax for importing a module, your code will not work as expected. To avoid this mistake, make sure to carefully read the documentation and examples for importing modules, and always use the correct syntax when importing modules in your code. For example, the code below will not work because the "import" keyword is misspelled:
# Incorrect
imort math
# Correct
import math
These are just a couple of many possible examples. I highly recommend using an IDE to write Python. Most IDEs will have support for Python Linting/Validation that will help you avoid such errors.
9. Confusing Built-in Methods
Python has a rich standard library that includes many built-in functions and methods that can help you accomplish common tasks. If you use the wrong methods or functions for a task, your code may not work as expected. To avoid this mistake, make sure to familiarize yourself with the available methods and functions in the Python standard library and use the right ones for the task at hand. For example, the code below will not work because the "sort" method is used to sort a string, which is not possible:
# Incorrect
my_string = "hello"
my_string.sort() # this will cause an error
# Correct
my_string = "hello"
my_list = list(my_string)
my_list.sort()
my_string = "".join(my_list)
print(my_string) # this will work as expected
10. Difference between == and is
In Python, there are two operators for comparison: "==" and "is". The "==" operator checks if the values of two operands are equal, while the "is" operator checks if the operands are the same object. If you use the wrong operator for comparison, your code may not work as expected. To avoid this mistake, make sure to understand the difference between "==" and "is" and use the appropriate operator for your needs. For example, the code below will not work because "==" is used instead of "is" to check if two variables are the same object:
# I want to check if `x` and `y` are the same object
# Incorrect
x = [1, 2, 3]
y = [1, 2, 3]
if x == y:
print("x and y are the same object")
else:
print("x and y are not the same object")
# Correct
x = [1, 2, 3]
y = [1, 2, 3]
if x is y:
print("x and y are the same object")
else:
print("x and y are not the same object")
Conclusion
By avoiding these common mistakes, you can write more effective and efficient Python programs and avoid frustrating errors and bugs. A lot of these bugs can be avoided or easily detected with the help of the Python Linter/Validator. I personally prefer VS Code for Python development.