Understand the None Value
In this step, you will learn about the None
value in Python. None
is a special constant in Python that represents the absence of a value or a null value. It is often used to indicate that a variable has not been assigned a value or that a function does not return a value.
Let's start by creating a Python file named none_example.py
in your ~/project
directory using the VS Code editor.
## ~/project/none_example.py
def greet(name):
if name:
return "Hello, " + name
else:
return None
result = greet("Alice")
print(result)
result = greet("")
print(result)
In this code:
- We define a function
greet
that takes a name
as input.
- If
name
is not empty, the function returns a greeting string.
- If
name
is empty, the function returns None
.
- We call the
greet
function with "Alice" and an empty string "" and print the results.
Now, run the Python script:
python ~/project/none_example.py
You should see the following output:
Hello, Alice
None
As you can see, when we call greet
with "Alice", it returns "Hello, Alice". When we call it with an empty string, it returns None
, which is then printed to the console.
None
is not the same as 0, False, or an empty string. It is a distinct value that represents the absence of a value.
You can assign None
to a variable:
## ~/project/none_example2.py
x = None
print(x)
Run the script:
python ~/project/none_example2.py
Output:
None
You can also use None
as a default argument value in a function:
## ~/project/none_example3.py
def my_function(arg=None):
if arg is None:
print("No argument was passed.")
else:
print("Argument:", arg)
my_function()
my_function("Hello")
Run the script:
python ~/project/none_example3.py
Output:
No argument was passed.
Argument: Hello
In this example, if no argument is provided when calling my_function
, arg
will default to None
.