• Legit Python
  • Posts
  • The 10 Biggest Python Mistakes Newbies Make

The 10 Biggest Python Mistakes Newbies Make

Avoid These Common Pitfalls and Level Up Your Python Skills

When I started learning Python, I was just focused on getting my code to work. I didn’t care much about the “right way” to do things. But that changed when my teacher looked at my code and said, “It works, but it’s written horribly.”

That was a wake-up call. I realized that writing good code isn’t just about making it work — it’s about writing it cleanly and efficiently.

In this post, we’ll go over 10 common Python mistakes that scream you’re a newbie. Avoiding these will help you write better, cleaner code!

Table of Contents

Mistake 1: Not Using Proper Indentation

Indentation is crucial in Python because it defines code blocks, like loops, conditionals, and functions. Unlike other languages that use curly braces {}, Python relies on spaces. If the indentation is wrong, the code can break or behave unexpectedly.

So, You should always use 4 spaces for indentation, as recommended by the official Python style guide (PEP 8). This keeps your code clean and easy to read.

Wrong:

sore = 67
if score > 50:
  print('you pass')   # 2 spaces, which is inconsistent
score = 67
if score > 50:
    print('you pass')  # 4 spaces, consistent indentation

In the above example, 2 spaces & 4 were used. This inconsistency can cause issues later, even if the code seems to work fine at first.

Correct:

score = 67
if score > 50:
    print('you pass')  # consistent 4 spaces for indentation

Mistake 2: Forgetting to Close Files

Forgetting to close files can cause issues like data not being saved or resources being locked. Closing a file ensures all data is written correctly and frees up system resources.

Wrong:

f = open('dataset.txt', 'w')
f.write('new_data')
f.close()

If an exception occurs between open() and close(), the file might not get closed.

Correct:

with open('dataset.txt', 'w') as f:
    f.write('new_data')

Using the with statement automatically closes the file, even if an error occurs. It’s best to use with to ensure files are always properly closed.

Always gif ~ tenor.com

Mistake 3: Confusing = with ==

Newbie often mixed up the = (assignment operator) and == (comparison operator). It’s an easy mistake to make, but it can lead to confusing bugs in your code.

Wrong:

score = 67
if score = 50:  # Mistakenly using = instead of ==
    print('You passed!')

Here, I tried to compare score with 50 but accidentally used =. This would cause a syntax error.

Correct:

score = 67
if score == 50:  # Correctly using ==
    print('You passed!')

Now, it correctly checks if score equals 50.

Mistake 4: Not Understanding Python's Scope & Lifetime

At Starting, I didn’t fully understand how variables work in terms of scope and lifetime. This led to unexpected behavior, like using variables outside their intended context or thinking a variable would still be available after a function ended.

  • Scope defines where a variable is accessible (e.g., inside or outside a function).

  • Lifetime is how long a variable exists in memory.

Wrong:

def greet():
    message = "Hello!"
print(message)  # Error: message is not accessible outside greet()

In this example, the message exists only inside the function greet(). Trying to access it outside results in an error.

Correct:

def greet():
    message = "Hello!"
    print(message)  # Accessing message within the function

greet()  # Correct way to use variables within their scope

Here, the variable message is used correctly within the scope of the function.

Mistake 5: Using import *

Using from something import * can be tempting for quick access to all objects in a module, but it’s not a good practice.

Here is why ⤵️:

  • If the module has many objects, importing everything can slow down your program.

  • It imports all names without clarity, leading to potential conflicts and unexpected behavior.

Wrong:

from math import *

print(floor(2.4))
print(ceil(2.4))
print(pi)

Here, I imported everything from math without knowing what exactly I was bringing in, and this can cause problems later.

Correct:

import math
from math import pi

print(math.floor(2.4))
print(math.ceil(2.4))
print(pi)

In the second example, I imported only the specific functions I needed, keeping the code clean and clear.

Mistake 6: Forgetting to Handle Exceptions

I didn’t fully understand the importance of handling exceptions early on. My program would crash whenever an error occurred. It wasn’t until I started catching and managing errors that things improved.

Handling exceptions prevents your program from crashing unexpectedly and allows you to show a helpful error message instead of abruptly halting.

Wrong:

age = int(input("Enter your age: "))
print("Your age is:", age)

If the user enters something that’s not a number, this program will crash!

Correct:

try:
    age = int(input("Enter your age: "))
    print("Your age is:", age)
except ValueError:
    print("Please enter a valid number.")

Here, I've added a try and except block to catch the error and display a friendly message instead of crashing the program. Notice that I’ve specified the exact error I expected and handled it properly in the except block.

At first, we often use a bare except block, but it’s something to avoid. While it might seem convenient to catch all errors at once, it can unintentionally capture things like SystemExit or KeyboardInterrupt, making it difficult to interrupt the program when needed.

Why is it Bad Practice?

Using a bare except without specifying the error type can hide important issues that you may want to handle differently.

Why is it Good Practice?

Specifying the type of exception you're expecting ensures that you only catch the errors you intend to handle. This helps prevent unintended errors from being silenced and makes your code easier to debug and maintain in the long run.

Mistake 7. Overusing Global Variables

Global variables can be useful, but overusing them can make your code harder to maintain. A common mistake is modifying them inside functions without using the global keyword, which can lead to confusion and bugs. It’s important to be explicit about which variables you're modifying.

Wrong:

count = 0

def increment_counter():
    count += 1  # This would create a local variable, not modify the global one

increment_counter()
print(count)  # This will raise an error because count is treated as a local variable

Correct:

count = 0

def increment_counter():
    global count  # Specify we're using the global variable
    count += 1

increment_counter()
print(count)  # 1

While this works, it's better to avoid globals when possible. A cleaner approach is to pass variables as arguments or use return values to communicate between functions.

Better Practice:

def calculate_sum():
    result = 0
    for i in range(1, 5):
        result += i
    return result

sum_result = calculate_sum()
print(sum_result)  # 10

This method avoids global variables and keeps functions clean and independent, making the code more maintainable.

Mistake 8: Using Inefficient String Concatenation

Using the + operator repeatedly inside a loop to concatenate strings can lead to poor performance. Since strings in Python are immutable, every concatenation creates a new string, leading to unnecessary memory allocation and copying.

Wrong:

names = ["Alice", "Bob", "Charlie"]
message = ""
for name in names:
    message += name + ", "
message = message[:-2]  # Remove the trailing comma and space

Correct:

# Efficient concatenation using join()
message = ", ".join(names)

By using the join() method, we can concatenate all the names in one go, which is far more efficient than using the + operator inside a loop.

Mistake 9: Neglecting Proper Documentation

Proper documentation is crucial for understanding and maintaining code. Many beginners overlook it, making it difficult for others (or even your future self) to understand the purpose and reasoning behind the code. Clear and concise documentation improves readability and maintainability.

Wrong:

def calculate_sum(a, b):
    return a + b

While this function works, there's no documentation to explain what it does, what the parameters are, or what it returns.

Correct:

def calculate_sum(a, b):
    """
    Calculates the sum of two numbers.
    
    Args:
        a (int): First number.
        b (int): Second number.
        
    Returns:
        int: The sum of `a` and `b`.
    """
    return a + b

By adding a docstring, we clearly explain the function's purpose, its arguments, and what it returns. This makes the code much easier to understand and maintain.

Mistake 10. Ignoring Virtual Environments

It’s common to see beginners installing libraries directly into the global Python environment without using a virtual environment. Ignoring virtual environments can lead to dependency issues and version conflicts across projects.

Using isolated environments for each project makes it much easier to maintain clean setups and avoid future conflicts.

Wrong:

# Installing packages globally without a virtual environment
pip install numpy

This might work, but it can create problems when you need different versions of a library for different projects.

Correct:

# Creating a virtual environment
python -m venv myenv
source myenv/bin/activate  # On Windows, use myenv\Scripts\activate

# Installing packages inside the virtual environment
pip install numpy

Now, by using virtual environments, each project has its own set of dependencies, avoiding conflicts and making everything easier to manage.

Final Words

These are just a few of the common mistakes I’ve seen myself and many others make while learning Python. The key takeaway here is that mistakes are part of the learning process, but recognizing them early will help you grow faster as a developer.

Keep experimenting, keep learning, and don’t be afraid to make mistakes—they’re just stepping stones toward mastering Python!

Thanks for reading, and feel free to reach out if you have any questions or need help along the way.

Stay curious and happy coding! 🚀

jack sparrow bye gif ~ tenor.com