Avoid these common pitfalls and level up your Python skills!
👉 Like 👍 | Comment 💬 | Subscribe 🔔 for more Python tips
Indentation is crucial in Python because it defines code blocks. Unlike other languages that use curly braces {}, Python relies on spaces. You should always use 4 spaces for indentation (PEP 8).
Wrong:score = 67
if score > 50:
print('you pass') # 2 spaces (inconsistent)
score = 67
if score > 50:
print('you pass') # 4 spaces
Correct:
score = 67
if score > 50:
print('you pass') # Consistent 4 spaces
Forgetting to close files can cause issues like data not being saved or resources being locked. Using the with statement is the best practice.
f = open('dataset.txt', 'w')
f.write('new_data')
f.close()
# If an error happens before close(), the file stays open!
Correct:
with open('dataset.txt', 'w') as f:
f.write('new_data')
# Automatically closes the file, even if errors occur.
Newbies often mix up the assignment operator (=) and the comparison operator (==).
score = 67
if score = 50: # Syntax Error!
print('You passed!')
Correct:
score = 67
if score == 50: # Correct comparison
print('You passed!')
Scope defines where a variable is accessible. Variables defined inside a function are not accessible outside of it.
Wrong:def greet():
message = "Hello!"
print(message) # Error: message is not defined globally
Correct:
def greet():
message = "Hello!"
print(message) # Correct usage inside scope
Importing everything using * pollutes the namespace and can lead to conflicts. It is better to be explicit.
from math import *
print(floor(2.4))
print(pi) # Where did these come from? Unclear.
Correct:
import math
print(math.floor(2.4))
print(math.pi) # Clear and clean namespace
Handling exceptions prevents crashes and allows you to show friendly error messages.
Wrong:age = int(input("Enter your age: "))
print("Your age is:", age)
# Crashes if user enters "ten"
Correct:
try:
age = int(input("Enter your age: "))
print("Your age is:", age)
except ValueError:
print("Please enter a valid number.")
Modifying global variables inside functions can lead to bugs. It's often better to pass arguments and return values.
Wrong:count = 0
def increment():
count += 1 # UnboundLocalError
increment()
Better Practice:
def calculate_sum():
result = 0
for i in range(1, 5):
result += i
return result # Use return values instead of globals
Using + repeatedly in a loop is slow because strings are immutable. Use .join() instead.
msg = ""
for name in names:
msg += name + ", "
Correct:
# Efficient concatenation
msg = ", ".join(names)
Docstrings help others (and future you) understand what your functions do.
Wrong:def add(a, b):
return a + b
Correct:
def add(a, b):
"""Calculates the sum of two numbers."""
return a + b
Installing libraries globally causes version conflicts. Always use a virtual environment for each project.
Wrong:pip install numpy # Installing globally
Correct:
python -m venv myenv
source myenv/bin/activate
pip install numpy # Installing in isolated environment