How do I go about printin a NoneType object in Python?
# score can be a NonType object
logging.info("NEW_SCORE : "+score)
Also why is that sometime I see a comma instead of the + above?
One way to avoid this error is to check before iterating on an object if that object is None or not. In addition, another way to handle this error: Python nonetype object is not iterable is to write the for loop in try-except block. Thirdly, it is to explicitly assign an empty list to the variable if it is None .
The TypeError: 'NoneType' object is not iterable error is raised when you try to iterate over an object whose value is equal to None. To solve this error, make sure that any values that you try to iterate over have been assigned an iterable object, like a string or a list.
What does %d do in Python? The %d operator is used as a placeholder to specify integer values, decimals, or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified.
NoneType in Python is a data type that simply shows that an object has no value/has a value of None . You can assign the value of None to a variable but there are also methods that return None .
The best approach is:
logging.info("NEW_SCORE: %s", score)
In most contexts, you'd have to use a %
operator between the format string on the left and the value(s) on the right (in a tuple, if more than one). But the logging
functions are special: you pass the format string as the first argument, then, one after the other, just as many arguments as needed to match the number of %s
&c formatting markers in the format, and the logging
functions will use the formatting operator %s
as appropriate if and only if necessary -- so you don't incur any runtime overhead if your current logging level is such that, e.g., logging.info
is not actually going to be shown.
Forget str
calls and +
-based string concatenation anyway -- even without logging
's specials, %
-formatting is really the way to go (in Python 2.6 or earlier; in 2.6 or later, you should also consider strings' format
method, allowing clearer and more readable expression of what amounts to the same functionality).
logging.info("NEW_SCORE : " + str(score))
Proof by Python interpreter:
>>> x = None
>>> "x: " + x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'NoneType' objects
>>> "x: " + str(x)
'x: None'
QED
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With