Issue related to: Core Python
Issue link: https://www.reddit.com/r/learnpython/comments/g4pdik/when_and_why_would_you_use_none/
Issue:
Can someone explain to me when and why would you use None? Any help will be greatly appreciated. Thank you very much.
Explanation:
None in Python is an object which tells us there is no value.
You can see none being used when there is no return statement in a function:
def somefunction(): pass print(somefunction())
def somefunction():
pass
print(somefunction())
output
None
Interestingly, the print statement is a good example of a function that has no return statement:
print(print("Hello, World!"))
Output
Hello, World! None
Hello, World!
What is happening?
The inner print statement is executed first which is print("Hello, World!"). This gives us the output “Hello World!”
print("Hello, World!")
“Hello World!”
The outer print statement print() has nothing inside of its brackets so prints None
print()
Where can you use the None object?
There are a few areas of programming where None can be used
If you wanted to create a variable that stored nothing initially so that you can later fill the variable with information later
A good place that I can use this information is setting parameters in a function to None as follows:
def somefunction(variable=None): if variable is None: variable = "Hello World!" return variable print(somefunction())
def somefunction(variable=None):
if variable is None:
variable = "Hello World!"
return variable
In libraries and modules, you may see functions that have optional parameters being used.
Also note when we are working with the object None we should use is or is not when comparing a variable to None as opposed to == or != as this is good practice
is
is not
Why do we do this?
In Python, variables must have a value for it to exist and be recognised even if the value is nothing
Another place is to check if something is ‘not None’ which means True. This is known as a falsy such as the following:
result = None if result: print("Got a result!") else: print("No result.")
result = None
if result:
print("Got a result!")
else:
print("No result.")
This will check if the variable result has a value
In this case it will print:
No result
'NoneType' object has no attribute
This is known as an attribute error. If you see this traceback error: