Essential Tips for Self-Taught Python Programmers: Bad Habits to Change

As a self-taught Python programmer, do you often find yourself writing code and feeling that something is off, but you can’t quite put your finger on it? It might be due to some bad habits holding you back! Today, let’s discuss the bad habits in Python that you should change to help you write cleaner code.

1. Stop Manually Concatenating Strings

Bad Habit:

name = "Alice"
greeting = "Hello, " + name + "!"

Good Habit:

name = "Alice"
greeting = f"Hello, {name}!"

Why Change: Using + to concatenate strings not only looks messy but can also lead to errors in complex scenarios. F-strings are much clearer and cleaner!

2. Let the “Automatic Manager” Handle File Closing

Bad Habit:

file = open("example.txt", "r")
content = file.read()
file.close()

Good Habit:

with open("example.txt", "r") as file:
    content = file.read()

Why Change: Manually closing files can easily be forgotten! Using the with statement ensures that the file is automatically closed after the block is executed, even if an error occurs, providing peace of mind.

3. Don’t Catch All Exceptions

Bad Habit:

try:
    result = 10 / 0
except:
    print("Error occurred")

Good Habit:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error occurred")

Why Change: A bare except will catch all exceptions, including system-level ones, which can obscure real errors and make debugging difficult. Specifying the exception type allows for precise problem-solving.

4. Avoid Using Mutable Objects as Default Parameters

Bad Habit:

def add_item(item, items=[]):
    items.append(item)
    return items

Good Habit:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Why Change: Default parameters are evaluated at the time of function definition. If you use a mutable object like a list as a default parameter, it will be shared across multiple calls, leading to unexpected results. Using None as a default ensures a new list is created each time.

5. Use List Comprehensions for Cleaner Code

Bad Habit:

squares = []
for i in range(5):
    squares.append(i ** 2)

Good Habit:

squares = [i ** 2 for i in range(5)]

Why Change: List comprehensions condense the loop and list creation into a single line, making the code more concise and easier to read.

6. Use isinstance for Type Checking

Bad Habit:

value = 42
if type(value) is int:
    print("It's an integer")

Good Habit:

value = 42
if isinstance(value, int):
    print("It's an integer")

Why Change: The type function does not handle class inheritance, while isinstance is more flexible and can correctly identify subclass objects.

7. Use is for Checking None, True, and False

Bad Habit:

if x == None:
    print("x is None")

Good Habit:

if x is None:
    print("x is None")

Why Change: None, True, and False are singleton objects in Python, and using is compares object identity, which is more accurate. Additionally, the object’s __eq__ method may be overridden, making == unreliable.

8. Simplify Condition Checks

Bad Habit:

my_list = [1, 2, 3]
if len(my_list) != 0:
    print("List is not empty")

Good Habit:

my_list = [1, 2, 3]
if my_list:
    print("List is not empty")

Why Change: Using the list itself as a condition is more readable and avoids the need to explicitly check the length.

9. Use enumerate for Iteration

Bad Habit:

my_list = ['apple', 'banana', 'orange']
for i in range(len(my_list)):
    item = my_list[i]
    print(i, item)

Good Habit:

my_list = ['apple', 'banana', 'orange']
for i, item in enumerate(my_list):
    print(i, item)

Why Change: The enumerate function allows you to get both the index and the value during iteration, saving you the hassle of manually retrieving the index.

10. Use the items Method for Dictionary Traversal

Bad Habit:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
    print(key, my_dict[key])

Good Habit:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(key, value)

Why Change: The items method allows you to directly access both keys and values without needing to look up the value in the dictionary, making it more straightforward.

11. Use Tuple Unpacking for Simplicity and Efficiency

Bad Habit:

coordinates = (3, 5)
x = coordinates[0]
y = coordinates[1]

Good Habit:

coordinates = (3, 5)
x, y = coordinates

Why Change: Tuple unpacking allows you to assign multiple values to variables at once, making the code cleaner and easier to read.

12. Use perf_counter for Timing Code

Bad Habit:

start_time = time.time()
# Code to time
end_time = time.time()

Good Habit:

start_time = time.perf_counter()
# Code to time
end_time = time.perf_counter()

Why Change: perf_counter provides higher precision for timing, making it suitable for measuring the execution time of small code segments, while time may not be accurate for short intervals.

13. Use Logging Instead of Print in Production

Bad Habit:

result = calculate_result()
print("Result:", result)

Good Habit:

import logging
result = calculate_result()
logging.info("Result: %s", result)

Why Change: Print is only useful for debugging; in production, use logging, which allows for different levels and various configuration options, making it much more convenient.

14. Avoid “Import All” for Modules

Bad Habit:

from module import *

Good Habit:

from module import specific_function_or_class

Why Change: Importing everything can lead to naming conflicts and complicate code maintenance. Importing only the specific functions or classes you need makes it clearer.

15. Use Raw Strings for Path Handling

Bad Habit:

regular_string = "C:\Documents\file.txt"

Good Habit:

raw_string = r"C:\Documents\file.txt"

Why Change: Raw strings do not treat backslashes as escape characters, improving readability when handling paths and regular expressions.

16. Follow PEP8 for Code Style

Bad Habit:

aVar=5
result=aVar+2

Good Habit:

a_var = 5
result = a_var + 2

Why Change: PEP8 is the official style guide for Python code. Following it ensures a consistent code style, making it easier to read and collaborate with others.

So, how many of these bad Python habits do you have? It’s time to change them and elevate your code quality!

Leave a Comment