Как проверить переменную на пустоту python
Перейти к содержимому

Как проверить переменную на пустоту python

  • автор:

Check if a Variable Is None in Python

Check if a Variable Is None in Python

A variable can store different values in Python. It can have integer, character, float, and other values. The None is a special keyword in Python. It does not mean that the value is zero, but the value is NULL or not available. None is a special object. Its type is called NoneType .

We sometimes encounter an exception that a variable is of NoneType . So we should know how to check if a variable is None or not.

In this tutorial, we will test if a variable is of type None in Python.

Use the is Keyword to Check if a Variable Is None in Python

The if statement can check for a condition in Python. To check whether a variable is None , we can use the is keyword. This keyword checks whether two variables refer to the same object.

Use the isinstance() Function to Check if a Variable Is None in Python

The isinstance() function can check whether an object belongs to a certain type or not. We can check if a variable is None by checking with type(None) .

It returns a tuple, whose first element is the variable whose value we want to check. The second element is True or False, whether the variable matches the required type or not.

Check if a Variable is Not Null in Python

This Python tutorial help to check whether a variable is null or not in Python, Python programming uses None instead of null. I will try different methods to check whether a Python variable is null or not. The None is an object in Python.

This quick tutorial help to choose the best way to handle not null in your Python application. It’s a kind of placeholder when a variable is empty, or to mark default parameters that you haven’t supplied yet. The None indicates missing or default parameters.

You can also check out other python tutorials:

  • The None is not 0.
  • The None is not as like False.
  • The None is not an empty string.
  • When you Comparing None to other values, This will always return False except None itself.

How To Check None is an Object

As earlier, I have stated that None is an Object. You can use the below code to define an object with None type and check what type is –

The above code will return the following output.

Option 1: Checking if the variable is not null

The following is the first option to check object is None using Python.

The output :
Var is not null

Option 2: Checking if the variable is not null

Let’s check whether a variable is null or not using if condition.

Output:

Var is not null

Option 3: How To Check the Variable is not null

We can also check python variable is null or not using not equal operator

How To Check If A Variable Is Null In Python

Check if a variable is Null in Python

To check if a variable is Null in Python, there are some methods we have effectively tested: the is operator, Use try/except and the non-equal operator. Follow the article to better understand.

Table of Contents

None and Null in Python

Nowaday, the keyword null is used in many programming languages to represent that the pointer is not pointing to any value. NULL is equivalent to 0. A newly created pointer points “miscellaneous” to a particular memory area. Assign the pointer to NULL to make sure it points to 0. Even though 0 is an invalid location, it’s easier to manage than when the pointer points to an area we don’t know.

In Python, there is no null but None .

None is a specific object indicating that the object is missing the presence of a value. The Python Null object is the singleton None .

In other words None in Python is similar to the Null keyword in other programming languages.

Check if a variable is Null in Python

Use the ‘is’ operator

The is operator is used to compare the memory addresses of two arguments. Everything in Python is an object, and each object has its memory address. The is operator checks if two variables refer to the same object in memory.

Example:

Output:

In the above example, I declared value = None and then used the is operator to check if value has None or not. If value is valid, then execute the if statement; otherwise execute the else statement.

Note:

Do not use the == operator to check for the value None . Because in some cases will lead to erroneous results.

Use try/except

Use try/except block to check if the variable is None .

Example:

The ‘if’ statement in ‘try’ to check variable ‘value’ exists and the value of ‘value’ is ‘none’

Output:

Use the non-equal operator

Another method to check if a variable is None is using the non-equal or != operator.

Example:

Output:

Summary

Here are ways to help you check if a variable is Null in Python. Or, if you have any questions about this topic, leave a comment below. I will answer your questions.

Maybe you are interested:

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

How to check if the string is empty?

Does Python have something like an empty string variable where you can do:

Regardless, what’s the most elegant way to check for empty string values? I find hard coding «» every time for checking an empty string not as good.

25 Answers 25

Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:

This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:

See the documentation on Truth Value Testing for other values that are false in Boolean contexts.

Mateen Ulhaq's user avatar

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

So you should use:

Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True .

The most elegant way would probably be to simply check if its true or falsy, e.g.:

However, you may want to strip white space because:

You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.

I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache’s StringUtils.isBlank or Guava’s Strings.isNullOrEmpty

This is what I would use to test if a string is either None OR Empty OR Blank:

And, the exact opposite to test if a string is not None NOR Empty NOR Blank:

I once wrote something similar to Bartek’s answer and javascript inspired:

The only really solid way of doing this is the following:

All other solutions have possible problems and edge cases where the check can fail.

len(myString) == 0 can fail if myString is an object of a class that inherits from str and overrides the __len__() method.

myString == "" and myString.__eq__("") can fail if myString overrides __eq__() and __ne__() .

"" == myString also gets fooled if myString overrides __eq__() .

myString is "" and "" is myString are equivalent. They will both fail if myString is not actually a string but a subclass of string (both will return False ). Also, since they are identity checks, the only reason why they work is because Python uses String Pooling (also called String Internment) which uses the same instance of a string if it is interned (see here: Why does comparing strings using either '==' or 'is' sometimes produce a different result?). And "" is interned from the start in CPython

The big problem with the identity check is that String Internment is (as far as I could find) that it is not standardised which strings are interned. That means, theoretically "" is not necessary interned and that is implementation dependant.

Also, comparing strings using is in general is a pretty evil trap since it will work correctly sometimes, but not at other times, since string pooling follows pretty strange rules.

Relying on the falsyness of a string may not work if the object overrides __bool__() .

The only way of doing this that really cannot be fooled is the one mentioned in the beginning: "".__eq__(myString) . Since this explicitly calls the __eq__() method of the empty string it cannot be fooled by overriding any methods in myString and solidly works with subclasses of str .

This is not only theoretical work but might actually be relevant in real usage since I have seen frameworks and libraries subclassing str before and using myString is "" might return a wrong output there.

That said, in most cases all of the mentioned solutions will work correctly. This is post is mostly academic work.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *