[Introduction to Python] How to judge authenticity with if statement (True and None)

Reference site: [Introduction to Python] How to determine authenticity with if statements (True and None)

[Introduction to Python] How to judge authenticity with if statement (True and None)

I often use if statements in python, but I would like to explain the occasional None. In the if statement, there is a condition to be compared, and it is determined whether the conditional statement is True or False. None is a concept close to False, and you can almost think of False = None. The difference is that False has the information that it is false (0), while None means "there is no data there" in the first place. I think it's difficult to understand from the words alone, so I'd like to give a concrete example.

How to handle True and False

Let's start with an example of True and False.

>>> a = 3
>>> if(a > 1):
...  print "a > 1"
a > 1

This is a program that displays "a> 1" if the value a is greater than 1. In the if statement, the truth of a> 1 is judged. Now that we have a = 3, the verdict is True. The point is that it only judges whether the judgment sentence is true or false, so the same thing can be done as follows.

>>> if(True):
...  print "True"
... 
True
>>> if(False):
...  print "True"
... else:
...  print "False"
... 
False

In this way, it is decided whether the judgment statement is True or False, and in the program, it is judged as 1 and 0 after all (True = 1, False = 0).

Just in case, let's make sure that True = 1 and False = 0.

>>> print 1+True
2
>>> print 1+False
1

As you can see, True and False correspond to 1 and zero.

How to handle None

Now let's talk about None, which is the main subject. Let's judge the if statement in the same way.

>>> print 1+True
2
>>> print 1+False
1

So far, it seems that you can think of False = None. Next, let's add.

>>> print 1+None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Hmmm, I got an error here. As mentioned at the beginning, None indicates that there is no data there, so there is no concept of a value. Therefore, you can see that it is impossible to add the values.

One example of when None appears is when using dictionary-type objects. An example of a dictionary type object is as follows.

test = {"red":"apple","blue":"sky","green":"forest"}

By associating red with apple, you can find apple by searching with the keyword red. The get function is useful when doing a keyword search here.

>>> print  test.get("red")
apple

Now, let's search for words (orange) that are not registered in this dictionary.

>>> print  test.get("orange")
None

That's where None came in. As you can see, None is used to indicate non-existent data. You can see that the meaning is a little different from False.

By the way, it is possible to access directly with test [“keyword”], but if you use a keyword that does not exist, you will get a KeyError as shown below.

>>> print  test["orange"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'orange'

If this happens, the program you wrote will be forcibly terminated in the middle, so it is recommended to use the get function that does not terminate.

Comparison using None

When using None logical comparisons, either "is" or "==" is fine.

>>> a = test.get("orange") #Put None in a
>>> if (a == None): # ==Logical comparison using
...  print "a == None"
a == None
>>> if (a is None): #Logical comparison using is
...  print "a is None"
... 
a is None

Both are working properly. To put it bluntly, "is" is recommended. Although it is a rare case, it seems that an error may occur with "==" (although the author has not encountered it yet). It is also said that "is" is faster in execution speed. The result of measuring the processing time using the timeit module for verification is shown.

>>> timeit.timeit("1 == None", number=10000000)
0.3263418674468994

What this means is "It took 0.33 seconds to measure the time required to compare" 1 == None "10000000 times."

In the same way, try "1 is None".

>>> timeit.timeit("1 is None", number=10000000)
0.19225311279296875

As you can see from this result, the processing time is about 0.19 / 0.33 to 60% faster when using is.

Recommended Posts

[Introduction to Python] How to judge authenticity with if statement (True and None)
[Introduction to Udemy Python3 + Application] 33. if statement
Difference in how to write if statement between ruby ​​and python
[Introduction to Python] How to get the index of data with a for statement
[Introduction to Python] How to iterate with the range function?
[Introduction to Udemy Python3 + Application] 68. Import statement and AS
Addition with Python if statement
[python] How to judge scalar
[Introduction to Python] How to write conditional branches using if statements
[Python] How to play with class variables with decorator and metaclass
[Introduction to Udemy Python3 + Application] 42. for statement, break statement, and continue statement
[Introduction to Udemy Python3 + Application] 39. while statement, continue statement and break statement
[Python] How to write an if statement in one sentence.
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to do Bulk Update with PyMySQL and notes [Python]
[Introduction to Python] How to get data with the listdir function
How to log in to AtCoder with Python and submit automatically
Python: How to use async with
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python] How to parse JSON
How to get started with Python
Hadoop introduction and MapReduce with Python
How to use FTP with Python
How to calculate date with python
[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to output a character string in a Print statement
How to import CSV and TSV files into SQLite with Python
How to make a surveillance camera (Security Camera) with Opencv and Python
[Introduction to Python] How to use the in operator in a for statement?
How to deal with errors when installing Python and pip with choco
How to use Python with Jw_cad (Part 2 Command explanation and operation)
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
How to build Python and Jupyter execution environment with VS Code
How to package and distribute Python scripts
[Introduction to Python] How to use class in Python?
How to install and use pandas_datareader [Python]
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Fractal to make and play with Python
How to work with BigQuery in Python
[Introduction to Python] Let's use foreach with Python
[Python] Introduction to CNN with Pytorch MNIST
How to do portmanteau test with python
How to display python Japanese with lolipop
python: How to use locals () and globals ()
How to enter Japanese with Python curses
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
[Python] How to deal with module errors
How to use is and == in Python
How to install python3 with docker centos
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
What to do if ipython and python start up with different versions
How to get the date and time difference in seconds with python
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] What is the method of repeating with the continue statement?
[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement
How to upload with Heroku, Flask, Python, Git (4)
[Python] Easy introduction to machine learning with python (SVM)
Introduction to Artificial Intelligence with Python 1 "Genetic Algorithm-Theory-"
How to read a CSV file with Python 2/3