Fix - NameError: name 'true' is not defined in Python


Borislav Hadzhiev

Wed Apr 20 20222 min read


Photo by Raychan

Fix - NameError: name 'true' is not defined in Python #

The Python "NameError: name 'true' is not defined" occurs when we misspell the keyword True. To solve the error, make sure to capitalize the first letter of the keyword - True.

nameerror name true is not defined

Here is an example of how the error occurs.
# ⛔️ NameError: name 'true' is not defined. Did you mean: 'True'? t = true print(t)

To solve the error, we have to use a capital T when spelling the True keyword.
t = True print(t) # True

Names of variables, functions, classes and keywords are case-sensitive in Python.

The only other available boolean value is False (capital F).
t = True print(t) # 👉️ True f = False print(f) # 👉️ False
There are only 2 boolean values - True and False.

The type of the two boolean values is <class 'bool'>.
print(type(True)) # 👉️ <class 'bool'> print(type(False)) # 👉️ <class 'bool'>

Boolean objects in Python are implemented as a subclass of integers.
print(isinstance(True, int)) # 👉️ True print(isinstance(False, int)) # 👉️ True

Converting a True boolean value to an integer returns 1, whereas converting False returns 0.
print(int(True)) # 👉️ 1 print(int(False)) # 👉️ 0

You can use the not (negation) operator to invert a boolean value.
print(not True) # 👉️ False print(not False) # 👉️ True

You can use the built-in bool() function to convert any value to a boolean.
print(bool(1)) # 👉️ True print(bool('hello world')) # 👉️ True print(bool('')) # 👉️ False print(bool(0)) # 👉️ False

The bool() function takes a value and converts it to a boolean (True or False). If the provided value is falsy or omitted, then bool returns False, otherwise it returns True.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

The bool() function returns True if passed any non-falsy value.

Use the search field on my Home Page to filter through my more than 1,000 articles.