Python if null then value

In C#, I can say x ?? "", which will give me x if x is not null, and the empty string if x is null. I've found it useful for working with databases.

Is there a way to return a default value if Python finds None in a variable?

asked Dec 4, 2012 at 19:42

1

You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).

Tenzin Chemi

4,3312 gold badges25 silver badges31 bronze badges

answered Dec 4, 2012 at 19:44

starhuskerstarhusker

6,0683 gold badges18 silver badges12 bronze badges

16

return "default" if x is None else x

try the above.

answered Dec 4, 2012 at 19:45

brent.paynebrent.payne

4,8993 gold badges21 silver badges17 bronze badges

6

You can use a conditional expression:

x if x is not None else some_value

Example:

In [22]: x = None

In [23]: print x if x is not None else "foo"
foo

In [24]: x = "bar"

In [25]: print x if x is not None else "foo"
bar

answered Dec 4, 2012 at 19:43

Python if null then value

Ashwini ChaudharyAshwini Chaudhary

236k55 gold badges443 silver badges495 bronze badges

You've got the ternary syntax x if x else '' - is that what you're after?

answered Dec 4, 2012 at 19:44

Python if null then value

Jon ClementsJon Clements

134k31 gold badges240 silver badges273 bronze badges

4

Looking for Null in Python? You’ll not find it. However, Python has None, which is the closest equivalent of Null from other programming languages. Let’s explore Python’s None object.

If you are familiar with other programming languages like Java, JavaScript, or PHP, you may wonder if Python has a Null value that works the same as Null in other languages.

The short answer is that there is no Null in Python, but there is the None object that Python programmers use to define null objects and variables. Still, it’s important to understand that while None does serve some of the same purposes as Null in other languages, it is still very different from the Null you might be used to.

The special Null value used in many programming languages (e.g. C, Java, JavaScript, PHP) denotes an empty pointer, an unknown value, or a variable that has not been initialized yet. Often, Null is defined to be 0 in these languages. In Python, None may serve the same purposes as Null but it is not defined to be 0 or any other value. None in Python is an object and a first-class citizen.

In this article, I’ll discuss what this implies and how you can use Python’s None effectively. Then, you can start practicing Python right away with our Python Basics. Part 1 course, which covers key entry-level concepts with 95 interactive exercises.

None in Python: A Deep Dive

Let’s start by identifying a few things that None is not. It is not the same as False, even though the None object is falsy (e.g. evaluates to false in a Boolean operation). Also, None is not a zero or an empty string. Any comparison with the None object returns False, except for comparing None with itself.

To help you get an understanding of what the Python None object is, we’ll go through a few use cases, including:

  • Assigning None to a variable.
  • Testing for None.
  • Getting None as a function output.
  • Using None as a default parameter.

Assigning a None Object to a Variable

Some programming languages allow for introducing new variables through declaration without an explicitly assigned initial value. The default initial value in such cases is often Null.

In Python, things work very differently. To introduce a new variable, you need to assign a certain value to it, which can be a None object. If you don’t assign any value to a variable, it is considered undefined and you’ll get a NameError when referring to it.

For example, let’s try to print an undefined variable vs. a variable that was assigned a None object.

print (employees)

Output:

NameError Traceback (most recent call last)
 in ()
----> 1 print (employees)
NameError: name 'employees' is not defined

employees = None
print (employees)

Output:

None

However, a None object cannot be modified, referred to with Python methods, or used with operators. If you refer to a None object in such cases, you’ll get a TypeError. For example:

employees = None
print(employees + 1)

Output:

TypeError Traceback (most recent call last)
 in ()
----> 1 print(employees + 1)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

As you can see in the traceback, the error is caused by referring to a None object.

Checking If a Variable Is None

You can check if a variable is assigned None by using the is None and is not None operators.

employees = None
if employees is None:
    print("It is a None object.")
else:
    print("It is not a None object ")

Output:

It is a None object.

Note that it’s important to use the identity operators (like is None and is not None) with the None objects in Python and not the equality operators like == and !=. The issue is that the equality operators can output wrong results when you’re comparing user-defined objects that override them. Here is an example:

class EquityVsIdentity():
    def __eq__ (self, other):
        return True

check = EquityVsIdentity()
print(check == None)
print(check is None)

Output:

True
False

Here, the equality operator (“==”) returns the wrong answer because it was overridden by a user-defined object, while the identity operator (is) returns the correct result because it cannot be overridden.

Another interesting thing to note is that as a None object is falsy, you can simply use an if statement to check if the variable is None or not.

employees = None
if employees:
    print("It is not a None object.")
else:
    print("It is a None object.")

Output:

It is a None object.

None as a function output

First of all, None is the value returned when there is no return statement in a function. Let’s create a function that doesn’t return any value and check its output:

def no_return():
    pass

print(no_return())

Output:

None

As you can see, the function above doesn’t explicitly return a value. Python supplies an implicit return statement with None as the return value. Check out this guide on defining a function in Python to learn more about cases in which you may want your function to do some operations without returning any value.

Some functions return an actual object when they have a real result and None when there is no result. The re package for processing regular expressions in Python has a number of such functions.

You can check if the function returned the value by comparing the result with None. For example, let’s explore the output of the search() function of the re package when there is no match:

import re

languages = "She speaks English, French, German, and Norwegian."
match = re.search("Spanish", languages)

if match is None:
    print("She doesn't speak this language.")
else:
    print("She speaks this language.")

Output:

Here, Spanish is not among the languages this person speaks. Thus, when searching for “Spanish”, we got a None object. We have checked and confirmed that the output of the search() function is None in this case.

None as a Default Value for an Optional Parameter

Finally, None is very often used as the default value for an optional parameter of a function, especially when you need to deal with a mutable data type such as a list. If you set the default value of a parameter to a list, this list will be updated in all subsequent function calls that do not specify the corresponding optional parameter – while you usually want a new empty list each time.

It will be clearer after an example. We’ll start by creating a function that uses a list as the default value for an optional parameter:

def function_with_list (element, start=[]):
    start.insert(0, element)
    return start

employees = ['employee A', 'employee B', 'employee C']
function_with_list('employee D', employees)

Output:

['employee D', 'employee A', 'employee B', 'employee C']

As you see, we have created a function that places a new element at position #1 on the list. It performs well when we provide the start parameter. However, if we do not provide this optional parameter, we start seeing incorrect behavior with every new call to the function:

function_with_list('employee D')

Output:

['employee D']

function_with_list('employee E')

Output:

['employee E', 'employee D']

function_with_list('employee F')

Output:

['employee F', 'employee E', 'employee D']

As list is a mutable object type, we get a list updated after each function call when we don’t pass an existing list.

If you want to have a new list with each call, consider using a None object as a default parameter:

def function_with_none(element, start=None):
    if start is None:
        start = []
    start.insert(0, element)
    return start

employees = ['employee A', 'employee B', 'employee C']
function_with_none('employee D', employees)

Output:

['employee D',
 'employee A',
 'employee B',
 'employee C']

In this function, we check if a starting list is None; if it is, we initiate a new list. This ensures that we get the correct behavior when we don’t provide a starting list to the function.

function_with_none('employee D')

Output:

['employee D']

function_with_none('employee E')

Output:

['employee E']

function_with_none('employee F')

Output:

['employee F']

Now we get the correct output, no matter how many times we call the function. This is just one example of how a None object can be effectively used as a default value for an optional parameter.

Let’s Practice None in Python!

Even though Python doesn’t have a Null value like you might be used to, it has all the necessary tools to deal with null values. Moreover, due to Python’s simple and easy-to-follow syntax, you can learn Python basics very quickly – likely in less than a month. The key is to take a structured approach to studying and do a lot of coding.

If you are very new to Python, I recommend starting with the Python Basics Part 1 course. In its 95 interactive exercises, you’ll learn how to accept input from users, use variables and math in Python, and write if statements, loops, and functions. You’ll also get a better understanding of the None type. You can read more about this course in this overview article.

When you are ready to learn more, check out the Learn Programming with Python track. It includes five interactive courses with hundreds of coding challenges. After finishing this learning track, you’ll have a good understanding of Python data structures, including lists, sets, dictionaries, and tuples. You’ll also be comfortable using key built-in algorithms and functions, like the ones used for searching and sorting in Python.

Thanks for reading, and happy learning!

How do you check if the value is a null value Python?

Use the is operator to check if a variable is null in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None . Copied! Note that there isn't a null value in Python.

IS null or == null Python?

In Python, there is no such value as null. Instead, Python has None that represents null.

IS null in if statement Python?

There's no null in Python; instead there's None . As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

How do you give a value to null in Python?

In order to define a null variable, you can use the None keyword. Note: The None keyword refers to a variable or object that is empty or has no value. It is Python's way of defining null values.