Typical Python Bugs And How To Correct Them
Typical Python Mistakes
Below are some typical Python bugs or mistakes that could be used as interview questions. You can find detailed explanation and how to correct them.
-
Mutable Default Arguments:
Mistake: Using mutable objects (e.g., lists, dictionaries) as default arguments in a function.
def add_item(item, items=[]): items.append(item) return items result = add_item('apple') print(result) # Output: ['apple'] result = add_item('banana') print(result) # Output: ['apple', 'banana']
Explanation: Default arguments are evaluated only once when the function is defined, not each time the function is called. In this case, the mutable list
items
is shared across all function calls.Correction: Use an immutable default argument (e.g.,
None
) and create a new object inside the function.def add_item(item, items=None): if items is None: items = [] items.append(item) return items
-
Overusing Global Variables:
Mistake: Relying heavily on global variables.
total = 0 def add_to_total(value): global total total += value
Explanation: Using global variables makes code less modular, harder to test, and can lead to unintended side effects.
Correction: Pass values as arguments and return results from functions instead of using global variables.
def add_to_total(total, value): return total + value
-
Shadowing Built-in Functions:
Mistake: Defining variables or functions with names that shadow Python's built-in functions or types.
list = [1, 2, 3] def print(value): print("Value:", value)
Explanation: Shadowing built-in names can lead to confusion and unexpected behavior.
Correction: Use different variable names to avoid shadowing built-in names.
my_list = [1, 2, 3] def custom_print(value): print("Value:", value)
-
Indentation Errors:
Mistake: Inconsistent or incorrect indentation.
def some_function(): print("Indented incorrectly") print("Not aligned properly")
Explanation: Indentation errors can result in syntax errors and affect the code's structure.
Correction: Ensure consistent and proper indentation according to Python's indentation rules.
def some_function(): print("Correctly indented") print("Aligned properly")
-
Infinite Recursion:
Mistake: Writing a recursive function without a base case, leading to infinite recursion.
def factorial(n): return n * factorial(n - 1)
Explanation: This will lead to a "RecursionError: maximum recursion depth exceeded" and may crash the program.
Correction: Include a base case to terminate the recursion.
def factorial(n): if n == 0: return 1 return n * factorial(n - 1)
-
Using
==
for Object Comparison:Mistake: Using
==
to compare objects for equality when you want to check if they are the same object.list1 = [1, 2, 3] list2 = [1, 2, 3] if list1 == list2: print("Equal")
Explanation:
==
compares the values of objects, not whether they are the same object in memory.Correction: Use
is
to check if two variables reference the same object.if list1 is list2: print("Same object")
-
Unintended Type Conversions:
Mistake: Unexpected type conversions, especially when working with integers and floats.
result = 5 / 2 # Result is 2.5, not 2
Explanation: Python performs float division when dividing integers, which may not be what you expect.
Correction: Use
//
for integer division if needed.result = 5 // 2 # Result is 2 (integer division)
-
Ignoring Exceptions:
Mistake: Ignoring or catching exceptions without proper handling.
try: result = 1 / 0 except ZeroDivisionError: pass # Silently ignoring the error
Explanation: Ignoring exceptions can lead to unexpected program behavior.
Correction: Handle exceptions appropriately, whether by logging, providing a default value, or raising a more informative error.
try: result = 1 / 0 except ZeroDivisionError as e: print("Error:", e)
-
Mixing Tabs and Spaces:
Mistake: Mixing tabs and spaces for indentation.
def some_function(): \tprint("Using tabs") \tprint("and spaces")
Explanation: Mixing tabs and spaces can lead to indentation errors and should be avoided.
Correction: Use consistent indentation (preferably spaces) throughout the code.
def some_function(): print("Using spaces") print("only")
-
Comparing Floating-Point Numbers:
Mistake: Directly comparing floating-point numbers for equality.
a = 0.1 + 0.2 b = 0.3 if a == b: print("Equal")
Explanation: Due to floating-point precision, direct comparisons can lead to unexpected results.
Correction: Use math libraries (e.g.,
math.isclose
) to compare floating-point numbers within an acceptable tolerance.import math a = 0.1 + 0.2 b = 0.3 if math.isclose(a, b): print("Approximately equal")
Hope these will help you :)