When and why would you use None?

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())

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

What is happening?

The inner print statement is executed first which is print("Hello, World!"). This gives us the output “Hello World!”

The outer print statement print() has nothing inside of its brackets so prints None

Where can you use the None object?

There are a few areas of programming where None can be used

  • Use None as default parameters or Variable
  • Test for None with is and is Not
  • Decipher NoneType errors

Use None as default parameters or Variable

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())

output

“Hello World!”

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 

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

Test for None with is and is Not

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.")

This will check if the variable result has a value

  • If it does it will print Got a result
  • Otherwise it will print No result.

In this case it will print:

No result

 Decipher NoneType errors

'NoneType' object has no attribute

This is known as an attribute error. If you see this traceback error:

  • look for the attribute that raised the error
  • figure out how that object got to be None and take the necessary steps to fix your code.