Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a variable is null in python [duplicate]

Tags:

python

val = ""  del val  if val is None:     print("null") 

I ran above code, but got NameError: name 'val' is not defined.

How to decide whether a variable is null, and avoid NameError?

like image 432
Zephyr Guo Avatar asked May 12 '17 09:05

Zephyr Guo


People also ask

How do you check if a value is None in Python?

To check none value in Python, use the is operator. The “is” is a built-in Python operator that checks whether both the operands refer to the same object or not.

How do you check if a list is empty in Python?

In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.

How do you handle null in 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. In Python, to represent an absence of the value, you can use a None value (types.

What is the difference between None and null in Python?

null is often defined to be 0 in those languages, but null in Python is different. Python uses the keyword None to define null objects and variables. While None does serve some of the same purposes as null in other languages, it's another beast entirely.


1 Answers

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:     pass  # val exists and is None 

To check if name exists:

try:     val except NameError:     pass  # val does not exist at all 
like image 199
Łukasz Rogalski Avatar answered Sep 24 '22 23:09

Łukasz Rogalski