AnyCompiler
← Blog

September 18, 2026

AttributeError: 'NoneType' object has no attribute 'X' — What It Means

This error means you called a method on a value that turned out to be None — usually because a function didn't return what you expected it to.

def find_first_even(numbers):
    for n in numbers:
        if n % 2 == 0:
            result = n

numbers = [1, 3, 5]
first_even = find_first_even(numbers)
print(first_even.bit_length())
Output
Traceback (most recent call last):
  File "script.py", line 8, in <module>
    print(first_even.bit_length())
AttributeError: 'NoneType' object has no attribute 'bit_length'

Why this happens

find_first_even() has no return statement at all — it just assigns to a local variable called result and never sends anything back. Every function without an explicit return implicitly returns None, no matter what happened inside it. first_even ends up as None, and calling .bit_length() on it fails.

The fix

def find_first_even(numbers):
    for n in numbers:
        if n % 2 == 0:
            return n
    return None

numbers = [1, 3, 5, 4]
first_even = find_first_even(numbers)
if first_even is not None:
    print(first_even.bit_length())
else:
    print("No even number found")
Output
3

return exits the function immediately with the value that was actually found. Checking if first_even is not None before using the result means the program handles the "nothing found" case on purpose, instead of crashing on it.

This exact shape of bug — a missing return causing a silent None — is common enough that it's worth checking first whenever you see 'NoneType' object has no attribute. See the Functions lesson in our free Python course for more on return values.