Python 101: 10 Mistakes Beginners Make

Jul 6, 2024

Discover 10 common mistakes python beginners make and learn how to avoid them. Perfect for new coders looking to improve their skills and avoid common pitfalls.

  1. Improper indentation

    Example:

    python
    def function():
    print("This is incorrectly indented")
        print("This is correctly indented")

    Explanation:

    Python uses indentation to define code blocks. Incorrect indentation can lead to IndentationErrors or unexpected behavior. In this example, he first print statement will cause an IndentationError.

  2. Mutable default arguments

    Example:

    python
    def add_item(item, list=[]):
        list.append(item)
        return list
     
    print(add_item(1))  # [1]
    print(add_item(2))  # [1, 2] (not [2] as might be expected)

    Explanation:

    Default arguments are evaluated only once at function definition. For mutable objects like lists, this can lead to unexpected results. Each call to the function will modify the same list object.

  3. Misusing global variables

    Example:

    python
    count = 0
     
    def increment():
        count += 1  # This will raise an UnboundLocalError
        print(count)
     
    increment()

    Explanation:

    Without the global keyword, Python treats count as a local variable. To modify a global variable within a function, you need to declare it as global:

    python
    count = 0
     
    def increment():
        global count
        count += 1
        print(count)
     
    increment()  # This will work correctly
  4. Ignoring PEP 8 style guidelines

    Example:

    python
    def badlyNamedFunction( arg1,arg2 ):
        x=arg1+arg2
        return x

    Explanation:

    This violates several PEP 8 guidelines. A PEP 8 compliant version would be:

    python
    def well_named_function(arg1, arg2):
        result = arg1 + arg2
        return result
  5. Not using virtual environments

    This is more of a development practice than a code exampleN. ot using virtual environments can lead to dependency conflicts between projects.

    Explanation:

    Virtual environments allow you to have isolated Python environments for different projects, each with its own dependencies and packages.

  6. Inefficient list comprehensions

    Example:

    python
    result = [i for i in range(1000) if i % 2 == 0 if i % 3 == 0]

    Explanation:

    While this works, it's less efficient than it could be. A more efficient version:

    python
    result = [i for i in range(0, 1000, 6)]
  7. Misunderstanding variable scope

    Example:

    python
    x = 10
    def func():
        print(x)
        x = 20
     
    func()  # This will raise an UnboundLocalError

    Explanation:

    When you assign to a variable in a function, it becomes local. The print statement tries to use the local x before it's assigned.

  8. Neglecting to close files or resources

    Example:

    python
    f = open('file.txt', 'w')
    f.write('Hello, World!')
    # File is not closed

    Explanation:

    This can lead to resource leaks. Better practice:

    python
    with open('file.txt', 'w') as f:
        f.write('Hello, World!')
    # File is automatically closed after the with block
  9. Using '==' instead of 'is' for singletons

    Example:

    python
    if x == None:  # Not ideal
        pass
     
    if x is None:  # Correct way
        pass

    Explanation:

    is checks for identity, which is more appropriate for singletons like None, True, and False.

  10. Modifying lists while iterating over them

    Example:

    python
    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
        if num % 2 == 0:
            numbers.remove(num)  # This can lead to unexpected results

    Explanation:

    Modifying a list while iterating over it can lead to skipped elements or runtime errors. A better approach:

    python
    numbers = [1, 2, 3, 4, 5]
    numbers = [num for num in numbers if num % 2 != 0]

Conclusion

Python is a powerful and flexible programming language, but like any tool, it requires proper understanding and careful use. The mistakes we've covered today are common pitfalls that both beginners and experienced programmers can fall into. By being aware of these issues, you can write more efficient, readable, and bug-free code.