None(null) в Python
В этой статье мы сосредоточимся на ключевом слове NONE в Python.

Что такое объект NONE в Python?
Python NONE — это объект из мира Python — объектно-ориентированного программирования. Идентично значению NULL в других языках программирования, таких как java или php.
Объект NONE относится к типу данных «NoneType» и, следовательно, не может рассматриваться как значение некоторых примитивных типов данных или логических значений.
Таким образом, мы можем присвоить NONE в качестве значения любой используемой переменной.
Рассмотрим форму входа в систему с серверным языком Python для подключения к базе данных. Если мы хотим проверить, сформировали ли мы соединение с указанной базой данных, мы можем назначить NONE объекту подключения к базе данных и проверить, является ли соединение защищенным или нет.
Синтаксис NONE
Объект NONE не соответствует нормам обычных типов данных.
Более того, присвоение переменной NONE показывает, что конкретная переменная представляет собой нулевое значение.
Реализация NONE на примерах
Давайте посмотрим на пример ниже. Здесь мы присвоили переменной ‘var’ значение NONE.
Пример 1. Назначение объекта NONE переменной Python
Когда мы пытаемся распечатать значение, хранящееся в переменной, отображается следующий результат. Таким образом, становится ясно, что объект NONE представляет значение NONE, которое можно рассматривать как значение NULL.
В приведенном ниже примере мы попытались проверить, представляет ли NONE эквивалентное логическое значение.
Пример: логическая проверка на объект NONE
Как видно ниже, результат — ЛОЖЬ. Таким образом, этот пример проясняет, что объект не похож на логические значения или значения объектов других примитивных типов.
Теперь давайте попробуем объединить примитивный тип и значения NoneType в структуры данных Python, такие как Set, Lists и т. д.
Пример NONE с Set
Когда мы передаем значения других примитивных типов вместе с NONE в структуры данных, такие как наборы, списки и т. д., Мы наблюдаем, что значение NONE возвращает NONE в качестве значения при их печати.
Python NULL – How to identify null values in Python?

Let’s understand what does Python null mean and what is the NONE type. In many programming languages, ‘null‘ is used to denote an empty variable, or a pointer that points to nothing. ‘null’ basically equals 0. Whereas in Python, there is no ‘null’ keyword available. Instead, ‘None‘ is used, which is an object, for this purpose.
What is Python null?
Whenever a function doesn’t have anything to return i.e., it does not contain the return statement, then the output will be None.
In simpler words, None keyword here is used to define a null variable or object. None is an object , and a data type of class NoneType.
NOTE:
Whenever we assign None to a variable, all the variables that are assigned to it point to the same object. No new instances are created.
In Python, unlike other languages, null is not just the synonym for 0, but is an object in itself.
Declaring null variables in Python
Null variables in python are not declared by default. That is, an undefined variable will not be the same as a null variable. To understand, all the variables in python come into existence by assignment only. Have a look at the code below :

The above code shows the difference between an undefined variable and a None variable.
How to check if a variable is none in Python?
You can check whether a variable is None or not either using ‘ is ‘ operator or ‘ == ‘ operator as shown below
- Using the ‘is’ operator
The above code will give None as output.
- Using the ‘==’ operator
The above code gives The value of variable is None as output.
Null in Python: Understanding Python's NoneType Object
If you have experience with other programming languages, like C or Java, then you’ve probably heard of the concept of null . Many languages use this to represent a pointer that doesn’t point to anything, to denote when a variable is empty, or to mark default parameters that you haven’t yet supplied. 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. As the null in Python, None is not defined to be 0 or any other value. In Python, None is an object and a first-class citizen!
In this tutorial, you’ll learn:
- What None is and how to test for it
- When and why to use None as a default parameter
- What None and NoneType mean in your traceback
- How to use None in type checking
- How null in Python works under the hood
Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.
Understanding Null in Python
None is the value a function returns when there is no return statement in the function:
When you call has_no_return() , there’s no output for you to see. When you print a call to it, however, you’ll see the hidden None it returns.
In fact, None so frequently appears as a return value that the Python REPL won’t print None unless you explicitly tell it to:
None by itself has no output, but printing it displays None to the console.
Interestingly, print() itself has no return value. If you try to print a call to print() , then you’ll get None :
It may look strange, but print(print(«. «)) shows you the None that the inner print() returns.
None also often used as a signal for missing or default parameters. For instance, None appears twice in the docs for list.sort :
Here, None is the default value for the key parameter as well as the type hint for the return value. The exact output of help can vary from platform to platform. You may get different output when you run this command in your interpreter, but it will be similar.
Using Python’s Null Object None
Often, you’ll use None as part of a comparison. One example is when you need to check and see if some result or parameter is None . Take the result you get from re.match . Did your regular expression match a given string? You’ll see one of two results:
- Return a Match object: Your regular expression found a match.
- Return a None object: Your regular expression did not find a match.
In the code block below, you’re testing if the pattern «Goodbye» matches a string:
Here, you use is None to test if the pattern matches the string «Hello, World!» . This code block demonstrates an important rule to keep in mind when you’re checking for None :
- Do use the identity operators is and is not .
- Do not use the equality operators == and != .
The equality operators can be fooled when you’re comparing user-defined objects that override them:
Here, the equality operator == returns the wrong answer. The identity operator is , on the other hand, can’t be fooled because you can’t override it.
Note: For more info on how to compare with None , check out Do’s and Dont’s: Python Programming Recommendations.
None is falsy, which means not None is True . If all you want to know is whether a result is falsy, then a test like the following is sufficient:
The output doesn’t show you that some_result is exactly None , only that it’s falsy. If you must know whether or not you have a None object, then use is and is not .
The following objects are all falsy as well:
- Empty lists
- Empty dictionaries
- Empty sets
- Empty strings
- 0
- False
For more on comparisons, truthy values, and falsy values, you can read about how to use the Python or operator, how to use the Python and operator, and how to use the Python not operator.
Declaring Null Variables in Python
In some languages, variables come to life from a declaration. They don’t have to have an initial value assigned to them. In those languages, the initial default value for some types of variables might be null . In Python, however, variables come to life from assignment statements. Take a look at the following code block:
Here, you can see that a variable with the value None is different from an undefined variable. All variables in Python come into existence by assignment. A variable will only start life as null in Python if you assign None to it.
Using None as a Default Parameter
Very often, you’ll use None as the default value for an optional parameter. There’s a very good reason for using None here rather than a mutable type such as a list. Imagine a function like this:
bad_function() contains a nasty surprise. It works fine when you call it with an existing list:
Here, you add ‘d’ to the end of the list with no problems.
But if you call this function a couple times with no starter_list parameter, then you start to see incorrect behavior:
The default value for starter_list evaluates only once at the time the function is defined, so the code reuses it every time you don’t pass an existing list.
The right way to build this function is to use None as the default value, then test for it and instantiate a new list as needed:
good_function() behaves as you want by making a new list with each call where you don’t pass an existing list. It works because your code will execute lines 2 and 3 every time it calls the function with the default parameter.
Using None as a Null Value in Python
What do you do when None is a valid input object? For instance, what if good_function() could either add an element to the list or not, and None was a valid element to add? In this case, you can define a class specifically for use as a default, while being distinct from None :
Here, the class DontAppend serves as the signal not to append, so you don’t need None for that. That frees you to add None when you want.
You can use this technique when None is a possibility for return values, too. For instance, dict.get returns None by default if a key is not found in the dictionary. If None was a valid value in your dictionary, then you could call dict.get like this:
Here you’ve defined a custom class KeyNotFound . Now, instead of returning None when a key isn’t in the dictionary, you can return KeyNotFound . That frees you to return None when that’s the actual value in the dictionary.
Deciphering None in Tracebacks
When NoneType appears in your traceback, it means that something you didn’t expect to be None actually was None , and you tried to use it in a way that you can’t use None . Almost always, it’s because you’re trying to call a method on it.
For instance, you called append() on my_list many times above, but if my_list somehow became anything other than a list, then append() would fail:
Here, your code raises the very common AttributeError because the underlying object, my_list , is not a list anymore. You’ve set it to None , which doesn’t know how to append() , and so the code throws an exception.
When you see a traceback like this in your code, look for the attribute that raised the error first. Here, it’s append() . From there, you’ll see the object you tried to call it on. In this case, it’s my_list , as you can tell from the code just above the traceback. Finally, figure out how that object got to be None and take the necessary steps to fix your code.
Checking for Null in Python
There are two type checking cases where you’ll care about null in Python. The first case is when you’re returning None :
This case is similar to when you have no return statement at all, which returns None by default.
The second case is a bit more challenging. It’s where you’re taking or returning a value that might be None , but also might be some other (single) type. This case is like what you did with re.match above, which returned either a Match object or None .
The process is similar for parameters:
You modify good_function() from above and import Optional from typing to return an Optional[Match] .
Taking a Look Under the Hood
In many other languages, null is just a synonym for 0 , but null in Python is a full-blown object:
This line shows that None is an object, and its type is NoneType .
None itself is built into the language as the null in Python:
Here, you can see None in the list of __builtins__ which is the dictionary the interpreter keeps for the builtins module.
None is a keyword, just like True and False . But because of this, you can’t reach None directly from __builtins__ as you could, for instance, ArithmeticError . However, you can get it with a getattr() trick:
When you use getattr() , you can fetch the actual None from __builtins__ , which you can’t do by simply asking for it with __builtins__.None .
Even though Python prints the word NoneType in many error messages, NoneType is not an identifier in Python. It’s not in builtins . You can only reach it with type(None) .
None is a singleton. That is, the NoneType class only ever gives you the same single instance of None . There’s only one None in your Python program:
Even though you try to create a new instance, you still get the existing None .
You can prove that None and my_None are the same object by using id() :
Here, the fact that id outputs the same integer value for both None and my_None means they are, in fact, the same object.
Note: The actual value produced by id will vary across systems, and even between program executions. Under CPython, the most popular Python runtime, id() does its job by reporting the memory address of an object. Two objects that live at the same memory address are the same object.
If you try to assign to None , then you’ll get a SyntaxError :
All the examples above show that you can’t modify None or NoneType . They are true constants.
You can’t subclass NoneType , either:
This traceback shows that the interpreter won’t let you make a new class that inherits from type(None) .
Conclusion
None is a powerful tool in the Python toolbox. Like True and False , None is an immutable keyword. As the null in Python, you use it to mark missing values and results, and even default parameters where it’s a much better choice than mutable types.
Now you can:
- Test for None with is and is not
- Choose when None is a valid value in your code
- Use None and its alternatives as default parameters
- Decipher None and NoneType in your tracebacks
- Use None and Optional in type hints
How do you use the null in Python? Leave a comment down in the comments section below!
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python's None: Null in Python
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About Wolf
Wolf is an avid Pythonista and writes for Real Python.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:




Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Переменные в Python
Переменные — важная часть любого языка программирования. Они позволяют хранить, использовать и передавать данные.
Переменные позволяют не только удобно манипулировать данными, но и разделять их на типы, с которыми можно работать по определённым правилам. В Python они подчиняются концепциям, используемым в других языках программирования, однако они также имеют особенности, например, тип явно не объявляется.
Создание и присвоение значений
Создание переменной в Python 3 отличается от других языков программирования. Её не нужно заранее объявлять, указывать её тип, она создается в момент присваивания значения.
Чтобы создать переменную, используется символ равенства «=». Слева от которого пишут наименование, а справа — значение нужного типа. Пример:
Динамическая типизация
Такое создание переменных возможно благодаря динамической типизации.
Множественное присваивание и обмен значениями
Python позволяет программисту присвоить одно и то же значение нескольким переменным:
Кроме того, в отличие от других языков программирования Python позволяет обменять значения двух переменных —
Такая операция возможна, потому что Python используется кортеж, в который помещает значения, чтобы можно было поменять их местами.
Имена
В именах переменных в Python 3 можно использовать только буквы, цифры и символы подчеркивания. Цифры можно использовать в любой части имени, кроме начала.
И если синтаксис накладывает на программиста мало ограничений, то IT сообщество требует «хороших» имён для переменных:
- Имя должно описывать назначение. Так как код может перечитываться и изменяться множество раз, названия переменных должны быть такими, чтобы по ним можно было понять, что она хранит и для чего используется.
- Не нужно использовать транслит. Если программист хочет создать переменную, хранящую возраст программиста, он должен писать не «vozrast», а «age». Это обусловлено тем, что английский — самый используемый язык в IT, название на английском поймут все, в любом случае, можно воспользоваться переводчиком.
- Приемлемая длина. Имя должно не только отражать суть, но и быть коротким, слишком длинные названия увеличивают объем кода и ухудшают его восприятие.
Для создания хороших имён используются следующие методы:
- CamelCase (верблюжий регистр): первое слово начинается с маленькой буквы, а следующие за ним с большой. В Python CamelCase принято использовать для имён классов. Например: WorkersOfFactory .
- Snake Case: имя состоит из слов, разделенных символом подчеркивания «_», каждое слово пишут с маленькой буквы, например, hello_world . В Python Snake Case используется для имён функций, модулей и переменных. Такой стиль записи воспринимается лучше, чем CamelCase. Кроме того, он имеет несколько вариаций, которые не используются в Python: таких как запись через дефис «-» (kind-of-animals) и запись каждого слова с большой буквы (Sorted-Array-Of-Names).
Зарезервированные имена (ключевые слова)
Полный список ключевых слов можно посмотреть, набрав в интерпретаторе Python команду: help(«keywords») .
Вывод в консоль
Чтобы вывести переменную на экран, используют функцию print(). С её помощью можно вывести значение одной или нескольких переменных в форматированном выводе. Есть несколько вариантов синтаксиса вывода:
- print(«<> — число, <> — слово».format(number, word)). Например, переменная number хранит значение 5, а word хранит «пять», тогда на экран выведется: «5 — число, пять — слово».
- Можно обойтись без использования .format, достаточно писать составные части вывода через запятую: print(number, » — число», word, » — слово»).
Пустая переменная
Переменная — это ссылка на какой-то объект, она не может не содержать совсем ничего. Если программист хочет сделать его пустой (условно пустой), он присваивает ей значение None .
None используется в случаях, когда значение не определено, не существует. И хотя он не эквивалентен какому-либо значению типа bool, строке или числу, он также является объектом.
При необходимости, можно проверить содержимое переменной следующим образом:
Может использоваться, например, когда мы в переменной храним указатель на открытый файл. И когда мы этот файл закрываем, то присваиваем указателю значение None. В дальнейшем можно проверять будет перед записью или чтением данных, является ли переменная пустой.
Области видимости
В Python есть глобальная и локальная область видимости. Объявление переменных в разных областях видимости помогает избежать пересечения имён, открывает программисту новые уровни взаимодействий между ними и делает код более безопасным, делая невозможным несанкционированный доступ к механизмам работы функций.
Глобальная область видимости — это тело исполняемого скрипта. К любой переменной, объявленной в ней, можно получить доступ из любой части программы, даже из другого модуля.
Чтобы получить доступ к глобальной переменной из функции, необходимо использовать ключевое слово global, оно показывает интерпретатору, что нужно использовать находящуюся в глобальной области видимости. Кроме того, если функция не находит в своём теле нужную переменную, она автоматически ищет её в глобальной области видимости скрипта и использует.
Локальная область видимости недоступна для редактирования из вне, любая переменная, объявленная внутри функции будет находиться в локальной области видимости, это позволяет использовать одно и то же имя много раз в одной программе, защитить функцию от ненужных изменений и упростить написание кода.
В 3 версии Python было добавлено ключевое слово nonlocal . Оно позволяет получить доступ к переменной из локальной области видимости функции, при условии, что программист пытается получить доступ из другой вложенной функции. Пример:
Удаление
Для удаления переменной в Python 3 можно воспользоваться функцией del() , в качестве аргумента в которую нужно передать её имя. Пример:
Заключение
Python даёт программисту все необходимое для работы с переменными, он предоставляет и такие инструменты, которых нет в других языках программирования, например, обмен значений.
Python делает работу с переменными очень простой, он позволяет не объявлять их типы, присваивать уже существующей значение другого типа и поддерживает работу с областями видимости.